BlueGit

ict rusty-teams

Files

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

image_menu.rs

image_menu.rs 2.4 KiB Download Raw
1use std::path::PathBuf;
2use std::rc::Rc;
3
4use gpui_kit::assets::IconName;
5use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};
6use gpui_kit::*;
7
8use super::image_viewer::{suggested_name, write_image};
9use super::widgets::menu_icon;
10use crate::downloads;
11use crate::image_clipboard::ClipboardImage;
12
13pub type ImageShare = Rc<dyn Fn(&mut App)>;
14
15pub fn copy_image_file(path: PathBuf, cx: &mut App) {
16 cx.spawn(async move |cx| {
17 let image = cx
18 .background_spawn(async move {
19 std::fs::read(&path)
20 .ok()
21 .and_then(|bytes| ClipboardImage::from_bytes(&bytes))
22 })
23 .await;
24 if let Some(image) = image {
25 cx.update(|cx| image.write(cx));
26 }
27 })
28 .detach();
29}
30
31fn download_image_file(source: PathBuf, cx: &mut App) {
32 let name = suggested_name(&source, false);
33 let receiver = cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&name));
34 cx.background_spawn(async move {
35 if let Ok(Ok(Some(target))) = receiver.await {
36 if let Err(error) = write_image(&source, &target, 0) {
37 log::warn!("image download to {} failed: {error}", target.display());
38 }
39 }
40 })
41 .detach();
42}
43
44pub fn with_image_menu(
45 frame: Stateful<Div>,
46 path: PathBuf,
47 share: Option<ImageShare>,
48) -> impl IntoElement {
49 frame
50 .on_mouse_down(MouseButton::Right, |_, _, cx| cx.stop_propagation())
51 .context_menu(move |popup, _, _| {
52 let (copy_path, download_path) = (path.clone(), path.clone());
53 let popup = popup
54 .item(
55 PopupMenuItem::new("Copy image")
56 .icon(menu_icon(IconName::Copy))
57 .on_click(move |_, _, cx| copy_image_file(copy_path.clone(), cx)),
58 )
59 .item(
60 PopupMenuItem::new("Download")
61 .icon(menu_icon(IconName::Download))
62 .on_click(move |_, _, cx| download_image_file(download_path.clone(), cx)),
63 );
64 match share.clone() {
65 Some(share) => popup.item(
66 PopupMenuItem::new("Share")
67 .icon(menu_icon(IconName::Share))
68 .on_click(move |_, _, cx| share(cx)),
69 ),
70 None => popup,
71 }
72 })
73}