Skip to main content

egui_pop_api/bus/
drag.rs

1//! A drag across windows, on the bus (ADR 0029).
2//!
3//! egui keeps each window's input apart. While the button is held, the
4//! system gives every pointer event to the window the drag began in
5//! (Wayland's and X11's implicit grab, the capture on Windows), whose
6//! pointer keeps following the drag past its edges; no other window sees
7//! the drag, nor the release. egui's own drag payload lives in one
8//! window's passes: it is gone before another window could take it.
9//!
10//! A **drag session** carries any typed payload from the window it began
11//! in to the window it is let go over:
12//!
13//! - the source starts it ([`start`]), naming its kind; `pop.drag.start` is
14//!   asked ([`DragStart`]), then `drag.started` said;
15//! - each pass, the **drop targets** say where they are, by window and by
16//!   id ([`target`]): over one, the target shows where the payload would
17//!   go (per-frame painting, the ADR's exception: no event per pass);
18//! - while the drag lasts, **every target that takes its payload is
19//!   highlighted**, wherever the pointer is, so the user sees where it
20//!   may go; a target that refuses it is not, until hovered (then its
21//!   outline says it refuses, with its reason);
22//! - targets **nest**: a panel's background and the rows or cells inside
23//!   it. Under the pointer, the **most specific** one wins, the smallest
24//!   that contains it (the last registered among equals), whatever the
25//!   order they were registered in: only that one sees the drag over it
26//!   ([`Seen::Over`]) and takes the drop, as VS Code's tree views resolve
27//!   a drop by the element under the pointer, the view as the fallback
28//!   (<https://code.visualstudio.com/api/references/vscode-api#TreeDragAndDropController>);
29//! - let go, the payload is delivered once, to the target under the
30//!   pointer: in the window it began in, or in another window, found from
31//!   the screen's coordinates where the system tells where windows are;
32//!   where it hides them (Wayland), the first window that sees the pointer
33//!   over one of its targets once the drag lets it go takes it, within a
34//!   few passes. A delivery is `pop.drag.drop` ([`DragDrop`]), then
35//!   `drag.dropped`; a target that refuses it says why, in `drag.refused`
36//!   with its reason, as does a drag let go over no target and taken by
37//!   nobody, or cancelled (`Escape`). A source handling a drop in its own
38//!   window by itself (the workbench's tabs into its areas) claims it
39//!   ([`claim`]): `drag.dropped` names what took it.
40//!
41//! **The ghost.** A source says what goes under the pointer ([`Ghost`]:
42//! the first item's thumbnail with the stack's edges and a count, or an
43//! object's icon and name; [`start_with`], [`set_ghost`]); a target the
44//! drag hovers says what a drop would do ([`verdict`]: an [`Action`]
45//! and its title) or refuses it ([`target`]'s `refusal`). The session
46//! paints both at the end of each window's pass, from the kit (the
47//! `drag-ghost`, `drag-ghost-count`, `drag-verdict` and `drop-target`
48//! components): the ghost beside the pointer, the verdict as a symbol on
49//! its corner, the target's outline, and in a tooltip the refusal's
50//! reason at once, the action's title only after a short pause (symbols
51//! first). The look follows established desktops: the stacked, counted
52//! ghost of macOS's Finder (Apple's Human Interface Guidelines, "Drag
53//! and drop", <https://developer.apple.com/design/human-interface-guidelines/drag-and-drop>),
54//! the symbol and verb under Windows Explorer's ghost
55//! (`DROPDESCRIPTION`, <https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/ns-shlobj_core-dropdescription>),
56//! VS Code's named list drags (<https://code.visualstudio.com/api/references/vscode-api#TreeDragAndDropController>)
57//! and darktable's dragged thumbnail (`src/dtgtk/thumbtable.c`,
58//! <https://github.com/darktable-org/darktable>).
59//!
60//! The workbench's tabs and tab groups are carried by the session too, so
61//! their drags are said on the bus; their drop is the workbench's dock
62//! space's (egui_stack's one drag across its windows), which ends the
63//! session where it lands it, or refuses it, at a dock of another window:
64//! a release the space took is never delivered to a target of the
65//! session, nor said twice.
66
67use std::any::Any;
68use std::collections::BTreeMap;
69use std::sync::{Arc, Mutex};
70
71use bus_contract::{Bus, ListenOpts, Point, PointId, PointKind};
72use egui::{Context, Id, Pos2, Rect, Vec2, ViewportId};
73use egui_pop_core::lock;
74use serde::Serialize;
75use serde_json::json;
76
77use super::{OWNER, emit_with};
78use crate::app::AppHandle;
79
80/// How many passes a payload let go outside its window waits for another
81/// window to see the pointer over one of its targets (a pass a frame while
82/// it waits: about a fifth of a second), where the system hides window
83/// positions.
84const RELEASED_PASSES: u8 = 12;
85
86/// The opacity of the outline of a target that takes the drag but is not
87/// under the pointer: the hovered one stands out.
88const CANDIDATE_OPACITY: f32 = 0.45;
89
90/// How long a drag hovers the same target before the title of what a
91/// drop would do shows beside its ghost, in seconds: the symbol says it
92/// first. A refusal's reason shows at once.
93const HINT_PAUSE: f64 = 0.6;
94
95/// Where the ghost sits from the pointer, in points: below and to the
96/// right, clear of the cursor.
97const GHOST_OFFSET: Vec2 = Vec2::new(14.0, 16.0);
98
99/// A drag begins: its kind and the window it began in.
100#[derive(Clone, Debug, PartialEq, Serialize)]
101#[non_exhaustive]
102pub struct DragBegin {
103    /// What is dragged, as the source names it (`tab`, `photos`).
104    pub kind: String,
105    /// The window it began in (`main`, an application window's id,
106    /// `panel:<id>`).
107    pub window: String,
108}
109
110/// A drag let go over a target that takes it.
111#[derive(Clone, Debug, PartialEq, Serialize)]
112#[non_exhaustive]
113pub struct DragDelivery {
114    pub kind: String,
115    /// The window it began in.
116    pub source: String,
117    /// The window it is delivered in.
118    pub window: String,
119    /// The target that takes it, by the id it registered with.
120    pub target: String,
121}
122
123/// A drag begins (`pop.drag.start`): its listeners are told, each saying what
124/// it did in the value.
125#[derive(Debug)]
126pub struct DragStart;
127impl Point for DragStart {
128    const KIND: PointKind = PointKind::Request;
129    const ID: PointId = PointId::new("pop.drag.start");
130    type Input = DragBegin;
131    type Value = Vec<String>;
132}
133
134/// A drag is delivered to a target (`pop.drag.drop`): egui-pop's listener
135/// [`TARGET`] says which, first.
136#[derive(Debug)]
137pub struct DragDrop;
138impl Point for DragDrop {
139    const KIND: PointKind = PointKind::Request;
140    const ID: PointId = PointId::new("pop.drag.drop");
141    type Input = DragDelivery;
142    type Value = Vec<String>;
143}
144
145/// The drag points, in the order [`super::order_dump`] prints them.
146pub const DRAG_POINTS: [&str; 2] = [DragStart::ID.as_str(), DragDrop::ID.as_str()];
147
148/// egui-pop's listener of `pop.drag.drop`, first: the target that took it.
149pub const TARGET: &str = "pop.drag.target";
150
151/// What a drop target sees of a drag of its payload type in a pass.
152#[derive(Debug)]
153#[non_exhaustive]
154pub enum Seen<T> {
155    /// No drag of this type, or not over the target.
156    Nothing,
157    /// Over it, at this point of its window.
158    Over { payload: Arc<T>, at: Pos2 },
159    /// Dragged out of its window where the system hides where windows are
160    /// (Wayland): this window cannot tell whether the pointer is over the
161    /// target until the drag lets it go. The best hint is an outline.
162    Unknown(Arc<T>),
163    /// Let go over it: it is the target's, now, once.
164    Dropped(Arc<T>),
165    /// Let go over it while it refused it: why (said on the bus).
166    Refused { payload: Arc<T>, reason: String },
167}
168
169/// How a drag ended, for its source ([`ended`]).
170#[derive(Clone, Debug, PartialEq)]
171#[non_exhaustive]
172pub enum End {
173    /// Delivered to a target of a window.
174    Dropped { window: String, target: String },
175    /// Let go over a target that refused it.
176    Refused {
177        window: String,
178        target: String,
179        reason: String,
180    },
181    /// Let go over no target: in the window it began in (`inside`), or
182    /// outside every window that could tell. The source may handle it
183    /// ([`claim`]).
184    Left { inside: bool },
185    /// Cancelled (`Escape`).
186    Cancelled,
187}
188
189/// What a drag carries under the pointer: its source says it when the
190/// drag starts ([`start_with`], [`set_ghost`]); the session paints it.
191///
192/// <div class="warning">Experimental: may change in any release
193/// (docs/stability.md).</div>
194#[derive(Clone, Debug, Default, PartialEq)]
195#[non_exhaustive]
196pub enum Ghost {
197    /// Nothing but the cursor (the workbench's tabs draw their own).
198    #[default]
199    None,
200    /// Items with a picture (photos, files): the first one's thumbnail
201    /// (its texture and size, scaled to the kit's `drag-ghost.width`; a
202    /// plain frame without it), the edges of a stack behind it when more
203    /// go, and how many in a badge.
204    Thumbs {
205        first: Option<(egui::TextureId, Vec2)>,
206        count: usize,
207    },
208    /// One object (a keyword, a folder, an album): its icon, a name the
209    /// icon registry resolves (`phosphor:tag`), and its name.
210    Object { icon: String, name: String },
211}
212
213impl Ghost {
214    /// Items with a picture: the first one's thumbnail (its texture and
215    /// size), and how many go.
216    pub fn thumbs(first: Option<(egui::TextureId, Vec2)>, count: usize) -> Ghost {
217        Ghost::Thumbs { first, count }
218    }
219
220    /// One object: its icon's registry name and its name.
221    pub fn object(icon: impl Into<String>, name: impl Into<String>) -> Ghost {
222        Ghost::Object {
223            icon: icon.into(),
224            name: name.into(),
225        }
226    }
227}
228
229/// What a drop on a target would do, its symbol on the ghost.
230///
231/// <div class="warning">Experimental: may change in any release
232/// (docs/stability.md).</div>
233#[derive(Clone, Copy, Debug, PartialEq, Eq)]
234#[non_exhaustive]
235pub enum Action {
236    /// Puts the items in (an album, a list): a plus.
237    Add,
238    /// Moves them there: an arrow.
239    Move,
240    /// Copies them there: two sheets.
241    Copy,
242    /// Gives them a tag or a keyword: a tag.
243    Tag,
244    /// Links them, leaving them where they are: a link.
245    Link,
246}
247
248impl Action {
249    /// Its symbol: the icon registry's name, then a built-in icon where
250    /// the registry lacks it.
251    pub fn icon(self) -> (&'static str, &'static str) {
252        match self {
253            Action::Add => ("phosphor:plus", "plus"),
254            Action::Move => ("phosphor:arrow-right", "chevron-right"),
255            Action::Copy => ("phosphor:copy", "copy"),
256            Action::Tag => ("phosphor:tag", "diamond"),
257            Action::Link => ("phosphor:link", "asterisk"),
258        }
259    }
260}
261
262/// What a target the drag hovers says of it, shown on the ghost.
263///
264/// <div class="warning">Experimental: may change in any release
265/// (docs/stability.md).</div>
266#[derive(Clone, Copy, Debug, PartialEq, Eq)]
267#[non_exhaustive]
268pub enum Verdict {
269    /// It takes the drag; what a drop does, when the target says it.
270    Takes(Option<Action>),
271    /// It refuses it.
272    Refuses,
273}
274
275impl Verdict {
276    /// Its symbol: the registry's name and the built-in one.
277    pub fn icon(self) -> Option<(&'static str, &'static str)> {
278        match self {
279            Verdict::Takes(action) => action.map(Action::icon),
280            Verdict::Refuses => Some(("phosphor:prohibit", "close")),
281        }
282    }
283}
284
285type Payload = Arc<dyn Any + Send + Sync>;
286
287/// A drag in progress.
288struct Session {
289    kind: String,
290    payload: Payload,
291    /// The window it began in, its viewport and its name on the bus.
292    source: ViewportId,
293    source_window: String,
294    /// The source's pointer, in its points: it keeps following the drag
295    /// past the window's edges.
296    at: Pos2,
297    /// The pointer left the source window.
298    outside: bool,
299    /// The source's top-left on the screen, in pixels, and its scale;
300    /// `None` where the system hides window positions (Wayland).
301    origin: Option<(Vec2, f32)>,
302    /// The source's passes since the drag began.
303    pass: u64,
304    /// Let go outside: the source's passes left for a window to take it.
305    released: Option<u8>,
306    /// What goes under the pointer.
307    ghost: Ghost,
308}
309
310/// A target registered in a window's pass.
311#[derive(Clone)]
312struct Registered {
313    id: String,
314    rect: Rect,
315    refusal: Option<String>,
316    /// What a drop would do, and its title ([`verdict`]).
317    action: Option<Action>,
318    title: Option<String>,
319}
320
321/// The target under the pointer in a window, at the end of its last pass.
322#[derive(Clone)]
323struct Under {
324    window: String,
325    target: Registered,
326    /// The source's pass it was found in.
327    pass: u64,
328}
329
330/// A drop waiting for its target's call.
331struct Delivered {
332    window: String,
333    target: String,
334    payload: Payload,
335    refused: Option<String>,
336    /// Passes of its window begun since: one is the target's.
337    passes: u8,
338}
339
340/// What a drag ended as, kept for its source until the next drag.
341struct Ended {
342    kind: String,
343    payload: Payload,
344    source: String,
345    end: End,
346    /// What the source said took a drop it handled itself.
347    claimed: Option<String>,
348    /// Said on the bus.
349    said: bool,
350    /// Taken by its source ([`take_ended`]).
351    taken: bool,
352}
353
354/// What the bus is told at the end of a window's pass.
355enum Say {
356    Start(DragBegin),
357    Drop(DragDelivery),
358    Refused(serde_json::Value),
359}
360
361#[derive(Default)]
362struct State {
363    session: Option<Session>,
364    /// Each window's name on the bus, by viewport, from its pass.
365    windows: BTreeMap<ViewportId, String>,
366    /// The targets registered in each window's pass under way.
367    targets: BTreeMap<ViewportId, Vec<Registered>>,
368    /// The targets each window registered in its last pass, to tell a
369    /// target whether a more specific one lies under the pointer before
370    /// this pass registers it.
371    last_targets: BTreeMap<ViewportId, Vec<Registered>>,
372    /// The target under the pointer, per window, at its last pass's end.
373    under: BTreeMap<ViewportId, Under>,
374    delivered: Vec<Delivered>,
375    ended: Option<Ended>,
376    say: Vec<Say>,
377    /// The target the drag hovers, per window, and since when (the
378    /// window's time): its title waits for [`HINT_PAUSE`].
379    hovered: BTreeMap<ViewportId, (String, f64)>,
380}
381
382impl State {
383    fn window_of(&self, v: ViewportId) -> String {
384        self.windows
385            .get(&v)
386            .cloned()
387            .unwrap_or_else(|| crate::windows::WindowId::MAIN.to_string())
388    }
389
390    /// Ends the session as `end`, said on the bus now unless the source
391    /// may still claim it (let go over no target).
392    fn end(&mut self, end: End) {
393        let Some(s) = self.session.take() else { return };
394        self.under.clear();
395        match &end {
396            End::Dropped { window, target } => self.say.push(Say::Drop(DragDelivery {
397                kind: s.kind.clone(),
398                source: s.source_window.clone(),
399                window: window.clone(),
400                target: target.clone(),
401            })),
402            End::Refused {
403                window,
404                target,
405                reason,
406            } => self.say.push(Say::Refused(json!({
407                "kind": s.kind,
408                "source": s.source_window,
409                "window": window,
410                "target": target,
411                "reason": reason,
412            }))),
413            End::Cancelled => self.say.push(Say::Refused(json!({
414                "kind": s.kind,
415                "source": s.source_window,
416                "window": null,
417                "target": null,
418                "reason": "cancelled",
419            }))),
420            End::Left { .. } => {}
421        }
422        let said = !matches!(end, End::Left { .. });
423        self.ended = Some(Ended {
424            kind: s.kind,
425            payload: s.payload,
426            source: s.source_window,
427            end,
428            claimed: None,
429            said,
430            taken: false,
431        });
432    }
433
434    /// Delivers the session to `target` of `window`: taken, or refused.
435    fn deliver(&mut self, window: String, target: &Registered) {
436        let Some(s) = self.session.as_ref() else {
437            return;
438        };
439        self.delivered.push(Delivered {
440            window: window.clone(),
441            target: target.id.clone(),
442            payload: s.payload.clone(),
443            refused: target.refusal.clone(),
444            passes: 0,
445        });
446        let end = match &target.refusal {
447            Some(reason) => End::Refused {
448                window,
449                target: target.id.clone(),
450                reason: reason.clone(),
451            },
452            None => End::Dropped {
453                window,
454                target: target.id.clone(),
455            },
456        };
457        self.end(end);
458    }
459}
460
461/// The most specific of `targets` under `at`: the smallest containing it,
462/// the last registered among equals (drawn over the others).
463fn most_specific(targets: &[Registered], at: Pos2) -> Option<&Registered> {
464    targets
465        .iter()
466        .enumerate()
467        .filter(|(_, t)| t.rect.contains(at))
468        .min_by(|(i, a), (j, b)| {
469            a.rect
470                .area()
471                .total_cmp(&b.rect.area())
472                .then_with(|| j.cmp(i))
473        })
474        .map(|(_, t)| t)
475}
476
477fn state(ctx: &Context) -> Arc<Mutex<State>> {
478    ctx.data_mut(|d| {
479        d.get_temp_mut_or_default::<Arc<Mutex<State>>>(Id::unique("egui_pop.drag"))
480            .clone()
481    })
482}
483
484/// Starts a drag of `payload` in the window being drawn (`ctx`'s
485/// viewport), as `kind`: a source calls it when its drag starts
486/// (`Response::drag_started`). A drag still in progress is replaced.
487///
488/// <div class="warning">Experimental: may change in any release
489/// (docs/stability.md).</div>
490pub fn start<T: Any + Send + Sync>(ctx: &Context, kind: &str, payload: T) {
491    start_with(ctx, kind, payload, Ghost::None);
492}
493
494/// Starts a drag of `payload` as [`start`] does, `ghost` under the
495/// pointer while it lasts.
496///
497/// <div class="warning">Experimental: may change in any release
498/// (docs/stability.md).</div>
499pub fn start_with<T: Any + Send + Sync>(ctx: &Context, kind: &str, payload: T, ghost: Ghost) {
500    let st = state(ctx);
501    let mut st = lock(&st);
502    let source = ctx.viewport_id();
503    let source_window = st.window_of(source);
504    let at = ctx.input(|i| i.pointer.latest_pos()).unwrap_or(Pos2::ZERO);
505    st.session = None;
506    st.under.clear();
507    st.ended = None;
508    st.say.push(Say::Start(DragBegin {
509        kind: kind.to_string(),
510        window: source_window.clone(),
511    }));
512    st.session = Some(Session {
513        kind: kind.to_string(),
514        payload: Arc::new(payload),
515        source,
516        source_window,
517        at,
518        outside: false,
519        origin: origin(ctx),
520        pass: 0,
521        released: None,
522        ghost,
523    });
524}
525
526/// Gives the drag in progress its ghost (a source that knows it only
527/// once the drag started: its thumbnail loaded, its count known).
528///
529/// <div class="warning">Experimental: may change in any release
530/// (docs/stability.md).</div>
531pub fn set_ghost(ctx: &Context, ghost: Ghost) {
532    if let Some(s) = lock(&state(ctx)).session.as_mut() {
533        s.ghost = ghost;
534    }
535}
536
537/// What a drop on the target `id` (registered this pass by [`target`],
538/// which returned [`Seen::Over`]) would do, and its title: its symbol on
539/// the ghost at once, its title beside it after a short pause. A target
540/// that refuses the drag says why through [`target`]'s `refusal`.
541///
542/// <div class="warning">Experimental: may change in any release
543/// (docs/stability.md).</div>
544pub fn verdict(ctx: &Context, id: &str, action: Action, title: Option<String>) {
545    let st = state(ctx);
546    let mut st = lock(&st);
547    let viewport = ctx.viewport_id();
548    if let Some(t) = st
549        .targets
550        .get_mut(&viewport)
551        .and_then(|ts| ts.iter_mut().rev().find(|t| t.id == id))
552    {
553        t.action = Some(action);
554        t.title = title;
555    }
556}
557
558/// The payload of the drag in progress, when it is a `T`.
559///
560/// <div class="warning">Experimental: may change in any release
561/// (docs/stability.md).</div>
562pub fn payload<T: Any + Send + Sync>(ctx: &Context) -> Option<Arc<T>> {
563    let st = state(ctx);
564    let st = lock(&st);
565    st.session
566        .as_ref()
567        .and_then(|s| s.payload.clone().downcast::<T>().ok())
568}
569
570/// Whether a drag is in progress (held, or let go and waiting for a
571/// window to take it).
572///
573/// <div class="warning">Experimental: may change in any release
574/// (docs/stability.md).</div>
575pub fn active(ctx: &Context) -> bool {
576    lock(&state(ctx)).session.is_some()
577}
578
579/// Whether the drag in progress was let go and waits for another window
580/// to see the pointer.
581pub(crate) fn waiting(ctx: &Context) -> bool {
582    lock(&state(ctx))
583        .session
584        .as_ref()
585        .is_some_and(|s| s.released.is_some())
586}
587
588/// Where the pointer of the drag of a `T` in progress (held, or let go and
589/// waiting for a window to take it) is in the window being drawn (`ctx`'s
590/// viewport), in its points, when it can be known.
591pub(crate) fn pointer_here<T: Any + Send + Sync>(ctx: &Context) -> Option<Pos2> {
592    let st = state(ctx);
593    let st = lock(&st);
594    let s = st.session.as_ref().filter(|s| s.payload.is::<T>())?;
595    pointer_in(s, ctx)
596}
597
598/// How the last drag of a `T` ended, and its payload, while no other drag
599/// began: for its source, to handle a drop over no target itself.
600///
601/// <div class="warning">Experimental: may change in any release
602/// (docs/stability.md).</div>
603pub fn ended<T: Any + Send + Sync>(ctx: &Context) -> Option<(Arc<T>, End)> {
604    let st = state(ctx);
605    let st = lock(&st);
606    let e = st.ended.as_ref().filter(|e| !e.taken)?;
607    Some((e.payload.clone().downcast::<T>().ok()?, e.end.clone()))
608}
609
610/// Takes how the last drag of a `T` ended: [`ended`], once.
611///
612/// <div class="warning">Experimental: may change in any release
613/// (docs/stability.md).</div>
614pub fn take_ended<T: Any + Send + Sync>(ctx: &Context) -> Option<(Arc<T>, End)> {
615    let st = state(ctx);
616    let mut st = lock(&st);
617    let e = st.ended.as_mut().filter(|e| !e.taken)?;
618    let payload = e.payload.clone().downcast::<T>().ok()?;
619    e.taken = true;
620    Some((payload, e.end.clone()))
621}
622
623/// The source handled a drag let go over no target ([`End::Left`]): `what`
624/// took it (the workbench's areas), said as the target of `drag.dropped`.
625///
626/// <div class="warning">Experimental: may change in any release
627/// (docs/stability.md).</div>
628pub fn claim(ctx: &Context, what: &str) {
629    let st = state(ctx);
630    let mut st = lock(&st);
631    if let Some(e) = st.ended.as_mut().filter(|e| !e.said) {
632        e.claimed = Some(what.to_string());
633    }
634}
635
636/// A drop the workbench's dock space took, or refused at a target of its
637/// own (a tab or a tab group let go over a dock of another window): the
638/// drag of a `T` in progress, or the one just let go over no target of
639/// the session and not said yet, ends there, delivered to no target of
640/// the session (the claim rule: a release the space took is never
641/// delivered twice). `drag.dropped` names the window and the target the
642/// space took it in; `drag.refused` the reason, when refused.
643pub(crate) fn taken<T: Any + Send + Sync>(
644    ctx: &Context,
645    window: &str,
646    target: &str,
647    refusal: Option<String>,
648) {
649    let st = state(ctx);
650    let mut st = lock(&st);
651    let end = match refusal {
652        Some(reason) => End::Refused {
653            window: window.to_string(),
654            target: target.to_string(),
655            reason,
656        },
657        None => End::Dropped {
658            window: window.to_string(),
659            target: target.to_string(),
660        },
661    };
662    if st.session.as_ref().is_some_and(|s| s.payload.is::<T>()) {
663        st.end(end);
664        return;
665    }
666    let Some(e) = st
667        .ended
668        .as_mut()
669        .filter(|e| !e.said && e.payload.is::<T>() && matches!(e.end, End::Left { .. }))
670    else {
671        return;
672    };
673    e.said = true;
674    let say = match &end {
675        End::Refused {
676            window,
677            target,
678            reason,
679        } => Say::Refused(json!({
680            "kind": e.kind,
681            "source": e.source,
682            "window": window,
683            "target": target,
684            "reason": reason,
685        })),
686        _ => Say::Drop(DragDelivery {
687            kind: e.kind.clone(),
688            source: e.source.clone(),
689            window: window.to_string(),
690            target: target.to_string(),
691        }),
692    };
693    e.end = end;
694    st.say.push(say);
695}
696
697/// The window's top-left on the screen, in pixels, and its scale, where
698/// the system tells it.
699fn origin(ctx: &Context) -> Option<(Vec2, f32)> {
700    let ppp = ctx.pixels_per_point();
701    ctx.input(|i| i.viewport().inner_rect)
702        .map(|r| (r.min.to_vec2() * ppp, ppp))
703}
704
705/// Where the session's pointer is in the window being drawn (`ctx`), in
706/// its points, when it can be known: the window's own pointer; in the
707/// source window, the drag's; in another window, the drag's carried over
708/// the screen when both windows know where they are (not on Wayland).
709fn pointer_in(s: &Session, ctx: &Context) -> Option<Pos2> {
710    if let Some(p) = ctx.input(|i| i.pointer.hover_pos()) {
711        return Some(p);
712    }
713    if ctx.viewport_id() == s.source {
714        return Some(s.at);
715    }
716    let (origin, ppp) = s.origin?;
717    let inner = ctx.input(|i| i.viewport().inner_rect)?;
718    let screen = origin + s.at.to_vec2() * ppp;
719    Some((screen / ctx.pixels_per_point() - inner.min.to_vec2()).to_pos2())
720}
721
722/// A drop target for a payload of type `T`, in the window being drawn
723/// (`ctx`'s viewport), by its `id` (unique in its window) and its `rect`:
724/// what it sees of a drag this pass. `refusal` says why it does not take
725/// a payload, asked each pass while one is dragged: a target that takes
726/// it is highlighted, wherever the pointer is.
727///
728/// Targets nest: under the pointer, only the most specific (the
729/// smallest containing it) sees [`Seen::Over`] and takes the drop; the
730/// others around it see [`Seen::Nothing`], still highlighted as taking
731/// the drag.
732///
733/// A drop is delivered to the target once: as [`Seen::Dropped`] (or
734/// [`Seen::Refused`]) in the pass it is let go over it, or in this
735/// window's next pass when the release was resolved before the target
736/// was drawn (in another window, from the screen's coordinates).
737///
738/// <div class="warning">Experimental: may change in any release
739/// (docs/stability.md).</div>
740pub fn target<T: Any + Send + Sync>(
741    ctx: &Context,
742    id: &str,
743    rect: Rect,
744    refusal: impl FnOnce(&T) -> Option<String>,
745) -> Seen<T> {
746    let st = state(ctx);
747    let mut st = lock(&st);
748    let viewport = ctx.viewport_id();
749    let window = st.window_of(viewport);
750    // A drop already resolved for this target.
751    if let Some(i) = st
752        .delivered
753        .iter()
754        .position(|d| d.window == window && d.target == id && d.payload.is::<T>())
755    {
756        let d = st.delivered.remove(i);
757        let Ok(payload) = d.payload.downcast::<T>() else {
758            return Seen::Nothing;
759        };
760        return match d.refused {
761            Some(reason) => Seen::Refused { payload, reason },
762            None => Seen::Dropped(payload),
763        };
764    }
765    let Some(s) = st.session.as_ref() else {
766        return Seen::Nothing;
767    };
768    let Ok(payload) = s.payload.clone().downcast::<T>() else {
769        return Seen::Nothing;
770    };
771    let pointer = pointer_in(s, ctx);
772    let own = viewport == s.source;
773    let Some(pointer) = pointer else {
774        return if s.outside && !own {
775            Seen::Unknown(payload)
776        } else {
777            Seen::Nothing
778        };
779    };
780    let released = s.released.is_some();
781    let registered = Registered {
782        id: id.to_string(),
783        rect,
784        refusal: refusal(&payload),
785        action: None,
786        title: None,
787    };
788    if !rect.contains(pointer) {
789        // Not under the pointer: highlighted while it lasts, when it
790        // takes the drag.
791        if !released {
792            st.targets.entry(viewport).or_default().push(registered);
793        }
794        return Seen::Nothing;
795    }
796    let at = pointer;
797    // A more specific target under the pointer, this pass or the last:
798    // it takes the drag, this one is only highlighted.
799    let inner = |ts: Option<&Vec<Registered>>| {
800        ts.into_iter()
801            .flatten()
802            .any(|t| t.id != id && t.rect.contains(at) && t.rect.area() < rect.area())
803    };
804    if !released && (inner(st.targets.get(&viewport)) || inner(st.last_targets.get(&viewport))) {
805        st.targets.entry(viewport).or_default().push(registered);
806        return Seen::Nothing;
807    }
808    // Let go outside its window, where no window could tell it was under
809    // the pointer: the first that sees it over a target takes it.
810    if released && ctx.input(|i| i.pointer.hover_pos()).is_some() {
811        st.deliver(window, &registered);
812        let d = st.delivered.pop().expect("just delivered");
813        return match d.refused {
814            Some(reason) => Seen::Refused { payload, reason },
815            None => Seen::Dropped(payload),
816        };
817    }
818    if released {
819        return Seen::Nothing;
820    }
821    st.targets.entry(viewport).or_default().push(registered);
822    Seen::Over { payload, at }
823}
824
825/// A window's pass begins (`window`: its name on the bus). In the window
826/// a drag began in: its pointer followed; let go, the drag is delivered
827/// to the target found under the pointer in the last passes (in this
828/// window when it is let go inside it, else in the window the screen's
829/// coordinates place it in), else waits a few passes for another window
830/// to see the pointer; `Escape` cancels it.
831pub(crate) fn begin_pass(ctx: &Context, window: &str) {
832    let st = state(ctx);
833    let mut st = lock(&st);
834    let viewport = ctx.viewport_id();
835    st.windows.insert(viewport, window.to_string());
836    st.targets.remove(&viewport);
837    if st.session.is_none() {
838        st.last_targets.clear();
839    }
840    // Drops their target did not take in a whole pass of their window:
841    // forgotten.
842    st.delivered.retain_mut(|d| {
843        if d.window != window {
844            return true;
845        }
846        d.passes += 1;
847        d.passes < 2
848    });
849    let escape = egui_pop_core::focus::cancel_pressed(ctx, egui::Key::Escape);
850    let (latest, released, down) = ctx.input(|i| {
851        (
852            i.pointer.latest_pos(),
853            i.pointer.any_released(),
854            i.pointer.any_down(),
855        )
856    });
857    let viewport_rect = ctx.input(|i| i.viewport_rect());
858    let here = origin(ctx);
859    let (pass, outside) = {
860        let Some(s) = st.session.as_mut().filter(|s| s.source == viewport) else {
861            return;
862        };
863        s.pass += 1;
864        match s.released {
865            Some(0) => None,
866            Some(n) => {
867                s.released = Some(n - 1);
868                ctx.request_repaint();
869                return;
870            }
871            None => {
872                if let Some(p) = latest {
873                    s.at = p;
874                }
875                s.outside = !viewport_rect.contains(s.at);
876                s.origin = here;
877                Some((s.pass, s.outside))
878            }
879        }
880        .unwrap_or((0, true))
881    };
882    if pass == 0 {
883        // Let go outside, and no window took it in time.
884        st.end(End::Left { inside: false });
885        return;
886    }
887    if escape {
888        st.end(End::Cancelled);
889        return;
890    }
891    if !released && down {
892        return;
893    }
894    let fresh = |u: &&Under| u.pass + 1 >= pass;
895    let under = if outside {
896        st.under
897            .iter()
898            .filter(|(v, _)| **v != viewport)
899            .map(|(_, u)| u)
900            .find(fresh)
901            .cloned()
902    } else {
903        st.under.get(&viewport).filter(fresh).cloned()
904    };
905    match under {
906        Some(u) => {
907            st.deliver(u.window, &u.target);
908            ctx.request_repaint();
909        }
910        // No other window to see the pointer.
911        None if outside && st.windows.len() <= 1 => st.end(End::Left { inside: false }),
912        None if outside => {
913            if let Some(s) = st.session.as_mut() {
914                s.released = Some(RELEASED_PASSES);
915            }
916            ctx.request_repaint();
917        }
918        None => st.end(End::Left { inside: true }),
919    }
920}
921
922/// A window's pass ends: the target under the pointer in it kept for the
923/// release (the last registered: drawn over the others), and what the
924/// bus is to be told said.
925pub(crate) fn end_pass(app: &AppHandle, ctx: &Context) {
926    let st = state(ctx);
927    let say = {
928        let mut st = lock(&st);
929        let viewport = ctx.viewport_id();
930        let window = st.window_of(viewport);
931        let targets = st.targets.remove(&viewport).unwrap_or_default();
932        let found = st.session.as_ref().and_then(|s| {
933            let at = pointer_in(s, ctx)?;
934            let t = most_specific(&targets, at)?;
935            Some(Under {
936                window,
937                target: t.clone(),
938                pass: s.pass,
939            })
940        });
941        // What goes under the pointer in this window, painted once the
942        // state is let go.
943        let now = ctx.input(|i| i.time);
944        let hovered = found.as_ref().map(|u| u.target.id.clone());
945        match &hovered {
946            Some(id) if st.hovered.get(&viewport).is_some_and(|(h, _)| h == id) => {}
947            Some(id) => {
948                st.hovered.insert(viewport, (id.clone(), now));
949            }
950            None => {
951                st.hovered.remove(&viewport);
952            }
953        }
954        let since = st.hovered.get(&viewport).map(|(_, t)| now - *t);
955        let shown = st
956            .session
957            .as_ref()
958            .filter(|s| s.released.is_none())
959            .and_then(|s| {
960                let at = pointer_in(s, ctx)?;
961                Some(Shown {
962                    at,
963                    ghost: s.ghost.clone(),
964                    over: found.as_ref().map(|u| u.target.clone()),
965                    accepting: targets
966                        .iter()
967                        .filter(|t| t.refusal.is_none())
968                        .map(|t| (t.id.clone(), t.rect))
969                        .collect(),
970                    since,
971                })
972            });
973        egui_pop_core::pointer::set_ghost_shown(
974            ctx,
975            st.session.as_ref().is_some_and(|s| s.ghost != Ghost::None),
976        );
977        if st.session.is_some() {
978            st.last_targets.insert(viewport, targets);
979        } else {
980            st.last_targets.clear();
981        }
982        match found {
983            Some(u) => {
984                st.under.insert(viewport, u);
985            }
986            None => {
987                st.under.remove(&viewport);
988            }
989        }
990        // A drag let go over no target, in the source's pass: what the
991        // source claimed, or nobody.
992        let source_pass = st
993            .ended
994            .as_ref()
995            .is_some_and(|e| !e.said && st.window_of(viewport) == e.source);
996        let said = if source_pass && let Some(e) = st.ended.as_mut() {
997            e.said = true;
998            let inside = matches!(e.end, End::Left { inside: true });
999            let say = match e.claimed.clone() {
1000                Some(what) => Say::Drop(DragDelivery {
1001                    kind: e.kind.clone(),
1002                    source: e.source.clone(),
1003                    window: if inside {
1004                        e.source.clone()
1005                    } else {
1006                        String::new()
1007                    },
1008                    target: what,
1009                }),
1010                None => Say::Refused(json!({
1011                    "kind": e.kind,
1012                    "source": e.source,
1013                    "window": if inside { json!(e.source) } else { json!(null) },
1014                    "target": null,
1015                    "reason": if inside {
1016                        "nothing takes it here"
1017                    } else {
1018                        "let go outside every window"
1019                    },
1020                })),
1021            };
1022            Some(say)
1023        } else {
1024            None
1025        };
1026        st.say.extend(said);
1027        (std::mem::take(&mut st.say), shown)
1028    };
1029    let (say, shown) = say;
1030    if let Some(shown) = shown {
1031        shown.paint(ctx);
1032    }
1033    for s in say {
1034        match s {
1035            Say::Start(begin) => {
1036                let did = emit_with::<DragStart>(app, begin.clone(), Vec::new());
1037                app.publish(
1038                    "egui_pop",
1039                    None,
1040                    "drag.started",
1041                    json!({ "kind": begin.kind, "window": begin.window, "did": did }),
1042                );
1043            }
1044            Say::Drop(d) => {
1045                let did = emit_with::<DragDrop>(app, d.clone(), Vec::new());
1046                app.publish(
1047                    "egui_pop",
1048                    None,
1049                    "drag.dropped",
1050                    json!({
1051                        "kind": d.kind,
1052                        "source": d.source,
1053                        "window": d.window,
1054                        "target": d.target,
1055                        "did": did,
1056                    }),
1057                );
1058            }
1059            Say::Refused(data) => {
1060                log::info!(target: "egui_pop", "drag refused: {data}");
1061                app.publish("egui_pop", None, "drag.refused", data);
1062            }
1063        }
1064    }
1065}
1066
1067/// What a window last painted of a drag ([`shown`]): its ghost, the
1068/// verdict of the target it hovered (its id) and its hint, for tests and
1069/// agents.
1070///
1071/// <div class="warning">Experimental: may change in any release
1072/// (docs/stability.md).</div>
1073#[derive(Clone, Debug, PartialEq)]
1074#[non_exhaustive]
1075pub struct GhostShown {
1076    pub ghost: Ghost,
1077    pub verdict: Option<Verdict>,
1078    pub target: Option<String>,
1079    /// Every target of the window that takes the drag, highlighted, by
1080    /// the id it registered with, in the order they registered: the one
1081    /// under the pointer among them.
1082    pub accepting: Vec<String>,
1083    /// What its tooltip says, or will once the pause is over: the
1084    /// refusal's reason, or the title of what a drop would do.
1085    pub hint: Option<String>,
1086}
1087
1088/// The ghost the window being drawn (`ctx`'s viewport) showed at the end
1089/// of its last pass, while a drag is in progress; `None` once it ended.
1090///
1091/// <div class="warning">Experimental: may change in any release
1092/// (docs/stability.md).</div>
1093pub fn shown(ctx: &Context) -> Option<GhostShown> {
1094    if !active(ctx) {
1095        return None;
1096    }
1097    ctx.data(|d| d.get_temp::<Arc<GhostShown>>(Id::unique("egui_pop.drag.shown")))
1098        .map(|s| (*s).clone())
1099}
1100
1101/// What a window paints of the drag at the end of its pass.
1102struct Shown {
1103    at: Pos2,
1104    ghost: Ghost,
1105    over: Option<Registered>,
1106    /// The targets of the window that take the drag, highlighted: their
1107    /// ids and rectangles.
1108    accepting: Vec<(String, Rect)>,
1109    /// How long the drag has hovered that target, in seconds.
1110    since: Option<f64>,
1111}
1112
1113impl Shown {
1114    fn paint(self, ctx: &Context) {
1115        let painter = ctx.layer_painter(egui::LayerId::new(
1116            egui::Order::Tooltip,
1117            Id::unique("egui_pop.drag.ghost"),
1118        ));
1119        let verdict = self.over.as_ref().map(|t| match t.refusal {
1120            Some(_) => Verdict::Refuses,
1121            None => Verdict::Takes(t.action),
1122        });
1123        // Every target that takes the drag, faint; the one under the
1124        // pointer, plain.
1125        let over = self.over.as_ref().map(|t| t.id.as_str());
1126        let mut faint = painter.clone();
1127        faint.multiply_opacity(CANDIDATE_OPACITY);
1128        for (id, rect) in &self.accepting {
1129            if Some(id.as_str()) != over {
1130                paint_target(&faint, *rect, false);
1131            }
1132        }
1133        if let Some(t) = &self.over {
1134            paint_target(&painter, t.rect, t.refusal.is_some());
1135        }
1136        ctx.data_mut(|d| {
1137            d.insert_temp(
1138                Id::unique("egui_pop.drag.shown"),
1139                Arc::new(GhostShown {
1140                    ghost: self.ghost.clone(),
1141                    verdict,
1142                    target: self.over.as_ref().map(|t| t.id.clone()),
1143                    accepting: self.accepting.iter().map(|(id, _)| id.clone()).collect(),
1144                    hint: self
1145                        .over
1146                        .as_ref()
1147                        .and_then(|t| t.refusal.clone().or_else(|| t.title.clone())),
1148                }),
1149            );
1150        });
1151        let ghost = paint_ghost(&painter, self.at, &self.ghost, verdict);
1152        // The reason at once; the title once the symbol had its moment.
1153        let hint = self.over.as_ref().and_then(|t| match &t.refusal {
1154            Some(reason) => Some(reason.clone()),
1155            None => t
1156                .title
1157                .clone()
1158                .filter(|_| self.since.is_some_and(|s| s >= HINT_PAUSE)),
1159        });
1160        if let Some(text) = hint {
1161            paint_hint(&painter, ghost, self.at, &text);
1162        } else if self.over.as_ref().is_some_and(|t| t.title.is_some()) {
1163            let left = HINT_PAUSE - self.since.unwrap_or(0.0);
1164            ctx.request_repaint_after(std::time::Duration::from_secs_f64(left.max(0.0)));
1165        }
1166    }
1167}
1168
1169/// Paints the outline of a drop target the drag hovers, from the kit's
1170/// `drop-target`: at rest where it takes the drag, `disabled` where not.
1171fn paint_target(painter: &egui::Painter, rect: Rect, refused: bool) {
1172    use egui_pop_core::kit::{Kit, KitCx, Part, State};
1173    let kit = Kit::of(painter.ctx());
1174    kit.drop_target.paint(
1175        &KitCx {
1176            painter,
1177            ppp: painter.ctx().pixels_per_point(),
1178        },
1179        &Part {
1180            rect: rect.expand(1.0),
1181            room: rect,
1182            state: State::REST.with(State::DISABLED, refused),
1183            label: None,
1184        },
1185    );
1186}
1187
1188/// Paints a drag's ghost beside the pointer at `at`, from the kit (its
1189/// `drag-ghost`, `drag-ghost-count` and `drag-verdict` components), with
1190/// `verdict`'s symbol on its corner; the rectangle it took. The session
1191/// calls it each pass of the window the pointer is in; a page showing
1192/// ghosts (a gallery) may call it too.
1193///
1194/// <div class="warning">Experimental: may change in any release
1195/// (docs/stability.md).</div>
1196pub fn paint_ghost(
1197    painter: &egui::Painter,
1198    at: Pos2,
1199    ghost: &Ghost,
1200    verdict: Option<Verdict>,
1201) -> Rect {
1202    use egui_pop_core::kit::{Kit, KitCx, Part, State};
1203    let ctx = painter.ctx();
1204    let kit = Kit::of(ctx);
1205    let tokens = egui_pop_core::theme::Tokens::of(ctx);
1206    let data = &kit.drag_ghost.data;
1207    let mut faded = painter.clone();
1208    faded.multiply_opacity(data.opacity);
1209    let cx = KitCx {
1210        painter: &faded,
1211        ppp: ctx.pixels_per_point(),
1212    };
1213    let origin = at + GHOST_OFFSET;
1214    let rect = match ghost {
1215        Ghost::None => Rect::from_min_size(origin, Vec2::ZERO),
1216        Ghost::Thumbs { first, count } => {
1217            let side = data.width.max(16.0);
1218            let size = first
1219                .map(|(_, s)| s)
1220                .filter(|s| s.x > 0.0 && s.y > 0.0)
1221                .map_or(Vec2::splat(side), |s| s * (side / s.x.max(s.y)));
1222            let rect = Rect::from_min_size(origin, size);
1223            // The stack's edges behind the first, at most two.
1224            for i in (1..=(*count).saturating_sub(1).min(2)).rev() {
1225                let shift = Vec2::splat(data.offset * i as f32);
1226                kit.drag_ghost.paint(
1227                    &cx,
1228                    &Part {
1229                        rect: rect.translate(shift),
1230                        room: rect,
1231                        state: State::REST,
1232                        label: None,
1233                    },
1234                );
1235            }
1236            kit.drag_ghost.paint(
1237                &cx,
1238                &Part {
1239                    rect,
1240                    room: rect,
1241                    state: State::REST,
1242                    label: None,
1243                },
1244            );
1245            if let Some((texture, _)) = first {
1246                let inner = rect.shrink(kit.drag_ghost.border_room(cx.ppp));
1247                faded.image(
1248                    *texture,
1249                    inner,
1250                    Rect::from_min_max(Pos2::ZERO, Pos2::new(1.0, 1.0)),
1251                    egui::Color32::WHITE,
1252                );
1253            }
1254            if *count > 1 {
1255                let font = egui::FontId::proportional(tokens.font.small);
1256                let galley = ctx.fonts_mut(|f| {
1257                    f.layout_no_wrap(count.to_string(), font, egui::Color32::PLACEHOLDER)
1258                });
1259                let badge = &kit.drag_ghost_count;
1260                let size = badge.measure(galley.size());
1261                let r = Rect::from_center_size(rect.right_top(), size);
1262                badge.paint_part(
1263                    &KitCx {
1264                        painter,
1265                        ppp: cx.ppp,
1266                    },
1267                    &Part {
1268                        rect: r,
1269                        room: r,
1270                        state: State::REST,
1271                        label: Some(&galley),
1272                    },
1273                );
1274            }
1275            rect.expand2(Vec2::splat(data.offset * 2.0))
1276        }
1277        Ghost::Object { icon, name } => {
1278            let font = egui::FontId::proportional(tokens.font.body);
1279            let galley =
1280                ctx.fonts_mut(|f| f.layout_no_wrap(name.clone(), font, egui::Color32::PLACEHOLDER));
1281            let h = data.height.max(galley.size().y);
1282            let icon_side = h - data.padding_x;
1283            let w = data.padding_x * 3.0 + icon_side + galley.size().x;
1284            let rect = Rect::from_min_size(origin, Vec2::new(w, h));
1285            let style = *kit.drag_ghost.style(State::REST);
1286            kit.drag_ghost.paint(
1287                &cx,
1288                &Part {
1289                    rect,
1290                    room: rect,
1291                    state: State::REST,
1292                    label: None,
1293                },
1294            );
1295            let icon_rect = Rect::from_min_size(
1296                Pos2::new(
1297                    rect.left() + data.padding_x,
1298                    rect.center().y - icon_side / 2.0,
1299                ),
1300                Vec2::splat(icon_side),
1301            );
1302            egui_pop_core::icon::registry::resolve(icon, "drag ghost")
1303                .unwrap_or(egui_pop_core::icon::PLACEHOLDER)
1304                .paint(&faded, icon_rect, style.text);
1305            faded.galley(
1306                Pos2::new(
1307                    icon_rect.right() + data.padding_x,
1308                    rect.center().y - galley.size().y / 2.0,
1309                ),
1310                galley,
1311                style.text,
1312            );
1313            rect
1314        }
1315    };
1316    if let Some((name, builtin)) = verdict.and_then(Verdict::icon) {
1317        let badge = &kit.drag_verdict;
1318        let side = badge.data.height.max(12.0);
1319        // On a thumbnail's corner; after an object's chip, clear of its
1320        // name.
1321        let centre = match ghost {
1322            Ghost::Object { .. } => Pos2::new(rect.right() + side / 2.0 + 2.0, rect.center().y),
1323            _ => Pos2::new(rect.right(), rect.bottom()),
1324        };
1325        let r = Rect::from_center_size(centre, Vec2::splat(side));
1326        let refused = verdict == Some(Verdict::Refuses);
1327        let state = State::REST.with(State::DISABLED, refused);
1328        badge.paint(
1329            &KitCx {
1330                painter,
1331                ppp: cx.ppp,
1332            },
1333            &Part {
1334                rect: r,
1335                room: r,
1336                state,
1337                label: None,
1338            },
1339        );
1340        let icon = egui_pop_core::icon::registry::lookup(name)
1341            .or_else(|| egui_pop_core::icon::Icon::by_name(builtin))
1342            .unwrap_or(egui_pop_core::icon::PLACEHOLDER);
1343        icon.paint(painter, r.shrink(side * 0.2), badge.style(state).text);
1344    }
1345    rect
1346}
1347
1348/// Paints what a drop would do, or why not, under the ghost: the kit's
1349/// `tooltip`, as a hover's.
1350fn paint_hint(painter: &egui::Painter, ghost: Rect, at: Pos2, text: &str) {
1351    use egui_pop_core::kit::{Kit, KitCx, Part, State};
1352    let ctx = painter.ctx();
1353    let kit = Kit::of(ctx);
1354    let tokens = egui_pop_core::theme::Tokens::of(ctx);
1355    let font = egui::FontId::proportional(tokens.font.body);
1356    let galley =
1357        ctx.fonts_mut(|f| f.layout_no_wrap(text.to_string(), font, egui::Color32::PLACEHOLDER));
1358    let tip = &kit.tooltip;
1359    let pad = Vec2::new(tip.data.padding_x, tip.data.padding_y);
1360    let top = ghost.bottom().max(at.y) + tip.data.offset.max(4.0);
1361    let rect = Rect::from_min_size(Pos2::new(ghost.left(), top), galley.size() + pad * 2.0);
1362    tip.paint_part(
1363        &KitCx {
1364            painter,
1365            ppp: ctx.pixels_per_point(),
1366        },
1367        &Part {
1368            rect,
1369            room: rect.shrink2(pad),
1370            state: State::REST,
1371            label: Some(&galley),
1372        },
1373    );
1374}
1375
1376/// Registers egui-pop's listener of `pop.drag.drop`.
1377pub(super) fn install(kernel: &dyn Bus) {
1378    let listened = kernel.listen::<DragDrop>(
1379        TARGET,
1380        ListenOpts::new().owner(OWNER).priority(1000),
1381        |d, did| {
1382            did.push(format!("{TARGET}: `{}` in `{}`", d.target, d.window));
1383            Ok(())
1384        },
1385    );
1386    debug_assert!(listened.is_ok(), "{listened:?}");
1387}