Skip to main content

egui_pop_api/bus/
files.rs

1//! Files dropped from another program, on the bus (ADR 0029).
2//!
3//! Every window's pass (the main window, an application window, a
4//! detached panel's window) reads the files the system says over it or
5//! dropped on it **once, here**: nothing else in egui-pop reads egui's
6//! `hovered_files` or `dropped_files`. Files dropped on a window are its
7//! `pop.files.drop` request ([`FilesDrop`], a [`FileDrop`] naming the window),
8//! asked at the end of that window's pass; whoever takes them is one of its
9//! listeners and says so in the value. Taken, `files.dropped` is said;
10//! taken by nobody, `files.refused` (ADR 0003: never lost without a word).
11//!
12//! Widgets drawn in the pass see the drop through [`system_drag`]. One that
13//! takes it ([`take`], the file browser over one of its targets) is said by
14//! egui-pop's listener [`BROWSER`], first: an application's listener
15//! declared `after` it knows the drop is already taken. While files hover a
16//! window and no widget shows where they would go, the window shows
17//! whether anything takes files ([`end_pass`]).
18
19use 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/// Files dropped on a window: which window, the files, where the pointer
31/// was.
32#[derive(Clone, Debug, PartialEq, Serialize)]
33#[non_exhaustive]
34pub struct FileDrop {
35    /// The window's id in the registry (`main`, an application window's
36    /// id, `panel:<id>`).
37    pub window: String,
38    pub paths: Vec<PathBuf>,
39    /// The pointer in the window, in points, when the system says it.
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub at: Option<[f32; 2]>,
42    /// What widgets of the window's pass took it ([`take`]): said by
43    /// [`BROWSER`].
44    #[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    /// Where the pointer was, in the window's points.
59    pub fn at(mut self, at: [f32; 2]) -> Self {
60        self.at = Some(at);
61        self
62    }
63}
64
65/// Files are dropped on a window (`pop.files.drop`): each listener that takes
66/// them says what it did, one line, in the value. Nobody taking them is a
67/// refusal.
68#[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
77/// The files points, in the order [`super::order_dump`] prints them.
78pub const FILES_POINTS: [&str; 1] = [FilesDrop::ID.as_str()];
79
80/// egui-pop's listener of `pop.files.drop`, first: what the widgets of the
81/// window's pass took (the file browser over one of its targets).
82pub const BROWSER: &str = "pop.files.browser";
83
84/// What a window's pass knows of the files from another program.
85#[derive(Clone, Debug, Default)]
86struct Pass {
87    /// The window, when its pass began here (else a widget drawn outside
88    /// an egui-pop window: it reads egui's input itself).
89    window: Option<String>,
90    hovered: Vec<PathBuf>,
91    /// Files hover, whether or not the system says their paths.
92    hovering: bool,
93    dropped: Vec<PathBuf>,
94    at: Option<egui::Pos2>,
95    /// What widgets took the drop.
96    taken: Vec<String>,
97    /// A widget showed where the hovering files would go.
98    shown: bool,
99}
100
101fn pass_id(ctx: &Context) -> Id {
102    Id::unique(("egui_pop.files.drop", ctx.viewport_id()))
103}
104
105/// Reads egui's input: the one place that does.
106fn 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
129/// A window's pass begins: what the system says of files over it, or
130/// dropped on it, read once.
131pub(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
138/// Files from another program in this pass, for a widget: their paths and
139/// whether they are dropped now (else they hover; their paths may be empty
140/// while they do, some systems say them only on the drop).
141pub(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
156/// A widget of this pass took the files dropped: `what` says how, as
157/// [`BROWSER`] says it on the request.
158pub(crate) fn take(ctx: &Context, what: String) {
159    in_pass(ctx, |p| p.taken.push(what));
160}
161
162/// A widget of this pass showed where the hovering files would go: the
163/// window shows nothing more.
164pub(crate) fn shown(ctx: &Context) {
165    in_pass(ctx, |p| p.shown = true);
166}
167
168/// Changes the window pass's record; outside an egui-pop window's pass
169/// (a widget in plain egui) there is none, and nothing to say.
170fn 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
180/// A window's pass ends: files dropped on it are its `pop.files.drop`; files
181/// hovering it that no widget placed show whether anything takes files.
182pub(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        // egui repaints while files hover; the drop's pass comes.
197        ctx.request_repaint();
198    }
199}
200
201/// Over the whole window: whether its files go somewhere.
202fn 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
249/// The listeners of `pop.files.drop` but egui-pop's own.
250fn 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
259/// Registers egui-pop's listener of `pop.files.drop`.
260pub(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    /// Asks for files dropped on a window (`pop.files.drop`): its listeners run
276    /// now, in their declared order, each that takes them saying so; then
277    /// `files.dropped` is said with what they did, or `files.refused` when
278    /// none took them or the window is not open. What they did, one line
279    /// each.
280    ///
281    /// Every window's pass asks it for the files the system dropped on it;
282    /// an application or a test may ask it too.
283    ///
284    /// <div class="warning">Experimental: may change in any release
285    /// (docs/stability.md).</div>
286    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}