BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / image_menu.rs

image_menu.rs

image_menu.rs 2.6 KiB Download Raw
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}