1use std::path::PathBuf;
20
21use bus_contract::{Bus, ListenOpts, Point, PointId, PointKind};
22use egui::{Context, Id, Ui};
23use serde::Serialize;
24use serde_json::json;
25
26use super::{OWNER, emit_with};
27use crate::app::AppHandle;
28use egui_pop_core::strings;
29
30#[derive(Clone, Debug, PartialEq, Serialize)]
33#[non_exhaustive]
34pub struct FileDrop {
35 pub window: String,
38 pub paths: Vec<PathBuf>,
39 #[serde(skip_serializing_if = "Option::is_none")]
41 pub at: Option<[f32; 2]>,
42 #[serde(skip)]
45 taken: Vec<String>,
46}
47
48impl FileDrop {
49 pub fn new(window: impl Into<String>, paths: Vec<PathBuf>) -> Self {
50 Self {
51 window: window.into(),
52 paths,
53 at: None,
54 taken: Vec::new(),
55 }
56 }
57
58 pub fn at(mut self, at: [f32; 2]) -> Self {
60 self.at = Some(at);
61 self
62 }
63}
64
65#[derive(Debug)]
69pub struct FilesDrop;
70impl Point for FilesDrop {
71 const KIND: PointKind = PointKind::Request;
72 const ID: PointId = PointId::new("pop.files.drop");
73 type Input = FileDrop;
74 type Value = Vec<String>;
75}
76
77pub const FILES_POINTS: [&str; 1] = [FilesDrop::ID.as_str()];
79
80pub const BROWSER: &str = "pop.files.browser";
83
84#[derive(Clone, Debug, Default)]
86struct Pass {
87 window: Option<String>,
90 hovered: Vec<PathBuf>,
91 hovering: bool,
93 dropped: Vec<PathBuf>,
94 at: Option<egui::Pos2>,
95 taken: Vec<String>,
97 shown: bool,
99}
100
101fn pass_id(ctx: &Context) -> Id {
102 Id::unique(("egui_pop.files.drop", ctx.viewport_id()))
103}
104
105fn read(ctx: &Context) -> Pass {
107 ctx.input(|i| Pass {
108 window: None,
109 hovered: i
110 .raw
111 .hovered_files
112 .iter()
113 .filter_map(|f| f.path.clone())
114 .collect(),
115 hovering: !i.raw.hovered_files.is_empty(),
116 dropped: i
117 .raw
118 .dropped_files
119 .iter()
120 .map(|f| f.path().to_path_buf())
121 .filter(|p| !p.as_os_str().is_empty())
122 .collect(),
123 at: i.pointer.latest_pos(),
124 taken: Vec::new(),
125 shown: false,
126 })
127}
128
129pub(crate) fn begin_pass(ctx: &Context, window: &str) {
132 let mut pass = read(ctx);
133 pass.window = Some(window.to_string());
134 let id = pass_id(ctx);
135 ctx.data_mut(|d| d.insert_temp(id, pass));
136}
137
138pub(crate) fn system_drag(ctx: &Context) -> Option<(Vec<PathBuf>, bool)> {
142 let id = pass_id(ctx);
143 let pass = ctx
144 .data(|d| d.get_temp::<Pass>(id))
145 .filter(|p| p.window.is_some())
146 .unwrap_or_else(|| read(ctx));
147 if !pass.dropped.is_empty() {
148 Some((pass.dropped, true))
149 } else if pass.hovering {
150 Some((pass.hovered, false))
151 } else {
152 None
153 }
154}
155
156pub(crate) fn take(ctx: &Context, what: String) {
159 in_pass(ctx, |p| p.taken.push(what));
160}
161
162pub(crate) fn shown(ctx: &Context) {
165 in_pass(ctx, |p| p.shown = true);
166}
167
168fn in_pass(ctx: &Context, change: impl FnOnce(&mut Pass)) {
171 let id = pass_id(ctx);
172 ctx.data_mut(|d| {
173 if let Some(mut p) = d.get_temp::<Pass>(id).filter(|p| p.window.is_some()) {
174 change(&mut p);
175 d.insert_temp(id, p);
176 }
177 });
178}
179
180pub(crate) fn end_pass(app: &AppHandle, ui: &Ui) {
183 let ctx = ui.ctx();
184 let id = pass_id(ctx);
185 let Some(pass) = ctx.data_mut(|d| d.remove_temp::<Pass>(id)) else {
186 return;
187 };
188 let Some(window) = pass.window else { return };
189 if !pass.dropped.is_empty() {
190 let mut drop = FileDrop::new(window, pass.dropped);
191 drop.at = pass.at.map(|p| [p.x, p.y]);
192 drop.taken = pass.taken;
193 app.request_files_drop(drop);
194 } else if pass.hovering && !pass.shown {
195 paint_hover(app, ui);
196 ctx.request_repaint();
198 }
199}
200
201fn paint_hover(app: &AppHandle, ui: &Ui) {
203 let ctx = ui.ctx();
204 let takes = takers(app) > 0;
205 let visuals = ui.visuals();
206 let color = if takes {
207 visuals.selection.stroke.color
208 } else {
209 visuals.error_fg_color
210 };
211 let rect = ctx.content_rect();
212 let painter = ctx.layer_painter(egui::LayerId::new(
213 egui::Order::Foreground,
214 Id::unique("egui_pop.files.hover"),
215 ));
216 painter.rect_stroke(
217 rect.shrink(2.0),
218 4.0,
219 egui::Stroke::new(3.0, color),
220 egui::StrokeKind::Inside,
221 );
222 let text = strings::tr(
223 ctx,
224 if takes {
225 &crate::strings::FILES_DROP_HERE
226 } else {
227 &crate::strings::FILES_DROP_NOWHERE
228 },
229 );
230 let font = egui::TextStyle::Body.resolve(ui.style());
231 let galley = painter.layout_no_wrap(text, font, visuals.strong_text_color());
232 let size = galley.size() + egui::vec2(16.0, 8.0);
233 let caption = egui::Rect::from_center_size(rect.center(), size);
234 painter.rect_filled(caption, 4.0, visuals.window_fill);
235 painter.rect_stroke(
236 caption,
237 4.0,
238 egui::Stroke::new(1.0, color),
239 egui::StrokeKind::Inside,
240 );
241 painter.galley(caption.center() - galley.size() / 2.0, galley, color);
242 ctx.set_cursor_icon(if takes {
243 egui::CursorIcon::Copy
244 } else {
245 egui::CursorIcon::NoDrop
246 });
247}
248
249fn takers(app: &AppHandle) -> usize {
251 app.bus()
252 .listeners(&FilesDrop::ID)
253 .unwrap_or_default()
254 .iter()
255 .filter(|l| l.id != BROWSER)
256 .count()
257}
258
259pub(super) fn install(kernel: &dyn Bus) {
261 let listened = kernel.listen::<FilesDrop>(
262 BROWSER,
263 ListenOpts::new().owner(OWNER).priority(1000),
264 |drop, did| {
265 for t in &drop.taken {
266 did.push(format!("{BROWSER}: {t}"));
267 }
268 Ok(())
269 },
270 );
271 debug_assert!(listened.is_ok(), "{listened:?}");
272}
273
274impl AppHandle {
275 pub fn request_files_drop(&self, drop: FileDrop) -> Vec<String> {
287 let data = |extra: serde_json::Value| {
288 let mut d = json!({ "window": drop.window, "paths": drop.paths });
289 if let Some(at) = drop.at {
290 d["at"] = json!(at);
291 }
292 if let (Some(d), Some(extra)) = (d.as_object_mut(), extra.as_object()) {
293 d.extend(extra.clone());
294 }
295 d
296 };
297 let open = self.windows_list().iter().any(|w| w.id == drop.window);
298 let did = if open {
299 emit_with::<FilesDrop>(self, drop.clone(), Vec::new())
300 } else {
301 Vec::new()
302 };
303 if did.is_empty() {
304 let reason = if open {
305 "nothing takes files dropped on this window"
306 } else {
307 "no open window of this id"
308 };
309 log::warn!(
310 target: "egui_pop",
311 "{} files dropped on `{}` refused: {reason}",
312 drop.paths.len(),
313 drop.window
314 );
315 self.publish(
316 "egui_pop",
317 None,
318 "files.refused",
319 data(json!({ "request": FilesDrop::ID.as_str(), "reason": reason })),
320 );
321 } else {
322 self.publish(
323 "egui_pop",
324 None,
325 "files.dropped",
326 data(json!({ "did": did })),
327 );
328 }
329 did
330 }
331}