BlueGit

ict rusty-teams

fix(chat): copy image works in other Windows apps, image right-click menu

- clipboard writes PNG plus CF_DIB on Windows; gpui only wrote PNG, which Paint, Office and Teams ignore
- right-click on a chat image: Copy image, Download, Share (forward), as in Teams
- viewer copy button uses the same writer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-15 · 6 weeks ago

Hash
9590d0f0e0300034567ae8dcc4e3e3267c11aebf
Parent
ae1d64c3
10 files changed +282 −47
crates/app-base/Cargo.toml +3 −0
@@ -39,6 +39,9 @@ windows = { version = "0.62", features = [
39 39 "Win32_Graphics_Dwm",
40 40 "Win32_Graphics_Gdi",
41 41 "Win32_Security",
42 "Win32_System_DataExchange",
43 "Win32_System_Memory",
44 "Win32_System_Ole",
42 45 "Win32_Storage_FileSystem",
43 46 "Win32_System_Com",
44 47 "Win32_System_Pipes",
@@ -39,6 +39,9 @@ windows = { version = "0.62", features = [
39 "Win32_Graphics_Dwm",
39 "Win32_Graphics_Dwm",
40 "Win32_Graphics_Gdi",
40 "Win32_Graphics_Gdi",
41 "Win32_Security",
41 "Win32_Security",
42 "Win32_System_DataExchange",
43 "Win32_System_Memory",
44 "Win32_System_Ole",
42 "Win32_Storage_FileSystem",
45 "Win32_Storage_FileSystem",
43 "Win32_System_Com",
46 "Win32_System_Com",
44 "Win32_System_Pipes",
47 "Win32_System_Pipes",
crates/app-base/src/image_clipboard.rs added +143 −0
@@ -0,0 +1,143 @@
1 use std::io::Cursor;
2
3 use gpui_kit::{App, ClipboardItem, Image, ImageFormat};
4
5 const DIB_HEADER_SIZE: u32 = 40;
6 const DIB_BITS_PER_PIXEL: u16 = 32;
7
8 /// Windows apps such as Paint, Office and Teams only paste `CF_DIB`, which gpui does not write.
9 pub struct ClipboardImage {
10 png: Vec<u8>,
11 #[cfg(windows)]
12 dib: Vec<u8>,
13 }
14
15 impl ClipboardImage {
16 pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
17 let decoded = image::load_from_memory(bytes).ok()?;
18 let png = if image::guess_format(bytes).ok()? == image::ImageFormat::Png {
19 bytes.to_vec()
20 } else {
21 let mut png = Vec::new();
22 decoded
23 .write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png)
24 .ok()?;
25 png
26 };
27 Some(ClipboardImage {
28 png,
29 #[cfg(windows)]
30 dib: dib_bytes(&decoded.into_rgba8()),
31 })
32 }
33
34 pub fn write(self, cx: &mut App) {
35 #[cfg(windows)]
36 if windows_clipboard::write(&self.png, &self.dib).is_ok() {
37 return;
38 }
39 cx.write_to_clipboard(ClipboardItem::new_image(&Image::from_bytes(
40 ImageFormat::Png,
41 self.png,
42 )));
43 }
44 }
45
46 pub fn dib_bytes(rgba: &image::RgbaImage) -> Vec<u8> {
47 let (width, height) = rgba.dimensions();
48 let pixel_bytes = width as usize * height as usize * 4;
49 let mut dib = Vec::with_capacity(DIB_HEADER_SIZE as usize + pixel_bytes);
50 dib.extend_from_slice(&DIB_HEADER_SIZE.to_le_bytes());
51 dib.extend_from_slice(&(width as i32).to_le_bytes());
52 dib.extend_from_slice(&(height as i32).to_le_bytes());
53 dib.extend_from_slice(&1u16.to_le_bytes());
54 dib.extend_from_slice(&DIB_BITS_PER_PIXEL.to_le_bytes());
55 dib.extend_from_slice(&0u32.to_le_bytes());
56 dib.extend_from_slice(&(pixel_bytes as u32).to_le_bytes());
57 dib.extend_from_slice(&[0; 16]);
58 for row in rgba.rows().rev() {
59 for pixel in row {
60 let [red, green, blue, alpha] = pixel.0;
61 let on_white = |channel: u8| {
62 let alpha = u16::from(alpha);
63 ((u16::from(channel) * alpha + 255 * (255 - alpha) + 127) / 255) as u8
64 };
65 dib.extend_from_slice(&[on_white(blue), on_white(green), on_white(red), 255]);
66 }
67 }
68 dib
69 }
70
71 #[cfg(windows)]
72 mod windows_clipboard {
73 use windows::Win32::Foundation::HANDLE;
74 use windows::Win32::System::DataExchange::{
75 CloseClipboard, EmptyClipboard, OpenClipboard, RegisterClipboardFormatW, SetClipboardData,
76 };
77 use windows::Win32::System::Memory::{GMEM_MOVEABLE, GlobalAlloc, GlobalLock, GlobalUnlock};
78 use windows::Win32::System::Ole::CF_DIB;
79 use windows::core::{Owned, Result, w};
80
81 pub fn write(png: &[u8], dib: &[u8]) -> Result<()> {
82 unsafe {
83 OpenClipboard(None)?;
84 let result = (|| {
85 EmptyClipboard()?;
86 set_bytes(png, RegisterClipboardFormatW(w!("PNG")))?;
87 set_bytes(dib, u32::from(CF_DIB.0))
88 })();
89 CloseClipboard().ok();
90 result
91 }
92 }
93
94 unsafe fn set_bytes(data: &[u8], format: u32) -> Result<()> {
95 unsafe {
96 let global = Owned::new(GlobalAlloc(GMEM_MOVEABLE, data.len())?);
97 let pointer = GlobalLock(*global);
98 if pointer.is_null() {
99 return Err(windows::core::Error::from_win32());
100 }
101 std::ptr::copy_nonoverlapping(data.as_ptr(), pointer.cast(), data.len());
102 GlobalUnlock(*global).ok();
103 SetClipboardData(format, Some(HANDLE(global.0)))?;
104 std::mem::forget(global);
105 }
106 Ok(())
107 }
108 }
109
110 #[cfg(test)]
111 mod tests {
112 use super::*;
113 use image::{Rgba, RgbaImage};
114
115 #[test]
116 fn dib_is_a_bottom_up_bgra_bitmap_on_white_behind_a_40_byte_header() {
117 let mut rgba = RgbaImage::new(2, 2);
118 rgba.put_pixel(0, 0, Rgba([10, 20, 30, 255]));
119 rgba.put_pixel(1, 1, Rgba([40, 50, 60, 128]));
120 let dib = dib_bytes(&rgba);
121 assert_eq!(dib.len(), 40 + 16);
122 assert_eq!(&dib[0..4], &40u32.to_le_bytes());
123 assert_eq!(&dib[4..8], &2i32.to_le_bytes());
124 assert_eq!(&dib[8..12], &2i32.to_le_bytes());
125 assert_eq!(&dib[14..16], &32u16.to_le_bytes());
126 assert_eq!(&dib[44..48], &[157, 152, 147, 255]);
127 assert_eq!(&dib[48..52], &[30, 20, 10, 255]);
128 }
129
130 #[test]
131 fn a_jpeg_is_kept_as_png_for_the_clipboard() {
132 let mut jpeg = Vec::new();
133 image::DynamicImage::ImageRgba8(RgbaImage::from_pixel(3, 1, Rgba([1, 2, 3, 255])))
134 .to_rgb8()
135 .write_to(&mut Cursor::new(&mut jpeg), image::ImageFormat::Jpeg)
136 .unwrap();
137 let image = ClipboardImage::from_bytes(&jpeg).unwrap();
138 assert_eq!(
139 image::guess_format(&image.png).unwrap(),
140 image::ImageFormat::Png
141 );
142 }
143 }
@@ -0,0 +1,143 @@
1use std::io::Cursor;
2
3use gpui_kit::{App, ClipboardItem, Image, ImageFormat};
4
5const DIB_HEADER_SIZE: u32 = 40;
6const DIB_BITS_PER_PIXEL: u16 = 32;
7
8/// Windows apps such as Paint, Office and Teams only paste `CF_DIB`, which gpui does not write.
9pub struct ClipboardImage {
10 png: Vec<u8>,
11 #[cfg(windows)]
12 dib: Vec<u8>,
13}
14
15impl ClipboardImage {
16 pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
17 let decoded = image::load_from_memory(bytes).ok()?;
18 let png = if image::guess_format(bytes).ok()? == image::ImageFormat::Png {
19 bytes.to_vec()
20 } else {
21 let mut png = Vec::new();
22 decoded
23 .write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png)
24 .ok()?;
25 png
26 };
27 Some(ClipboardImage {
28 png,
29 #[cfg(windows)]
30 dib: dib_bytes(&decoded.into_rgba8()),
31 })
32 }
33
34 pub fn write(self, cx: &mut App) {
35 #[cfg(windows)]
36 if windows_clipboard::write(&self.png, &self.dib).is_ok() {
37 return;
38 }
39 cx.write_to_clipboard(ClipboardItem::new_image(&Image::from_bytes(
40 ImageFormat::Png,
41 self.png,
42 )));
43 }
44}
45
46pub fn dib_bytes(rgba: &image::RgbaImage) -> Vec<u8> {
47 let (width, height) = rgba.dimensions();
48 let pixel_bytes = width as usize * height as usize * 4;
49 let mut dib = Vec::with_capacity(DIB_HEADER_SIZE as usize + pixel_bytes);
50 dib.extend_from_slice(&DIB_HEADER_SIZE.to_le_bytes());
51 dib.extend_from_slice(&(width as i32).to_le_bytes());
52 dib.extend_from_slice(&(height as i32).to_le_bytes());
53 dib.extend_from_slice(&1u16.to_le_bytes());
54 dib.extend_from_slice(&DIB_BITS_PER_PIXEL.to_le_bytes());
55 dib.extend_from_slice(&0u32.to_le_bytes());
56 dib.extend_from_slice(&(pixel_bytes as u32).to_le_bytes());
57 dib.extend_from_slice(&[0; 16]);
58 for row in rgba.rows().rev() {
59 for pixel in row {
60 let [red, green, blue, alpha] = pixel.0;
61 let on_white = |channel: u8| {
62 let alpha = u16::from(alpha);
63 ((u16::from(channel) * alpha + 255 * (255 - alpha) + 127) / 255) as u8
64 };
65 dib.extend_from_slice(&[on_white(blue), on_white(green), on_white(red), 255]);
66 }
67 }
68 dib
69}
70
71#[cfg(windows)]
72mod windows_clipboard {
73 use windows::Win32::Foundation::HANDLE;
74 use windows::Win32::System::DataExchange::{
75 CloseClipboard, EmptyClipboard, OpenClipboard, RegisterClipboardFormatW, SetClipboardData,
76 };
77 use windows::Win32::System::Memory::{GMEM_MOVEABLE, GlobalAlloc, GlobalLock, GlobalUnlock};
78 use windows::Win32::System::Ole::CF_DIB;
79 use windows::core::{Owned, Result, w};
80
81 pub fn write(png: &[u8], dib: &[u8]) -> Result<()> {
82 unsafe {
83 OpenClipboard(None)?;
84 let result = (|| {
85 EmptyClipboard()?;
86 set_bytes(png, RegisterClipboardFormatW(w!("PNG")))?;
87 set_bytes(dib, u32::from(CF_DIB.0))
88 })();
89 CloseClipboard().ok();
90 result
91 }
92 }
93
94 unsafe fn set_bytes(data: &[u8], format: u32) -> Result<()> {
95 unsafe {
96 let global = Owned::new(GlobalAlloc(GMEM_MOVEABLE, data.len())?);
97 let pointer = GlobalLock(*global);
98 if pointer.is_null() {
99 return Err(windows::core::Error::from_win32());
100 }
101 std::ptr::copy_nonoverlapping(data.as_ptr(), pointer.cast(), data.len());
102 GlobalUnlock(*global).ok();
103 SetClipboardData(format, Some(HANDLE(global.0)))?;
104 std::mem::forget(global);
105 }
106 Ok(())
107 }
108}
109
110#[cfg(test)]
111mod tests {
112 use super::*;
113 use image::{Rgba, RgbaImage};
114
115 #[test]
116 fn dib_is_a_bottom_up_bgra_bitmap_on_white_behind_a_40_byte_header() {
117 let mut rgba = RgbaImage::new(2, 2);
118 rgba.put_pixel(0, 0, Rgba([10, 20, 30, 255]));
119 rgba.put_pixel(1, 1, Rgba([40, 50, 60, 128]));
120 let dib = dib_bytes(&rgba);
121 assert_eq!(dib.len(), 40 + 16);
122 assert_eq!(&dib[0..4], &40u32.to_le_bytes());
123 assert_eq!(&dib[4..8], &2i32.to_le_bytes());
124 assert_eq!(&dib[8..12], &2i32.to_le_bytes());
125 assert_eq!(&dib[14..16], &32u16.to_le_bytes());
126 assert_eq!(&dib[44..48], &[157, 152, 147, 255]);
127 assert_eq!(&dib[48..52], &[30, 20, 10, 255]);
128 }
129
130 #[test]
131 fn a_jpeg_is_kept_as_png_for_the_clipboard() {
132 let mut jpeg = Vec::new();
133 image::DynamicImage::ImageRgba8(RgbaImage::from_pixel(3, 1, Rgba([1, 2, 3, 255])))
134 .to_rgb8()
135 .write_to(&mut Cursor::new(&mut jpeg), image::ImageFormat::Jpeg)
136 .unwrap();
137 let image = ClipboardImage::from_bytes(&jpeg).unwrap();
138 assert_eq!(
139 image::guess_format(&image.png).unwrap(),
140 image::ImageFormat::Png
141 );
142 }
143}
crates/app-base/src/lib.rs +1 −0
@@ -16,6 +16,7 @@ pub mod emoji;
16 16 pub mod format;
17 17 pub mod frame_log;
18 18 pub mod fuzzy;
19 pub mod image_clipboard;
19 20 pub mod image_view_math;
20 21 pub mod inline_image;
21 22 pub mod notify;
@@ -16,6 +16,7 @@ pub mod emoji;
16pub mod format;
16pub mod format;
17pub mod frame_log;
17pub mod frame_log;
18pub mod fuzzy;
18pub mod fuzzy;
19pub mod image_clipboard;
19pub mod image_view_math;
20pub mod image_view_math;
20pub mod inline_image;
21pub mod inline_image;
21pub mod notify;
22pub mod notify;
crates/app-state/src/lib.rs +1 −1
@@ -41,6 +41,6 @@ pub use app_ui_kit::render;
41 41 pub use app_base::{
42 42 APP_NAME, avatar_image, channel_files, crash_log, demo_cards, demo_chart_cards, demo_gifs,
43 43 demo_input_cards, demo_library, demo_recap, diagnostics, downloads, format, frame_log, fuzzy,
44 image_view_math, inline_image, presence_link, read_state, recap, remote_image, runtime, schedule_time,
44 image_clipboard, image_view_math, inline_image, presence_link, read_state, recap, remote_image, runtime, schedule_time,
45 45 single_instance, stickers, theme, translation, updater, user_activity,
46 46 };
@@ -41,6 +41,6 @@ pub use app_ui_kit::render;
41pub use app_base::{
41pub use app_base::{
42 APP_NAME, avatar_image, channel_files, crash_log, demo_cards, demo_chart_cards, demo_gifs,
42 APP_NAME, avatar_image, channel_files, crash_log, demo_cards, demo_chart_cards, demo_gifs,
43 demo_input_cards, demo_library, demo_recap, diagnostics, downloads, format, frame_log, fuzzy,
43 demo_input_cards, demo_library, demo_recap, diagnostics, downloads, format, frame_log, fuzzy,
44 image_view_math, inline_image, presence_link, read_state, recap, remote_image, runtime, schedule_time,
44 image_clipboard, image_view_math, inline_image, presence_link, read_state, recap, remote_image, runtime, schedule_time,
45 single_instance, stickers, theme, translation, updater, user_activity,
45 single_instance, stickers, theme, translation, updater, user_activity,
46};
46};
crates/app/src/views/attachments.rs +19 −10
@@ -6,6 +6,7 @@ use gpui_kit::prelude::FluentBuilder as _;
6 6 use gpui_kit::*;
7 7 use teams_core::{FileCard, FileKind, ImageRef, external_image_url};
8 8
9 use super::image_menu::{ImageShare, with_image_menu};
9 10 use super::widgets::{icon, symbol};
10 11 use crate::data::Directory;
11 12 use crate::downloads::{self, DownloadState};
@@ -29,7 +30,11 @@ const LOCAL_IMAGE_PREFIX: &str = "../hostedContents/";
29 30 const LOCAL_IMAGE_SUFFIX: &str = "/$value";
30 31
31 32 pub type FileActivate = Rc<dyn Fn(usize, &mut App)>;
32 pub type ImageOpen = Rc<dyn Fn(&str, &mut App)>;
33 #[derive(Clone)]
34 pub struct ImageActions {
35 pub open: Rc<dyn Fn(&str, &mut App)>,
36 pub share: Option<ImageShare>,
37 }
33 38
34 39 #[derive(Clone)]
35 40 pub struct FileActions {
@@ -71,7 +76,7 @@ fn image_view(
71 76 image: &ImageRef,
72 77 id: String,
73 78 directory: &Directory,
74 open_image: Option<&ImageOpen>,
79 open_image: Option<&ImageActions>,
75 80 ) -> AnyElement {
76 81 let (width, height) = image_size(image, directory);
77 82 let frame = div()
@@ -101,8 +106,9 @@ fn image_view(
101 106 .into_any_element();
102 107 };
103 108 let path = entry.path.clone();
109 let share = open_image.and_then(|actions| actions.share.clone());
104 110 let (url, open_image) = (image.url.clone(), open_image.cloned());
105 frame
111 let frame = frame
106 112 .cursor_pointer()
107 113 .child(
108 114 img(entry.path.clone())
@@ -110,11 +116,14 @@ fn image_view(
110 116 .rounded(px(IMAGE_RADIUS))
111 117 .object_fit(ObjectFit::Cover),
112 118 )
113 .on_click(move |_, _, cx| match &open_image {
114 Some(open_image) => open_image(&url, cx),
115 None => cx.open_with_system(&path),
116 })
117 .into_any_element()
119 .on_click({
120 let path = path.clone();
121 move |_, _, cx| match &open_image {
122 Some(actions) => (actions.open)(&url, cx),
123 None => cx.open_with_system(&path),
124 }
125 });
126 with_image_menu(frame, path, share).into_any_element()
118 127 }
119 128
120 129 struct KindStyle {
@@ -332,7 +341,7 @@ pub fn message_body(
332 341 id: &str,
333 342 own: bool,
334 343 directory: &Directory,
335 open_image: Option<&ImageOpen>,
344 open_image: Option<&ImageActions>,
336 345 cx: &App,
337 346 ) -> Vec<AnyElement> {
338 347 if !blocks
@@ -381,7 +390,7 @@ pub fn attachments_view(
381 390 id: &str,
382 391 directory: &Directory,
383 392 file_actions: Option<&FileActions>,
384 open_image: Option<&ImageOpen>,
393 open_image: Option<&ImageActions>,
385 394 ) -> Option<Div> {
386 395 let placed = placements(blocks, images, local_images.len());
387 396 let unplaced_images: Vec<(usize, &ImageRef)> = images
@@ -6,6 +6,7 @@ use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
6use gpui_kit::*;
7use teams_core::{FileCard, FileKind, ImageRef, external_image_url};
7use teams_core::{FileCard, FileKind, ImageRef, external_image_url};
8
8
9use super::image_menu::{ImageShare, with_image_menu};
9use super::widgets::{icon, symbol};
10use super::widgets::{icon, symbol};
10use crate::data::Directory;
11use crate::data::Directory;
11use crate::downloads::{self, DownloadState};
12use crate::downloads::{self, DownloadState};
@@ -29,7 +30,11 @@ const LOCAL_IMAGE_PREFIX: &str = "../hostedContents/";
29const LOCAL_IMAGE_SUFFIX: &str = "/$value";
30const LOCAL_IMAGE_SUFFIX: &str = "/$value";
30
31
31pub type FileActivate = Rc<dyn Fn(usize, &mut App)>;
32pub type FileActivate = Rc<dyn Fn(usize, &mut App)>;
32pub type ImageOpen = Rc<dyn Fn(&str, &mut App)>;
33#[derive(Clone)]
34pub struct ImageActions {
35 pub open: Rc<dyn Fn(&str, &mut App)>,
36 pub share: Option<ImageShare>,
37}
33
38
34#[derive(Clone)]
39#[derive(Clone)]
35pub struct FileActions {
40pub struct FileActions {
@@ -71,7 +76,7 @@ fn image_view(
71 image: &ImageRef,
76 image: &ImageRef,
72 id: String,
77 id: String,
73 directory: &Directory,
78 directory: &Directory,
74 open_image: Option<&ImageOpen>,
79 open_image: Option<&ImageActions>,
75) -> AnyElement {
80) -> AnyElement {
76 let (width, height) = image_size(image, directory);
81 let (width, height) = image_size(image, directory);
77 let frame = div()
82 let frame = div()
@@ -101,8 +106,9 @@ fn image_view(
101 .into_any_element();
106 .into_any_element();
102 };
107 };
103 let path = entry.path.clone();
108 let path = entry.path.clone();
109 let share = open_image.and_then(|actions| actions.share.clone());
104 let (url, open_image) = (image.url.clone(), open_image.cloned());
110 let (url, open_image) = (image.url.clone(), open_image.cloned());
105 frame
111 let frame = frame
106 .cursor_pointer()
112 .cursor_pointer()
107 .child(
113 .child(
108 img(entry.path.clone())
114 img(entry.path.clone())
@@ -110,11 +116,14 @@ fn image_view(
110 .rounded(px(IMAGE_RADIUS))
116 .rounded(px(IMAGE_RADIUS))
111 .object_fit(ObjectFit::Cover),
117 .object_fit(ObjectFit::Cover),
112 )
118 )
113 .on_click(move |_, _, cx| match &open_image {
119 .on_click({
114 Some(open_image) => open_image(&url, cx),
120 let path = path.clone();
115 None => cx.open_with_system(&path),
121 move |_, _, cx| match &open_image {
116 })
122 Some(actions) => (actions.open)(&url, cx),
117 .into_any_element()
123 None => cx.open_with_system(&path),
124 }
125 });
126 with_image_menu(frame, path, share).into_any_element()
118}
127}
119
128
120struct KindStyle {
129struct KindStyle {
@@ -332,7 +341,7 @@ pub fn message_body(
332 id: &str,
341 id: &str,
333 own: bool,
342 own: bool,
334 directory: &Directory,
343 directory: &Directory,
335 open_image: Option<&ImageOpen>,
344 open_image: Option<&ImageActions>,
336 cx: &App,
345 cx: &App,
337) -> Vec<AnyElement> {
346) -> Vec<AnyElement> {
338 if !blocks
347 if !blocks
@@ -381,7 +390,7 @@ pub fn attachments_view(
381 id: &str,
390 id: &str,
382 directory: &Directory,
391 directory: &Directory,
383 file_actions: Option<&FileActions>,
392 file_actions: Option<&FileActions>,
384 open_image: Option<&ImageOpen>,
393 open_image: Option<&ImageActions>,
385) -> Option<Div> {
394) -> Option<Div> {
386 let placed = placements(blocks, images, local_images.len());
395 let placed = placements(blocks, images, local_images.len());
387 let unplaced_images: Vec<(usize, &ImageRef)> = images
396 let unplaced_images: Vec<(usize, &ImageRef)> = images
crates/app/src/views/conversation/render_env.rs +15 −6
@@ -18,7 +18,7 @@ use crate::rows::{Delivery, MessageRow, PostRow};
18 18 use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
19 19 use crate::translation::TranslationLine;
20 20 use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
21 use crate::views::attachments::ImageOpen;
21 use crate::views::attachments::ImageActions;
22 22 use crate::views::call_card::CallActions;
23 23 use crate::views::composer::Composer;
24 24 use crate::views::message_row::{DeliveryActions, RowActions};
@@ -237,11 +237,20 @@ impl RenderEnv {
237 237 .file_actions(&message.key, &message.files, view.clone())
238 238 });
239 239 let open_image = (is_real && !message.deleted && !message.images.is_empty()).then(|| {
240 let (view, key) = (view.clone(), message.key.clone());
241 Rc::new(move |url: &str, cx: &mut App| {
242 view.update(cx, |this, cx| this.open_image_viewer(&key, url, cx))
243 .ok();
244 }) as ImageOpen
240 let (open_view, open_key) = (view.clone(), message.key.clone());
241 let (share_view, share_key) = (view.clone(), message.key.clone());
242 ImageActions {
243 open: Rc::new(move |url: &str, cx: &mut App| {
244 open_view
245 .update(cx, |this, cx| this.open_image_viewer(&open_key, url, cx))
246 .ok();
247 }),
248 share: Some(Rc::new(move |cx: &mut App| {
249 share_view
250 .update(cx, |this, cx| this.forward_message(&share_key, cx))
251 .ok();
252 })),
253 }
245 254 });
246 255 let bot = self.bot_identity(message, cx);
247 256 let actionable_run = (is_real && !message.deleted)
@@ -18,7 +18,7 @@ use crate::rows::{Delivery, MessageRow, PostRow};
18use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
18use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
19use crate::translation::TranslationLine;
19use crate::translation::TranslationLine;
20use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
20use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
21use crate::views::attachments::ImageOpen;
21use crate::views::attachments::ImageActions;
22use crate::views::call_card::CallActions;
22use crate::views::call_card::CallActions;
23use crate::views::composer::Composer;
23use crate::views::composer::Composer;
24use crate::views::message_row::{DeliveryActions, RowActions};
24use crate::views::message_row::{DeliveryActions, RowActions};
@@ -237,11 +237,20 @@ impl RenderEnv {
237 .file_actions(&message.key, &message.files, view.clone())
237 .file_actions(&message.key, &message.files, view.clone())
238 });
238 });
239 let open_image = (is_real && !message.deleted && !message.images.is_empty()).then(|| {
239 let open_image = (is_real && !message.deleted && !message.images.is_empty()).then(|| {
240 let (view, key) = (view.clone(), message.key.clone());
240 let (open_view, open_key) = (view.clone(), message.key.clone());
241 Rc::new(move |url: &str, cx: &mut App| {
241 let (share_view, share_key) = (view.clone(), message.key.clone());
242 view.update(cx, |this, cx| this.open_image_viewer(&key, url, cx))
242 ImageActions {
243 .ok();
243 open: Rc::new(move |url: &str, cx: &mut App| {
244 }) as ImageOpen
244 open_view
245 .update(cx, |this, cx| this.open_image_viewer(&open_key, url, cx))
246 .ok();
247 }),
248 share: Some(Rc::new(move |cx: &mut App| {
249 share_view
250 .update(cx, |this, cx| this.forward_message(&share_key, cx))
251 .ok();
252 })),
253 }
245 });
254 });
246 let bot = self.bot_identity(message, cx);
255 let bot = self.bot_identity(message, cx);
247 let actionable_run = (is_real && !message.deleted)
256 let actionable_run = (is_real && !message.deleted)
crates/app/src/views/image_menu.rs added +83 −0
@@ -0,0 +1,83 @@
1 use std::path::PathBuf;
2 use std::rc::Rc;
3
4 use gpui_kit::assets::IconName;
5 use gpui_kit::component::{
6 Icon,
7 menu::{ContextMenuExt as _, PopupMenuItem},
8 };
9 use gpui_kit::*;
10
11 use super::image_viewer::{suggested_name, write_image};
12 use super::widgets::icon;
13 use crate::downloads;
14 use crate::image_clipboard::ClipboardImage;
15 use crate::theme;
16
17 const MENU_ICON_SIZE: f32 = 16.;
18
19 pub type ImageShare = Rc<dyn Fn(&mut App)>;
20
21 fn menu_icon(glyph: IconName) -> Icon {
22 icon(glyph, MENU_ICON_SIZE, theme::text_muted())
23 }
24
25 pub fn copy_image_file(path: PathBuf, cx: &mut App) {
26 cx.spawn(async move |cx| {
27 let image = cx
28 .background_spawn(async move {
29 std::fs::read(&path)
30 .ok()
31 .and_then(|bytes| ClipboardImage::from_bytes(&bytes))
32 })
33 .await;
34 if let Some(image) = image {
35 cx.update(|cx| image.write(cx));
36 }
37 })
38 .detach();
39 }
40
41 fn download_image_file(source: PathBuf, cx: &mut App) {
42 let name = suggested_name(&source, false);
43 let receiver = cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&name));
44 cx.background_spawn(async move {
45 if let Ok(Ok(Some(target))) = receiver.await {
46 if let Err(error) = write_image(&source, &target, 0) {
47 log::warn!("image download to {} failed: {error}", target.display());
48 }
49 }
50 })
51 .detach();
52 }
53
54 pub fn with_image_menu(
55 frame: Stateful<Div>,
56 path: PathBuf,
57 share: Option<ImageShare>,
58 ) -> impl IntoElement {
59 frame
60 .on_mouse_down(MouseButton::Right, |_, _, cx| cx.stop_propagation())
61 .context_menu(move |popup, _, _| {
62 let (copy_path, download_path) = (path.clone(), path.clone());
63 let popup = popup
64 .item(
65 PopupMenuItem::new("Copy image")
66 .icon(menu_icon(IconName::Copy))
67 .on_click(move |_, _, cx| copy_image_file(copy_path.clone(), cx)),
68 )
69 .item(
70 PopupMenuItem::new("Download")
71 .icon(menu_icon(IconName::Download))
72 .on_click(move |_, _, cx| download_image_file(download_path.clone(), cx)),
73 );
74 match share.clone() {
75 Some(share) => popup.item(
76 PopupMenuItem::new("Share")
77 .icon(menu_icon(IconName::Share))
78 .on_click(move |_, _, cx| share(cx)),
79 ),
80 None => popup,
81 }
82 })
83 }
@@ -0,0 +1,83 @@
1use std::path::PathBuf;
2use std::rc::Rc;
3
4use gpui_kit::assets::IconName;
5use gpui_kit::component::{
6 Icon,
7 menu::{ContextMenuExt as _, PopupMenuItem},
8};
9use gpui_kit::*;
10
11use super::image_viewer::{suggested_name, write_image};
12use super::widgets::icon;
13use crate::downloads;
14use crate::image_clipboard::ClipboardImage;
15use crate::theme;
16
17const MENU_ICON_SIZE: f32 = 16.;
18
19pub type ImageShare = Rc<dyn Fn(&mut App)>;
20
21fn menu_icon(glyph: IconName) -> Icon {
22 icon(glyph, MENU_ICON_SIZE, theme::text_muted())
23}
24
25pub fn copy_image_file(path: PathBuf, cx: &mut App) {
26 cx.spawn(async move |cx| {
27 let image = cx
28 .background_spawn(async move {
29 std::fs::read(&path)
30 .ok()
31 .and_then(|bytes| ClipboardImage::from_bytes(&bytes))
32 })
33 .await;
34 if let Some(image) = image {
35 cx.update(|cx| image.write(cx));
36 }
37 })
38 .detach();
39}
40
41fn download_image_file(source: PathBuf, cx: &mut App) {
42 let name = suggested_name(&source, false);
43 let receiver = cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&name));
44 cx.background_spawn(async move {
45 if let Ok(Ok(Some(target))) = receiver.await {
46 if let Err(error) = write_image(&source, &target, 0) {
47 log::warn!("image download to {} failed: {error}", target.display());
48 }
49 }
50 })
51 .detach();
52}
53
54pub fn with_image_menu(
55 frame: Stateful<Div>,
56 path: PathBuf,
57 share: Option<ImageShare>,
58) -> impl IntoElement {
59 frame
60 .on_mouse_down(MouseButton::Right, |_, _, cx| cx.stop_propagation())
61 .context_menu(move |popup, _, _| {
62 let (copy_path, download_path) = (path.clone(), path.clone());
63 let popup = popup
64 .item(
65 PopupMenuItem::new("Copy image")
66 .icon(menu_icon(IconName::Copy))
67 .on_click(move |_, _, cx| copy_image_file(copy_path.clone(), cx)),
68 )
69 .item(
70 PopupMenuItem::new("Download")
71 .icon(menu_icon(IconName::Download))
72 .on_click(move |_, _, cx| download_image_file(download_path.clone(), cx)),
73 );
74 match share.clone() {
75 Some(share) => popup.item(
76 PopupMenuItem::new("Share")
77 .icon(menu_icon(IconName::Share))
78 .on_click(move |_, _, cx| share(cx)),
79 ),
80 None => popup,
81 }
82 })
83}
crates/app/src/views/image_viewer.rs +13 −27
@@ -13,6 +13,7 @@ use super::avatar::person_avatar;
13 13 use super::widgets::symbol;
14 14 use crate::app_state::AppState;
15 15 use crate::downloads;
16 use crate::image_clipboard::ClipboardImage;
16 17 use crate::image_view_gallery::{GalleryItem, ViewerRequest};
17 18 use crate::image_view_math::{
18 19 MAX_ZOOM, Pair, View, clamp_pan, clamp_scale, counter_label, display_size, fit_scale,
@@ -119,31 +120,16 @@ fn rotated_png(path: &Path, quarter_turns: u8) -> Option<Vec<u8>> {
119 120 Some(bytes)
120 121 }
121 122
122 fn clipboard_format(bytes: &[u8]) -> Option<ImageFormat> {
123 match image::guess_format(bytes).ok()? {
124 image::ImageFormat::Png => Some(ImageFormat::Png),
125 image::ImageFormat::Jpeg => Some(ImageFormat::Jpeg),
126 image::ImageFormat::Gif => Some(ImageFormat::Gif),
127 image::ImageFormat::WebP => Some(ImageFormat::Webp),
128 image::ImageFormat::Bmp => Some(ImageFormat::Bmp),
129 _ => None,
130 }
131 }
132
133 fn clipboard_item(path: &Path, quarter_turns: u8) -> Option<ClipboardItem> {
134 if quarter_turns != 0 {
135 let bytes = rotated_png(path, quarter_turns)?;
136 return Some(ClipboardItem::new_image(&Image::from_bytes(
137 ImageFormat::Png,
138 bytes,
139 )));
140 }
141 let bytes = std::fs::read(path).ok()?;
142 let format = clipboard_format(&bytes)?;
143 Some(ClipboardItem::new_image(&Image::from_bytes(format, bytes)))
123 fn clipboard_image(path: &Path, quarter_turns: u8) -> Option<ClipboardImage> {
124 let bytes = if quarter_turns != 0 {
125 rotated_png(path, quarter_turns)?
126 } else {
127 std::fs::read(path).ok()?
128 };
129 ClipboardImage::from_bytes(&bytes)
144 130 }
145 131
146 fn suggested_name(path: &Path, rotated: bool) -> String {
132 pub(super) fn suggested_name(path: &Path, rotated: bool) -> String {
147 133 let name = path
148 134 .file_name()
149 135 .map(|name| name.to_string_lossy().into_owned())
@@ -165,7 +151,7 @@ fn suggested_name(path: &Path, rotated: bool) -> String {
165 151 format!("{name}.{extension}")
166 152 }
167 153
168 fn write_image(source: &Path, target: &Path, quarter_turns: u8) -> std::io::Result<()> {
154 pub(super) fn write_image(source: &Path, target: &Path, quarter_turns: u8) -> std::io::Result<()> {
169 155 if quarter_turns == 0 {
170 156 return std::fs::copy(source, target).map(|_| ());
171 157 }
@@ -539,11 +525,11 @@ impl ImageViewer {
539 525 cx.spawn(async move |this, cx| {
540 526 let fallback = path.clone();
541 527 let item = cx
542 .background_spawn(async move { clipboard_item(&path, quarter_turns) })
528 .background_spawn(async move { clipboard_image(&path, quarter_turns) })
543 529 .await;
544 530 this.update(cx, |this, cx| match item {
545 Some(item) => {
546 cx.write_to_clipboard(item);
531 Some(image) => {
532 image.write(cx);
547 533 this.show_notice("Image copied", cx);
548 534 }
549 535 None => {
@@ -13,6 +13,7 @@ use super::avatar::person_avatar;
13use super::widgets::symbol;
13use super::widgets::symbol;
14use crate::app_state::AppState;
14use crate::app_state::AppState;
15use crate::downloads;
15use crate::downloads;
16use crate::image_clipboard::ClipboardImage;
16use crate::image_view_gallery::{GalleryItem, ViewerRequest};
17use crate::image_view_gallery::{GalleryItem, ViewerRequest};
17use crate::image_view_math::{
18use crate::image_view_math::{
18 MAX_ZOOM, Pair, View, clamp_pan, clamp_scale, counter_label, display_size, fit_scale,
19 MAX_ZOOM, Pair, View, clamp_pan, clamp_scale, counter_label, display_size, fit_scale,
@@ -119,31 +120,16 @@ fn rotated_png(path: &Path, quarter_turns: u8) -> Option<Vec<u8>> {
119 Some(bytes)
120 Some(bytes)
120}
121}
121
122
122fn clipboard_format(bytes: &[u8]) -> Option<ImageFormat> {
123fn clipboard_image(path: &Path, quarter_turns: u8) -> Option<ClipboardImage> {
123 match image::guess_format(bytes).ok()? {
124 let bytes = if quarter_turns != 0 {
124 image::ImageFormat::Png => Some(ImageFormat::Png),
125 rotated_png(path, quarter_turns)?
125 image::ImageFormat::Jpeg => Some(ImageFormat::Jpeg),
126 } else {
126 image::ImageFormat::Gif => Some(ImageFormat::Gif),
127 std::fs::read(path).ok()?
127 image::ImageFormat::WebP => Some(ImageFormat::Webp),
128 };
128 image::ImageFormat::Bmp => Some(ImageFormat::Bmp),
129 ClipboardImage::from_bytes(&bytes)
129 _ => None,
130 }
131}
132
133fn clipboard_item(path: &Path, quarter_turns: u8) -> Option<ClipboardItem> {
134 if quarter_turns != 0 {
135 let bytes = rotated_png(path, quarter_turns)?;
136 return Some(ClipboardItem::new_image(&Image::from_bytes(
137 ImageFormat::Png,
138 bytes,
139 )));
140 }
141 let bytes = std::fs::read(path).ok()?;
142 let format = clipboard_format(&bytes)?;
143 Some(ClipboardItem::new_image(&Image::from_bytes(format, bytes)))
144}
130}
145
131
146fn suggested_name(path: &Path, rotated: bool) -> String {
132pub(super) fn suggested_name(path: &Path, rotated: bool) -> String {
147 let name = path
133 let name = path
148 .file_name()
134 .file_name()
149 .map(|name| name.to_string_lossy().into_owned())
135 .map(|name| name.to_string_lossy().into_owned())
@@ -165,7 +151,7 @@ fn suggested_name(path: &Path, rotated: bool) -> String {
165 format!("{name}.{extension}")
151 format!("{name}.{extension}")
166}
152}
167
153
168fn write_image(source: &Path, target: &Path, quarter_turns: u8) -> std::io::Result<()> {
154pub(super) fn write_image(source: &Path, target: &Path, quarter_turns: u8) -> std::io::Result<()> {
169 if quarter_turns == 0 {
155 if quarter_turns == 0 {
170 return std::fs::copy(source, target).map(|_| ());
156 return std::fs::copy(source, target).map(|_| ());
171 }
157 }
@@ -539,11 +525,11 @@ impl ImageViewer {
539 cx.spawn(async move |this, cx| {
525 cx.spawn(async move |this, cx| {
540 let fallback = path.clone();
526 let fallback = path.clone();
541 let item = cx
527 let item = cx
542 .background_spawn(async move { clipboard_item(&path, quarter_turns) })
528 .background_spawn(async move { clipboard_image(&path, quarter_turns) })
543 .await;
529 .await;
544 this.update(cx, |this, cx| match item {
530 this.update(cx, |this, cx| match item {
545 Some(item) => {
531 Some(image) => {
546 cx.write_to_clipboard(item);
532 image.write(cx);
547 this.show_notice("Image copied", cx);
533 this.show_notice("Image copied", cx);
548 }
534 }
549 None => {
535 None => {
crates/app/src/views/message_row.rs +3 −3
@@ -5,7 +5,7 @@ use gpui_kit::*;
5 5 use std::time::Duration;
6 6
7 7 use super::adaptive_card::cards_view;
8 use super::attachments::{FileActions, ImageOpen, attachments_view, message_body};
8 use super::attachments::{FileActions, ImageActions, attachments_view, message_body};
9 9 use super::avatar::{bot_avatar, person_avatar};
10 10 use super::call_card::{CallActions, call_card_row};
11 11 use super::link_preview::{link_preview_card, meeting_join_chip};
@@ -74,7 +74,7 @@ pub struct RowActions {
74 74 pub react: Option<PickHandler>,
75 75 pub reaction_controls: Option<ReactionControls>,
76 76 pub files: Option<FileActions>,
77 pub open_image: Option<ImageOpen>,
77 pub open_image: Option<ImageActions>,
78 78 pub highlighted: bool,
79 79 pub saved: bool,
80 80 pub translation: Option<TranslationActions>,
@@ -302,7 +302,7 @@ struct BubbleExtras {
302 302 react: Option<PickHandler>,
303 303 controls: Option<ReactionControls>,
304 304 files: Option<FileActions>,
305 open_image: Option<ImageOpen>,
305 open_image: Option<ImageActions>,
306 306 saved: bool,
307 307 translation: Option<TranslationActions>,
308 308 timeline: TimelineBounds,
@@ -5,7 +5,7 @@ use gpui_kit::*;
5use std::time::Duration;
5use std::time::Duration;
6
6
7use super::adaptive_card::cards_view;
7use super::adaptive_card::cards_view;
8use super::attachments::{FileActions, ImageOpen, attachments_view, message_body};
8use super::attachments::{FileActions, ImageActions, attachments_view, message_body};
9use super::avatar::{bot_avatar, person_avatar};
9use super::avatar::{bot_avatar, person_avatar};
10use super::call_card::{CallActions, call_card_row};
10use super::call_card::{CallActions, call_card_row};
11use super::link_preview::{link_preview_card, meeting_join_chip};
11use super::link_preview::{link_preview_card, meeting_join_chip};
@@ -74,7 +74,7 @@ pub struct RowActions {
74 pub react: Option<PickHandler>,
74 pub react: Option<PickHandler>,
75 pub reaction_controls: Option<ReactionControls>,
75 pub reaction_controls: Option<ReactionControls>,
76 pub files: Option<FileActions>,
76 pub files: Option<FileActions>,
77 pub open_image: Option<ImageOpen>,
77 pub open_image: Option<ImageActions>,
78 pub highlighted: bool,
78 pub highlighted: bool,
79 pub saved: bool,
79 pub saved: bool,
80 pub translation: Option<TranslationActions>,
80 pub translation: Option<TranslationActions>,
@@ -302,7 +302,7 @@ struct BubbleExtras {
302 react: Option<PickHandler>,
302 react: Option<PickHandler>,
303 controls: Option<ReactionControls>,
303 controls: Option<ReactionControls>,
304 files: Option<FileActions>,
304 files: Option<FileActions>,
305 open_image: Option<ImageOpen>,
305 open_image: Option<ImageActions>,
306 saved: bool,
306 saved: bool,
307 translation: Option<TranslationActions>,
307 translation: Option<TranslationActions>,
308 timeline: TimelineBounds,
308 timeline: TimelineBounds,
crates/app/src/views/mod.rs +1 −0
@@ -37,6 +37,7 @@ pub mod emoji_popup;
37 37 pub mod format_toolbar;
38 38 pub mod forward_dialog;
39 39 pub mod fun_picker;
40 pub mod image_menu;
40 41 pub mod image_viewer;
41 42 pub mod join_dialog;
42 43 pub mod link_preview;
@@ -37,6 +37,7 @@ pub mod emoji_popup;
37pub mod format_toolbar;
37pub mod format_toolbar;
38pub mod forward_dialog;
38pub mod forward_dialog;
39pub mod fun_picker;
39pub mod fun_picker;
40pub mod image_menu;
40pub mod image_viewer;
41pub mod image_viewer;
41pub mod join_dialog;
42pub mod join_dialog;
42pub mod link_preview;
43pub mod link_preview;