Skip to main content

teksilo_core/widget_tree/
drag_drop_impl.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4use super::*;
5
6// App-global stash for the typed payload of an in-flight app-originated OS
7// drag. When an in-app drag escalates to a native OS drag at the window
8// boundary, the OS only carries the serialized MIME bytes — the typed
9// `Box<dyn Any>` fast-path value would be lost. We park the whole `DragPayload`
10// here for the lifetime of the OS drag so that if the drag wanders back over
11// **any** window of this app (the source window or another one), that window
12// can recover the original typed payload and present it as a normal internal
13// drag. Single-threaded GUI ⇒ a thread-local is the process-wide registry, and
14// it is only ever touched on the main thread (escalation and all
15// `*_external_drag` / `handle_os_drag_ended` routing run there; the Wayland
16// dispatch thread only `post_external`s).
17//
18// **Liveness gate.** Recovery is gated on the `live` flag, not on payload
19// presence. `live` is set true by `outbound_begin` (escalation) and cleared by
20// `outbound_end` (the terminal `DragEnded`, or a source-window close). This is
21// what keeps a leaked / stale payload from misclaiming a *later* genuine
22// external drag from another application: `outbound_take_if_live` only hands
23// the payload back while `live`, and `outbound_restash` is a no-op once the
24// drag has ended — so even a racing re-stash (cross-window drop-on-nothing)
25// can't resurrect a finished drag.
26struct OutboundStash {
27    /// True while an app-originated OS drag is in flight.
28    live: bool,
29    /// The parked typed payload, present whenever no window currently holds it
30    /// as a re-entered session.
31    payload: Option<crate::drag_payload::DragPayload>,
32    /// The pointer that started the drag.
33    ///
34    /// Parked beside the payload because **no OS drag protocol names the
35    /// dragging device to the destination**: `wl_data_device`, XDND, OLE
36    /// `IDropTarget` and `NSDraggingDestination` all describe the data and the
37    /// position and say nothing about the hand. So for a drag from another
38    /// application the kind is genuinely unknown — but for our OWN drag
39    /// re-entering one of our windows it is not, and this is where the window
40    /// that recovers the payload also recovers the device, which is what makes
41    /// the re-entered session's hover slop, drop bands and preview clearance
42    /// read the finger rather than a mouse.
43    pointer: Option<crate::pointer::PointerInfo>,
44}
45
46thread_local! {
47    static OUTBOUND: std::cell::RefCell<OutboundStash> = const {
48        std::cell::RefCell::new(OutboundStash {
49            live: false,
50            payload: None,
51            pointer: None,
52        })
53    };
54}
55
56/// Begin an outbound drag: mark live and park the typed payload plus the
57/// pointer that is carrying it.
58fn outbound_begin(payload: crate::drag_payload::DragPayload, pointer: crate::pointer::PointerInfo) {
59    OUTBOUND.with(|s| {
60        let mut s = s.borrow_mut();
61        s.live = true;
62        s.payload = Some(payload);
63        s.pointer = Some(pointer);
64    });
65}
66
67/// Recover the parked payload **only while the drag is live**. Leaves `live`
68/// set (a window now holds the payload as a re-entered session).
69fn outbound_take_if_live() -> Option<crate::drag_payload::DragPayload> {
70    OUTBOUND.with(|s| {
71        let mut s = s.borrow_mut();
72        if s.live { s.payload.take() } else { None }
73    })
74}
75
76/// The pointer of the in-flight outbound drag, while it is live. Read by the
77/// window a re-entered drag lands in, so its session names the real device.
78fn outbound_pointer_if_live() -> Option<crate::pointer::PointerInfo> {
79    OUTBOUND.with(|s| {
80        let s = s.borrow();
81        if s.live { s.pointer } else { None }
82    })
83}
84
85/// Whether an app-originated OS drag is still in flight. A window holding a
86/// re-entered session whose stash has gone reads it to notice that the drag it
87/// is showing feedback for has ended elsewhere.
88fn outbound_is_live() -> bool {
89    OUTBOUND.with(|s| s.borrow().live)
90}
91
92/// Return a re-entered payload to the stash so another window can recover it —
93/// but only if the drag is still live (a racing terminal event may have ended
94/// it first, in which case the payload is dropped).
95fn outbound_restash(payload: crate::drag_payload::DragPayload) {
96    OUTBOUND.with(|s| {
97        let mut s = s.borrow_mut();
98        if s.live {
99            s.payload = Some(payload);
100        }
101    });
102}
103
104/// Whether a payload is currently parked. Test/diagnostic helper.
105#[cfg(test)]
106fn has_outbound_typed() -> bool {
107    OUTBOUND.with(|s| s.borrow().payload.is_some())
108}
109
110/// End the outbound drag: clear the live flag and drop any parked payload.
111/// Idempotent. After this, no window can recover the payload.
112fn outbound_end() {
113    OUTBOUND.with(|s| {
114        let mut s = s.borrow_mut();
115        s.live = false;
116        s.payload = None;
117        s.pointer = None;
118    });
119}
120
121/// The pointer an **inbound OS drag from another application** is credited to.
122///
123/// `PointerKind::Unknown` is the truthful answer, not a hedge: no OS drag
124/// protocol tells the destination which device the source is dragging with, and
125/// `Unknown` reads as precise everywhere a kind is consulted — the same
126/// behaviour every OS drop had before pointers were distinguishable. The id is
127/// the mouse's because the drag is following the system cursor and because an
128/// external session never enters the pointer table.
129fn unknown_external_pointer() -> crate::pointer::PointerInfo {
130    let mut info = crate::pointer::PointerInfo::mouse(crate::pointer::EventTime::ZERO);
131    info.kind = teksilo_tokens::PointerKind::Unknown;
132    info
133}
134
135/// Which half of the drag pipeline [`WidgetTree::drive_drag_session`] runs.
136#[derive(Copy, Clone, PartialEq, Eq, Debug)]
137enum DragDrive {
138    /// Re-target and re-feedback at `position` (`handle_drag_move`).
139    Move,
140    /// Complete the drag at `position` (`handle_drag_drop`).
141    Drop,
142}
143
144impl WidgetTree {
145    /// Run one half of the drag pipeline with the **drag's own pointer**
146    /// installed as the input snapshot.
147    ///
148    /// Every entry point that is not a pointer sample goes through here: an OS
149    /// drag's phases (delivered from a platform thread) and the per-layout drag
150    /// tick. Without it `current_input` holds its default — a mouse — so
151    /// `on_drag_hover` / `on_drag_tick` / `on_drop` were told they were serving
152    /// a mouse for the whole of a finger drag, and the hit test that picks the
153    /// target used a mouse's slop. Saved and restored around the call the same
154    /// way every dispatch site treats the snapshot, so a nested dispatch cannot
155    /// leak it.
156    fn drive_drag_session(
157        &mut self,
158        position: teksilo_canvas::Point,
159        which: DragDrive,
160        ops: &mut dyn crate::window::WindowOps,
161    ) -> Option<crate::drag_payload::DropOutcome> {
162        let pointer = self.active_drag.as_ref().map(|d| d.pointer)?;
163        let saved = std::mem::replace(
164            &mut self.current_input,
165            crate::pointer::InputSnapshot::for_drag_session(pointer),
166        );
167        let outcome = match which {
168            DragDrive::Move => {
169                self.handle_drag_move(position, ops);
170                None
171            }
172            DragDrive::Drop => self.handle_drag_drop(position, ops),
173        };
174        self.current_input = saved;
175        outcome
176    }
177
178    /// Clean up drag preview overlay (if any).
179    ///
180    /// The preview content is a built widget subtree, so it goes through
181    /// `destroy_subtree` like every other teardown: a bare `arena.destroy`
182    /// would leave its animations, animated-quad slots, bindings,
183    /// subscriptions and shortcuts registered until the tree drops.
184    pub(super) fn cleanup_drag_preview(&mut self) {
185        let Some((overlay_id, content_id)) = self
186            .active_drag
187            .as_ref()
188            .map(|drag| (drag.preview_overlay_id, drag.preview_content_id))
189        else {
190            return;
191        };
192        if let Some(overlay_id) = overlay_id {
193            self.overlay_manager.dismiss(overlay_id);
194        }
195        if let Some(content_id) = content_id {
196            self.destroy_subtree(content_id);
197        }
198    }
199
200    /// Cancel the active drag session: fire `on_drag_leave` on the current
201    /// target (if any), dismiss the preview overlay, clear the session and
202    /// release pointer capture. Used by Escape, explicit cancel requests,
203    /// and the source-destroyed salvage in `revalidate_interaction_state`.
204    pub(super) fn cancel_active_drag(&mut self, ops: &mut dyn crate::window::WindowOps) {
205        // A native start asked for and not yet confirmed must not happen after
206        // the drag it was for has ended here.
207        if self.os_drag_pending.take().is_some() {
208            ops.cancel_os_drag();
209        }
210        let prev_target = self.active_drag.as_ref().and_then(|d| d.current_target);
211        // The source widget, so a cancelled in-app drag still notifies its
212        // originator via `on_drag_ended(Cancelled)`. External drags carry no
213        // source (`None`), so they never fire it.
214        let source = self.active_drag.as_ref().and_then(|d| d.source_widget);
215        // Serve the teardown as the drag's own pointer. Every route into here is
216        // one where the current snapshot is about something else or nothing at
217        // all — an Escape key, a layout-pass reap, a platform abort — and a
218        // handler that branches on the device must get the same answer at the end
219        // of a drag as it did in the middle of it. Saved and restored, so a
220        // teardown reached from inside another dispatch leaves that dispatch's
221        // snapshot as it found it.
222        let saved = self.active_drag.as_ref().map(|d| d.pointer).map(|p| {
223            std::mem::replace(
224                &mut self.current_input,
225                crate::pointer::InputSnapshot::for_drag_session(p),
226            )
227        });
228        self.cleanup_drag_preview();
229        self.active_drag = None;
230        self.os_drop_accepted = None;
231        self.release_drag_capture(source);
232        self.current_cursor = crate::widget::CursorIcon::Default;
233        if let Some(prev) = prev_target {
234            self.fire_on_drag_leave(prev, &mut *ops);
235        }
236        if let Some(src) = source {
237            self.fire_on_drag_ended(src, crate::drag_payload::DropOutcome::Cancelled, &mut *ops);
238        }
239        if let Some(saved) = saved {
240            self.current_input = saved;
241        }
242    }
243
244    // --- External (OS) drag-and-drop -----------------------------------
245    //
246    // OS drops (files / text / URLs dragged from another application or the
247    // file manager) reuse the *entire* internal drag pipeline. Rather than a
248    // parallel set of handlers, an external drag synthesises a `DragSession`
249    // carrying a `DragPayload::external(...)` and then drives the same
250    // `handle_drag_move` / `handle_drag_drop` / `cancel_active_drag` paths, so
251    // any widget with `on_drag_hover` / `on_drag_leave` / `on_drop` works for
252    // both internal and external drags. Widgets distinguish the source via
253    // `payload.is_external()` / `payload.files()` etc.
254    //
255    // Differences from internal drags: there is no in-app source widget
256    // (`source_widget = None`), no pointer capture (the OS owns the pointer
257    // during its drag loop), and no in-tree preview overlay (the OS renders
258    // its own drag image).
259
260    /// Begin an external drag session at `position` carrying OS-delivered
261    /// `data`. Establishes the initial hover target and feedback immediately.
262    ///
263    /// # Which device is dragging
264    ///
265    /// A drag from **another application** does not say: none of
266    /// `wl_data_device`, XDND, OLE `IDropTarget` or `NSDraggingDestination`
267    /// carries the source's device to the destination, so the session reports
268    /// [`PointerKind::Unknown`](teksilo_tokens::PointerKind::Unknown) — which
269    /// resolves as precise everywhere a kind is read, i.e. exactly the
270    /// behaviour every OS drop had before pointers were distinguishable.
271    ///
272    /// Our OWN escalated drag re-entering a window is the case that *is*
273    /// knowable, and it does not go through this door blind: the pointer is
274    /// recovered from the outbound stash alongside the typed payload.
275    pub fn begin_external_drag(
276        &mut self,
277        position: teksilo_canvas::Point,
278        data: crate::drag_payload::ExternalDropData,
279        ops: &mut dyn crate::window::WindowOps,
280    ) {
281        // An inbound drag over the window that asked for a native start is that
282        // native drag: while the pointer is held for our drag, no other
283        // application's drag can reach us. The platform has the pointer, so
284        // hand the in-app session over first, as its confirmation would have.
285        if let Some(pending) = self.os_drag_pending {
286            self.confirm_os_drag(pending, &mut *ops);
287        }
288
289        // Defensively clear any stale session (e.g. a re-entered drag that
290        // never delivered a matching leave). cancel_active_drag fires
291        // on_drag_leave on the previous target first.
292        if self.active_drag.is_some() {
293            self.cancel_active_drag(&mut *ops);
294        }
295
296        // Is this our own app's in-flight OS drag wandering (back) over a
297        // window? A non-empty global stash means an app-originated OS drag is
298        // live (only one OS drag exists at a time), so recover the original
299        // typed payload and present it as a normal *internal* drag. In-app
300        // targets then see the typed value — this is what enables a drag to
301        // round-trip out and back, and drag-and-drop between two windows of the
302        // same app. The terminal `on_drag_ended` is owned by the source window
303        // (via `DragEnded`), so this re-entered session carries no
304        // `source_widget` and never fires it on drop.
305        if let Some(mut payload) = outbound_take_if_live() {
306            // Also expose the file/text/URI view derived from the carried MIME,
307            // so the re-entered drag satisfies external-style targets (DropZone)
308            // in addition to typed in-app targets.
309            payload.enrich_external_from_mime();
310            // The device is recoverable here and nowhere else: this is our own
311            // drag coming home, and the stash kept the pointer that armed it.
312            let pointer = outbound_pointer_if_live().unwrap_or_else(unknown_external_pointer);
313            self.active_drag = Some(crate::drag_state::DragSession {
314                payload,
315                pointer,
316                source_widget: None,
317                is_external: false,
318                current_position: position,
319                current_target: None,
320                feedback: crate::drag_state::DropFeedback::NoFeedback,
321                preview_content_id: None,
322                preview_overlay_id: None,
323            });
324            self.os_drag_reentered = true;
325            self.drive_drag_session(position, DragDrive::Move, &mut *ops);
326            return;
327        }
328
329        self.active_drag = Some(crate::drag_state::DragSession {
330            payload: crate::drag_payload::DragPayload::external(data),
331            pointer: unknown_external_pointer(),
332            source_widget: None,
333            is_external: true,
334            current_position: position,
335            current_target: None,
336            feedback: crate::drag_state::DropFeedback::NoFeedback,
337            preview_content_id: None,
338            preview_overlay_id: None,
339        });
340        // No pointer capture, no Grabbing cursor — the OS owns the drag image
341        // and cursor during an external drag.
342        self.drive_drag_session(position, DragDrive::Move, &mut *ops);
343    }
344
345    /// Update an in-flight external drag as the OS reports pointer motion.
346    /// No-op unless an external session — or our own re-entered OS drag, which
347    /// is an internal session — is active.
348    pub fn update_external_drag(
349        &mut self,
350        position: teksilo_canvas::Point,
351        ops: &mut dyn crate::window::WindowOps,
352    ) {
353        // Drives both a genuine external drag and our own re-entered OS drag
354        // (now an internal session). `handle_drag_move` re-stashes and re-exits
355        // if a re-entered drag leaves the window again.
356        if self.active_drag.as_ref().is_some_and(|d| d.is_external) || self.os_drag_reentered {
357            self.drive_drag_session(position, DragDrive::Move, &mut *ops);
358        }
359    }
360
361    /// Complete an external drag with a drop at `position`, firing `on_drop`
362    /// on the target. `data` is the authoritative payload read at drop time;
363    /// if non-empty it replaces the session payload (some backends only have
364    /// the full data at drop, not at enter). No-op unless an external session
365    /// — or our own re-entered OS drag, which is an internal session — is
366    /// active.
367    pub fn end_external_drag(
368        &mut self,
369        position: teksilo_canvas::Point,
370        data: crate::drag_payload::ExternalDropData,
371        ops: &mut dyn crate::window::WindowOps,
372    ) {
373        // Our own OS drag dropped inside an app window: complete it as an
374        // internal drop with the recovered typed payload. The re-entered
375        // session has no `source_widget`, so `handle_drag_drop` fires `on_drop`
376        // on the target but not `on_drag_ended` — the source window fires that
377        // once when the OS posts the terminal `DragEnded`. Clear the global
378        // stash so that trailing event treats the drag as finished.
379        if self.os_drag_reentered {
380            self.os_drag_reentered = false;
381            let outcome = self.drive_drag_session(position, DragDrive::Drop, &mut *ops);
382            // Dropped back on the window that started the drag: what the source
383            // must hear is the in-app outcome, which the platform cannot know
384            // (it reports a copy). Held until the platform's `DragEnded`, which
385            // is what fires the source's `on_drag_ended`. A drop on another
386            // window of the app keeps the platform's outcome.
387            if self.outbound_drag_source.is_some()
388                && let Some(in_app @ crate::drag_payload::DropOutcome::InApp { .. }) = outcome
389            {
390                self.reentered_drop_outcome = Some(in_app);
391            }
392            outbound_end();
393            return;
394        }
395        if !self.active_drag.as_ref().is_some_and(|d| d.is_external) {
396            return;
397        }
398        if !data.is_empty()
399            && let Some(drag) = self.active_drag.as_mut()
400        {
401            drag.payload = crate::drag_payload::DragPayload::external(data);
402        }
403        self.drive_drag_session(position, DragDrive::Drop, &mut *ops);
404    }
405
406    /// End an external drag over this window **for good**: the OS aborted the
407    /// operation, or the app-originated drag this window was holding as a
408    /// re-entered session has finished elsewhere. No drop will follow.
409    ///
410    /// The difference from [`cancel_external_drag`](Self::cancel_external_drag)
411    /// is the re-entered case, and it is the whole reason both exist: a leave
412    /// *re-stashes* the typed payload so the next window the drag enters can
413    /// pick it up, because the OS drag is still in flight. An abort must not —
414    /// re-stashing a dead drag leaves a payload that the next genuine external
415    /// drag from another application could misclaim.
416    ///
417    /// `on_drag_leave` fires on the current target so no highlight is stranded.
418    /// `on_drag_ended` fires **only** for a session with an in-app source, so a
419    /// re-entered session is silent here: the window that started the drag owns
420    /// that notification and fires it once from
421    /// [`handle_os_drag_ended`](Self::handle_os_drag_ended).
422    pub fn abort_external_drag(&mut self, ops: &mut dyn crate::window::WindowOps) {
423        if self.active_drag.is_none() {
424            self.os_drag_reentered = false;
425            return;
426        }
427        self.os_drag_reentered = false;
428        self.cancel_active_drag(&mut *ops);
429    }
430
431    /// Cancel an in-flight external drag (the pointer left the window or the
432    /// OS aborted the operation) without dropping. No-op unless an external
433    /// session — or our own re-entered OS drag, which is an internal session
434    /// that re-exits rather than cancels — is active.
435    pub fn cancel_external_drag(&mut self, ops: &mut dyn crate::window::WindowOps) {
436        // A re-entered OS drag leaving the window again must NOT cancel the
437        // whole drag (the OS drag is still live) — re-stash the typed payload
438        // for the next window it enters and tear down this internal session
439        // without a terminal `on_drag_ended`.
440        if self.os_drag_reentered {
441            self.reexit_outbound(&mut *ops);
442        } else if self.active_drag.as_ref().is_some_and(|d| d.is_external) {
443            self.cancel_active_drag(&mut *ops);
444        }
445    }
446
447    /// Fire `on_drag_tick` on the current drop target (if any). Runs once
448    /// per layout pass while a drag session is active, and the drag asks for
449    /// a pass every frame while its target has the handler
450    /// ([`arm_drag_tick`](Self::arm_drag_tick)), moving or not. The handler
451    /// receives the pointer position in the target's local coordinates.
452    /// Fires from both external and own handler buckets.
453    pub(super) fn process_drag_tick(&mut self, ops: &mut dyn crate::window::WindowOps) {
454        // First: a re-entered OS drag whose OS session has ended elsewhere.
455        self.reap_dead_reentered_drag(&mut *ops);
456        let Some((target_id, position, pointer)) = self
457            .active_drag
458            .as_ref()
459            .and_then(|d| d.current_target.map(|t| (t, d.current_position, d.pointer)))
460        else {
461            return;
462        };
463        if !self.arena.is_active(target_id) {
464            return;
465        }
466        let bounds = self.arena.bounds(target_id);
467        let local = teksilo_canvas::Point::new(position.x - bounds.x, position.y - bounds.y);
468        let (mut ext_handler, mut own_handler) = match self.arena.get_mut(target_id) {
469            Some(node) => (
470                node.external_handlers.on_drag_tick.take(),
471                node.handlers.on_drag_tick.take(),
472            ),
473            None => return,
474        };
475        if ext_handler.is_none() && own_handler.is_none() {
476            return;
477        }
478        // The tick fires from `layout()`, outside any sample, so the snapshot
479        // has to be installed here or the handler is told it is serving a mouse
480        // — which is what made the coarse auto-scroll band unreachable for the
481        // whole of a finger drag.
482        let saved = std::mem::replace(
483            &mut self.current_input,
484            crate::pointer::InputSnapshot::for_drag_session(pointer),
485        );
486        let mut ctx = self.make_event_context(&mut *ops);
487        if let Some(h) = ext_handler.as_mut() {
488            h(local, &mut ctx);
489        }
490        if let Some(h) = own_handler.as_mut() {
491            h(local, &mut ctx);
492        }
493        if let Some(node) = self.arena.get_mut(target_id) {
494            node.external_handlers.on_drag_tick = ext_handler;
495            node.handlers.on_drag_tick = own_handler;
496        }
497        self.collect_from_ctx(ctx, target_id);
498        // If the tick handler scrolled content, the pointer is now over a
499        // different item — refresh the hover pipeline with the same
500        // pointer position so feedback reflects the new content offset.
501        if self.active_drag.is_some() {
502            self.handle_drag_move(position, &mut *ops);
503        }
504        self.current_input = saved;
505    }
506
507    /// End a re-entered OS drag whose OS session has finished somewhere else.
508    ///
509    /// The terminal `DragEnded` is posted to the window that **started** the
510    /// drag, and that window is not necessarily the one currently showing the
511    /// re-entered session: drag a row out of window A, over window B, and let
512    /// the compositor abort it, and B is left holding a live `active_drag`, a
513    /// highlighted drop target and an `os_drag_reentered` flag for a drag that
514    /// no longer exists — for the rest of the process, since the OS will send B
515    /// nothing further. The outbound stash is process-wide and is cleared by
516    /// the terminal event, so "I hold a re-entered session and the stash is
517    /// dead" is the exact condition, and every window runs a layout pass.
518    ///
519    /// Deliberately *not* a fan-out from the terminal event: reaching every
520    /// window's tree from the one being routed to needs the window manager, and
521    /// the condition is already visible from inside each tree.
522    fn reap_dead_reentered_drag(&mut self, ops: &mut dyn crate::window::WindowOps) {
523        if !self.os_drag_reentered || outbound_is_live() {
524            return;
525        }
526        crate::trace_input!(
527            Gestures,
528            "the OS drag this window held as re-entered has ended elsewhere: dropping the session"
529        );
530        self.abort_external_drag(&mut *ops);
531    }
532
533    /// Fire `on_drag_leave` on the given widget (if it has one), mark it
534    /// needs_paint, and process any commands the handler emitted. Used
535    /// whenever a drop target stops being the current target — whether
536    /// because the pointer moved elsewhere, the drop completed, or the
537    /// drag was cancelled. Fires from both external and own buckets.
538    pub(super) fn fire_on_drag_leave(
539        &mut self,
540        target_id: WidgetId,
541        ops: &mut dyn crate::window::WindowOps,
542    ) {
543        if !self.arena.is_active(target_id) {
544            return;
545        }
546        let (mut ext_handler, mut own_handler) = match self.arena.get_mut(target_id) {
547            Some(node) => (
548                node.external_handlers.on_drag_leave.take(),
549                node.handlers.on_drag_leave.take(),
550            ),
551            None => return,
552        };
553        if ext_handler.is_none() && own_handler.is_none() {
554            // Still mark for repaint so any visual artefacts the
555            // framework owns (feedback lines, highlights) clear.
556            self.arena.mark_needs_paint(target_id);
557            return;
558        }
559        let mut ctx = self.make_event_context(&mut *ops);
560        if let Some(h) = ext_handler.as_mut() {
561            h(&mut ctx);
562        }
563        if let Some(h) = own_handler.as_mut() {
564            h(&mut ctx);
565        }
566        if let Some(node) = self.arena.get_mut(target_id) {
567            node.external_handlers.on_drag_leave = ext_handler;
568            node.handlers.on_drag_leave = own_handler;
569        }
570        self.collect_from_ctx(ctx, target_id);
571        self.arena.mark_needs_paint(target_id);
572    }
573
574    /// Fire `on_drag_ended` on a drag's **source** widget with the final
575    /// outcome (in-app drop, OS export, or cancel). Mirrors
576    /// [`Self::fire_on_drag_leave`]'s take/restore-handler discipline.
577    pub(super) fn fire_on_drag_ended(
578        &mut self,
579        source_id: WidgetId,
580        outcome: crate::drag_payload::DropOutcome,
581        ops: &mut dyn crate::window::WindowOps,
582    ) {
583        if !self.arena.is_active(source_id) {
584            return;
585        }
586        // Handlers attached at the widget's creation site live in the
587        // `external_handlers` bucket; those installed from the widget's own
588        // `build()` live in `handlers`. Fire whichever is present (both, if
589        // both) — same dual-bucket discipline as `fire_on_drag_leave`.
590        let (mut ext_handler, mut own_handler) = match self.arena.get_mut(source_id) {
591            Some(node) => (
592                node.external_handlers.on_drag_ended.take(),
593                node.handlers.on_drag_ended.take(),
594            ),
595            None => return,
596        };
597        if ext_handler.is_none() && own_handler.is_none() {
598            return;
599        }
600        let mut ctx = self.make_event_context(&mut *ops);
601        if let Some(h) = ext_handler.as_mut() {
602            h(outcome, &mut ctx);
603        }
604        if let Some(h) = own_handler.as_mut() {
605            h(outcome, &mut ctx);
606        }
607        if let Some(node) = self.arena.get_mut(source_id) {
608            node.external_handlers.on_drag_ended = ext_handler;
609            node.handlers.on_drag_ended = own_handler;
610        }
611        self.collect_from_ctx(ctx, source_id);
612    }
613
614    /// Window content size (logical px) from the last layout proposal, if both
615    /// axes were exact. Used to detect when an in-app drag leaves the window.
616    fn window_content_size(&self) -> Option<(f32, f32)> {
617        Some((self.last_proposal.width?, self.last_proposal.height?))
618    }
619
620    /// Whether `position` is outside this window's content rect. Unknown bounds
621    /// (non-exact proposal) ⇒ never treated as outside.
622    fn is_outside_window(&self, position: teksilo_canvas::Point) -> bool {
623        match self.window_content_size() {
624            Some((w, h)) => {
625                position.x < 0.0 || position.y < 0.0 || position.x > w || position.y > h
626            }
627            None => false,
628        }
629    }
630
631    /// Hand an **internal** drag whose payload is OS-exportable to the platform
632    /// as a native OS drag: when it leaves the window bounds, or, with
633    /// [`OsHandoff::Eager`](crate::drag_payload::OsHandoff::Eager), on a real
634    /// pointer sample (`sample`) anywhere. Returns `true` if it consumed the
635    /// move (handed over, or re-exited a re-entered drag); `false` when the
636    /// in-app flow continues, which includes a start the platform answered
637    /// [`OsDragStart::Pending`](crate::drag_payload::OsDragStart::Pending).
638    fn try_escalate_to_os_drag(
639        &mut self,
640        position: teksilo_canvas::Point,
641        sample: bool,
642        ops: &mut dyn crate::window::WindowOps,
643    ) -> bool {
644        // Already handed off to the OS and currently re-entered into this
645        // window: leaving again must NOT start a second OS drag. Re-stash the
646        // typed payload (so the next window can recover it) and tear the
647        // internal session down without a terminal `on_drag_ended`.
648        if self.os_drag_reentered {
649            if self.is_outside_window(position) {
650                self.reexit_outbound(&mut *ops);
651                return true;
652            }
653            return false;
654        }
655
656        // A start is already in flight: the in-app drag carries on until the
657        // platform confirms it, and must not ask a second time.
658        if self.os_drag_pending.is_some() {
659            return false;
660        }
661
662        // Only a plain internal drag with an exportable payload escalates.
663        let (handoff, dragging) = match self.active_drag.as_ref() {
664            Some(d)
665                if !d.is_external && d.source_widget.is_some() && d.payload.is_os_exportable() =>
666            {
667                (d.payload.os_handoff(), d.pointer)
668            }
669            _ => return false,
670        };
671        // `Eager` asks only from a real pointer sample: macOS needs the live
672        // drag event to start a native drag, and a drag tick runs outside any
673        // sample. A tick leaves the next sample to ask.
674        let eager = handoff == crate::drag_payload::OsHandoff::Eager && sample;
675        if !eager && !self.is_outside_window(position) {
676            return false;
677        }
678        // Built only now: it clones the MIME map, and a drag that stays inside
679        // the window gets here on every pointer move without asking.
680        let Some(data) = self.active_drag.as_ref().map(|d| d.payload.to_outbound()) else {
681            return false;
682        };
683
684        // Ask the platform to start a native OS drag. A refusal (no backend /
685        // test sink, a stale event on macOS) keeps the in-app session intact,
686        // and the next move asks again.
687        match ops.begin_os_drag(data, None, dragging.kind) {
688            crate::drag_payload::OsDragStart::Declined => false,
689            crate::drag_payload::OsDragStart::Pending(drag) => {
690                self.os_drag_pending = Some(drag);
691                false
692            }
693            crate::drag_payload::OsDragStart::Started => {
694                self.hand_session_to_os(None, &mut *ops);
695                true
696            }
697        }
698    }
699
700    /// The platform has started the native drag `drag` this window asked for
701    /// and answered [`OsDragStart::Pending`](crate::drag_payload::OsDragStart::Pending)
702    /// about: hand the in-app session over to it. Routed here by `teksilo-app`
703    /// when a backend reports the start (`ExternalDragEvent::DragStarted`, or,
704    /// for the Windows modal drag loop, just before the loop runs).
705    ///
706    /// A confirmation for any other drag is stale: its in-app drag already
707    /// ended (a release, Escape) and asked the platform to drop the start.
708    /// When nothing else is waiting or running here, the platform is asked
709    /// again to end a native drag that nothing here owns; otherwise the newer
710    /// drag's start replaces it on the platform's side.
711    pub fn confirm_os_drag(
712        &mut self,
713        drag: crate::drag_payload::OsDragId,
714        ops: &mut dyn crate::window::WindowOps,
715    ) {
716        if self.os_drag_pending == Some(drag) {
717            self.os_drag_pending = None;
718            if self.active_drag.is_none() {
719                ops.cancel_os_drag();
720                return;
721            }
722            self.hand_session_to_os(Some(drag), &mut *ops);
723            return;
724        }
725        if self.os_drag_pending.is_none()
726            && self.outbound_drag_source.is_none()
727            && !self.os_drag_reentered
728        {
729            ops.cancel_os_drag();
730        }
731    }
732
733    /// The platform has the pointer: take the in-app session, park its typed
734    /// payload for the OS drag's lifetime and revoke what the press had going.
735    fn hand_session_to_os(
736        &mut self,
737        drag: Option<crate::drag_payload::OsDragId>,
738        ops: &mut dyn crate::window::WindowOps,
739    ) {
740        let Some(dragging) = self.active_drag.as_ref().map(|d| d.pointer) else {
741            return;
742        };
743        self.os_drag_pending = None;
744        self.outbound_drag_id = drag;
745        self.reentered_drop_outcome = None;
746        // Escalated: the OS owns the drag now. Take the in-app session and park
747        // its full (typed) payload in the app-global stash for the OS drag's
748        // lifetime, so any window the drag re-enters can recover it. Remember
749        // the source so the eventual `DragEnded` notifies it.
750        let prev_target = self.active_drag.as_ref().and_then(|d| d.current_target);
751        self.cleanup_drag_preview();
752        let drag = self
753            .active_drag
754            .take()
755            .expect("active_drag present (checked above)");
756        self.os_drop_accepted = None;
757        self.release_drag_capture(drag.source_widget);
758        self.current_cursor = crate::widget::CursorIcon::Default;
759        self.outbound_drag_source = drag.source_widget;
760        outbound_begin(drag.payload, dragging);
761        if let Some(prev) = prev_target {
762            self.fire_on_drag_leave(prev, &mut *ops);
763        }
764        // The OS owns the drag from here. On Wayland, macOS and Windows this
765        // window sees no further move and no `Up` for it, because the release
766        // happens over whatever the drag was dropped on; on X11 winit keeps its
767        // implicit grab and this window still gets them, and the router keeps
768        // them away from a re-entered session (the XDND events drive it) and
769        // swallows the `Up` of the press cancelled below. The source is told through
770        // `on_drag_ended(OsCopy | OsMove | Cancelled)` when the OS reports back,
771        // but anything *else* this press had going (a recognizer mid-drag, an
772        // ancestor still competing) has to be revoked now.
773        //
774        // The pointer to revoke is the **session's**, not `current_pointer_id`:
775        // the handover can be reached from a drag tick (a tick that scrolls can
776        // move the reported position outside the window) or from a platform
777        // confirmation, both outside any sample, where the singular accessor
778        // names the mouse. Cancelling the mouse there would leave the real
779        // contact armed.
780        self.cancel_pointer_to(
781            dragging.id,
782            crate::pointer::CancelReason::OsDragStarted,
783            self.outbound_drag_source,
784            &mut *ops,
785        );
786    }
787
788    /// A re-entered OS drag left this window again: return the typed payload to
789    /// the app-global stash and tear down the internal session, *without* a
790    /// terminal `on_drag_ended` (the OS drag is still in flight).
791    fn reexit_outbound(&mut self, ops: &mut dyn crate::window::WindowOps) {
792        let prev_target = self.active_drag.as_ref().and_then(|d| d.current_target);
793        self.cleanup_drag_preview();
794        let source = self.active_drag.as_ref().and_then(|d| d.source_widget);
795        if let Some(drag) = self.active_drag.take() {
796            outbound_restash(drag.payload);
797        }
798        self.os_drag_reentered = false;
799        self.reentered_drop_outcome = None;
800        self.os_drop_accepted = None;
801        self.release_drag_capture(source);
802        self.current_cursor = crate::widget::CursorIcon::Default;
803        if let Some(prev) = prev_target {
804            self.fire_on_drag_leave(prev, &mut *ops);
805        }
806    }
807
808    /// Resolve an OS (outbound) drag at its terminal event, for a backend
809    /// whose events name no drag (macOS, which starts at once). See
810    /// [`Self::handle_os_drag_ended_for`].
811    pub fn handle_os_drag_ended(
812        &mut self,
813        outcome: crate::drag_payload::DropOutcome,
814        ops: &mut dyn crate::window::WindowOps,
815    ) {
816        self.handle_os_drag_ended_for(None, outcome, ops);
817    }
818
819    /// Resolve an OS (outbound) drag at its terminal event. Clears the global
820    /// typed-payload stash and fires `on_drag_ended(outcome)` once on the
821    /// source widget (set only on the window that started the drag). Routed
822    /// here by `teksilo-app` when the platform backend reports `DragEnded`.
823    ///
824    /// `drag` names the drag the event is about, for a backend that answered
825    /// [`OsDragStart::Pending`](crate::drag_payload::OsDragStart::Pending). The
826    /// end of a start this window is still waiting for (no press serial, no
827    /// selection ownership) ends the in-app drag as the platform says. The
828    /// end of a drag that is neither waiting nor running here is stale and
829    /// changes nothing: it belongs to a drag released before its start,
830    /// whose late event must not end the next one.
831    pub fn handle_os_drag_ended_for(
832        &mut self,
833        drag: Option<crate::drag_payload::OsDragId>,
834        outcome: crate::drag_payload::DropOutcome,
835        ops: &mut dyn crate::window::WindowOps,
836    ) {
837        let waiting = match drag {
838            Some(id) if self.os_drag_pending == Some(id) => true,
839            Some(id) if self.outbound_drag_id == Some(id) => false,
840            Some(id) => {
841                crate::trace_input!(Gestures, "a stale end of OS drag {} is ignored", id.raw());
842                return;
843            }
844            None => self.os_drag_pending.is_some(),
845        };
846        // A start this window was waiting for ended without starting: the drag
847        // ends as the platform says, and the in-app session with it, as it
848        // would have if the start had been answered at once. Nothing of it was
849        // parked, so the stash (perhaps an earlier drag's, still ending) stays.
850        if waiting {
851            self.os_drag_pending = None;
852            self.reentered_drop_outcome = None;
853            self.cancel_active_drag(&mut *ops);
854            return;
855        }
856        // The OS guarantees this terminal event; end the stash so a later drag
857        // from another app can't be mistaken for ours.
858        outbound_end();
859        self.os_drag_reentered = false;
860        self.outbound_drag_id = None;
861        // A drop back on this window was an in-app drop, whatever the platform
862        // reports.
863        let outcome = self.reentered_drop_outcome.take().unwrap_or(outcome);
864        if let Some(source) = self.outbound_drag_source.take() {
865            self.fire_on_drag_ended(source, outcome, &mut *ops);
866        }
867    }
868
869    /// Abort any outbound OS drag this tree participates in, used when the
870    /// window is closing. If this tree is the drag *source*, the whole drag is
871    /// ending (the source object dies with the window) — end the stash so a
872    /// later genuine external drag can't be mistaken for ours. If instead this
873    /// is a non-source window currently holding the re-entered payload, hand it
874    /// back to the stash so another window can still recover it. No
875    /// `on_drag_ended` fires (the window and its handlers are being torn down).
876    pub fn abort_outbound_drag(&mut self) {
877        if self.outbound_drag_source.take().is_some() {
878            outbound_end();
879        } else if self.os_drag_reentered
880            && let Some(drag) = self.active_drag.take()
881        {
882            outbound_restash(drag.payload);
883        }
884        self.os_drag_reentered = false;
885        self.os_drag_pending = None;
886        self.outbound_drag_id = None;
887        self.reentered_drop_outcome = None;
888        self.os_drop_accepted = None;
889    }
890
891    /// Update the drag session on pointer move: find the drop target under the
892    /// pointer and call its `on_drag_hover` handler. For a move that is not a
893    /// pointer sample (a drag tick, a scroll, an OS drag phase); a real sample
894    /// goes through [`Self::handle_drag_sample`].
895    pub(super) fn handle_drag_move(
896        &mut self,
897        position: teksilo_canvas::Point,
898        ops: &mut dyn crate::window::WindowOps,
899    ) {
900        self.drag_move(position, false, ops);
901    }
902
903    /// [`Self::handle_drag_move`] for a real pointer sample, the only move that
904    /// may hand an [`OsHandoff::Eager`](crate::drag_payload::OsHandoff::Eager)
905    /// drag to the platform while the pointer is inside the window.
906    pub(super) fn handle_drag_sample(
907        &mut self,
908        position: teksilo_canvas::Point,
909        ops: &mut dyn crate::window::WindowOps,
910    ) {
911        self.drag_move(position, true, ops);
912    }
913
914    fn drag_move(
915        &mut self,
916        position: teksilo_canvas::Point,
917        sample: bool,
918        ops: &mut dyn crate::window::WindowOps,
919    ) {
920        // Update position on the session
921        if let Some(ref mut drag) = self.active_drag {
922            drag.current_position = position;
923        }
924
925        // If an internal, OS-exportable drag is due for the platform, hand it
926        // over as a native drag and stop the in-app pipeline.
927        if self.try_escalate_to_os_drag(position, sample, &mut *ops) {
928            return;
929        }
930
931        // Update preview overlay placement. `update_placement` only
932        // stores the new enum — the actual overlay bounds are recomputed
933        // by `position_overlays` which runs inside `WidgetTree::layout()`
934        // behind a `needs_layout` gate. Mark the content widget dirty so
935        // the next layout pass actually re-positions the preview instead
936        // of leaving it pinned at (0, 0).
937        let preview_content = self
938            .active_drag
939            .as_ref()
940            .and_then(|d| Some((d.preview_overlay_id?, d.preview_content_id?)));
941        if let Some((overlay_id, content_id)) = preview_content {
942            // Never *under* the contact for a coarse pointer: a preview pinned
943            // to the point a finger reported is behind the hand that is
944            // carrying it, so the user drags a card they cannot see. One branch,
945            // in `OverlayPlacement::at_pointer_for`, shared with every
946            // point-anchored panel — a mouse keeps `AtPointer` byte for byte.
947            let dragging = self.active_drag.as_ref().map(|d| d.pointer);
948            let placement = match dragging {
949                Some(pointer) => {
950                    crate::overlay::OverlayPlacement::at_pointer_for(position, &pointer)
951                }
952                None => crate::overlay::OverlayPlacement::AtPointer(position),
953            };
954            self.overlay_manager.update_placement(overlay_id, placement);
955            self.arena.mark_needs_layout(content_id);
956        }
957
958        // Hit-test to find the widget under the pointer, excluding the drag
959        // preview overlay and its content widget so they don't block hit-testing
960        // of actual drop targets.
961        let exclude_overlay = self.active_drag.as_ref().and_then(|d| d.preview_overlay_id);
962        let exclude_widget = self.active_drag.as_ref().and_then(|d| d.preview_content_id);
963        // Routed for the pointer dragging: a finger reaches a small drop target
964        // through the same widening its press would have used, so hover and
965        // drop agree with each other and with a plain tap.
966        let dragging = self.current_input.pointer;
967        let target =
968            self.hit_test_for_excluding(position, &dragging, exclude_overlay, exclude_widget);
969
970        // Drop-target bubbling: walk up from the hit target through successive
971        // drop targets, firing each one's `on_drag_hover`, and stop at the first
972        // that ENGAGES (returns a non-`NoFeedback` response). A target that
973        // returns `NoFeedback` does not accept this payload, so the drag bubbles
974        // to the next drop target above it — letting a reorderable view behind a
975        // per-row `DropTarget` still receive the drag. Pointer position is passed
976        // to each handler in TARGET-LOCAL coordinates.
977        let mut candidate = target.and_then(|t| self.find_drop_target_at_or_above(t));
978        let mut engaged: Option<WidgetId> = None;
979        let mut engaged_feedback = crate::drag_state::DropFeedback::NoFeedback;
980        let mut bubbled_past: Vec<WidgetId> = Vec::new();
981        while let Some(cand) = candidate {
982            let fb = self.fire_on_drag_hover(cand, position, &mut *ops);
983            if fb.is_engaged() {
984                engaged = Some(cand);
985                engaged_feedback = fb;
986                break;
987            }
988            bubbled_past.push(cand);
989            candidate = self.next_drop_target_above(cand);
990        }
991
992        // Resolve the tracked target and clear stray hover state:
993        // - If an ancestor ENGAGED, every rejecting target we passed is
994        //   transparent (the drag is accepted above) — clear them all so none
995        //   leaves a stuck "forbidden" border.
996        // - If NOTHING engaged, the drag is genuinely rejected: the DEEPEST drop
997        //   target keeps its own reject affordance and becomes the tracked target
998        //   (cleared when the drag moves off); clear only the ancestors above it.
999        let (new_target, new_feedback) = if engaged.is_some() {
1000            for cand in &bubbled_past {
1001                self.fire_on_drag_leave(*cand, &mut *ops);
1002            }
1003            (engaged, engaged_feedback)
1004        } else if let Some((&deepest, rest)) = bubbled_past.split_first() {
1005            for cand in rest {
1006                self.fire_on_drag_leave(*cand, &mut *ops);
1007            }
1008            (Some(deepest), crate::drag_state::DropFeedback::NoFeedback)
1009        } else {
1010            (None, crate::drag_state::DropFeedback::NoFeedback)
1011        };
1012
1013        // Fire `on_drag_leave` on the previously-tracked target when it changes.
1014        // Skip targets already cleared by the per-frame rejecter cleanup above:
1015        // a target that rejected this frame while an ancestor engaged is in
1016        // `bubbled_past` and has already had its `on_drag_leave` fired, so
1017        // re-firing here would deliver two leaves for one pointer move.
1018        let prev_target = self.active_drag.as_ref().and_then(|d| d.current_target);
1019        if prev_target != new_target
1020            && let Some(prev) = prev_target
1021            && !bubbled_past.contains(&prev)
1022        {
1023            self.fire_on_drag_leave(prev, &mut *ops);
1024        }
1025        let engaged_now = new_feedback.is_engaged();
1026        // A re-entered app drag counts: the OS still owns it, its offer is still
1027        // negotiating, and a refusal there must still show the refusing cursor.
1028        // It is not `is_external` — the session was rebuilt as an internal one so
1029        // in-app targets see the typed payload — which is exactly why the flag
1030        // alone would have missed the app's own cross-window drag.
1031        let is_os_drag =
1032            self.os_drag_reentered || self.active_drag.as_ref().is_some_and(|d| d.is_external);
1033        if let Some(ref mut drag) = self.active_drag {
1034            drag.current_target = new_target;
1035            drag.feedback = new_feedback;
1036        }
1037        // Revise the OS's own accept state from the widget's verdict.
1038        //
1039        // An inbound backend has to answer the source *synchronously* — XDND
1040        // requires an `XdndStatus` per position and Wayland wants an
1041        // `accept` + `set_actions` on the offer — long before the widget tree
1042        // has seen the sample, so its first answer can only be about format
1043        // compatibility. That is why the cursor showed "will accept" over a
1044        // target that rejects: nothing ever told the OS otherwise. Pushed only
1045        // on a change, because the OS side is a round trip per call and a
1046        // motion stream would otherwise re-send the same answer every sample.
1047        if is_os_drag && self.os_drop_accepted != Some(engaged_now) {
1048            self.os_drop_accepted = Some(engaged_now);
1049            ops.set_drop_accepted(engaged_now);
1050        }
1051        self.arm_drag_tick();
1052    }
1053
1054    /// Ask for the next frame when the drop target has an `on_drag_tick`
1055    /// handler, so the tick runs on the frame clock and not only when
1056    /// something else lays the window out.
1057    ///
1058    /// Nothing else is sure to: a move inside one row leaves the drop
1059    /// feedback as it was, so it notifies nothing, and a drag with no preview
1060    /// in the tree (an external drag, this application's drag coming back
1061    /// into a window, a header reorder) marks nothing for layout. A pointer
1062    /// held still sends nothing at all. Spring-loaded folders and edge
1063    /// auto-scroll live in the tick. Called after every drag move, a tick's
1064    /// own included, so the frames go on while the target keeps its handler
1065    /// and stop after the drag ends; a window that draws nothing gets them as
1066    /// ticks, the frame tick being part of
1067    /// [`next_unpainted_deadline`](Self::next_unpainted_deadline).
1068    fn arm_drag_tick(&self) {
1069        let Some(target) = self.active_drag.as_ref().and_then(|d| d.current_target) else {
1070            return;
1071        };
1072        let ticks = self.arena.is_active(target)
1073            && self.arena.get(target).is_some_and(|node| {
1074                node.handlers.on_drag_tick.is_some()
1075                    || node.external_handlers.on_drag_tick.is_some()
1076            });
1077        if ticks {
1078            self.request_frame();
1079        }
1080    }
1081
1082    /// Fire `on_drag_hover` on a single drop target and return its response.
1083    /// A drop target that has an `on_drop` handler but no `on_drag_hover`
1084    /// engages optimistically (`Accept`, no visual) so it can still receive the
1085    /// drop; `on_drop` makes the final decision on release.
1086    fn fire_on_drag_hover(
1087        &mut self,
1088        target_id: WidgetId,
1089        position: teksilo_canvas::Point,
1090        ops: &mut dyn crate::window::WindowOps,
1091    ) -> crate::drag_state::DropFeedback {
1092        use crate::drag_state::DropFeedback;
1093        let target_bounds = self.arena.bounds(target_id);
1094        let local =
1095            teksilo_canvas::Point::new(position.x - target_bounds.x, position.y - target_bounds.y);
1096        let (mut ext_handler, mut own_handler, has_on_drop) = match self.arena.get_mut(target_id) {
1097            Some(node) => {
1098                let has_on_drop = node.any_handler(|h| h.on_drop.is_some());
1099                let ext = node.external_handlers.on_drag_hover.take();
1100                let own = node.handlers.on_drag_hover.take();
1101                (ext, own, has_on_drop)
1102            }
1103            None => return DropFeedback::NoFeedback,
1104        };
1105        // Drop-only target (no hover handler): engage optimistically.
1106        if ext_handler.is_none() && own_handler.is_none() {
1107            return if has_on_drop {
1108                DropFeedback::Accept
1109            } else {
1110                DropFeedback::NoFeedback
1111            };
1112        }
1113        let mut feedback = DropFeedback::NoFeedback;
1114        if self.active_drag.is_some() {
1115            let mut ctx = self.make_event_context(&mut *ops);
1116            if let Some(ref drag) = self.active_drag {
1117                if let Some(h) = ext_handler.as_mut() {
1118                    feedback = h(&drag.payload, local, &mut ctx);
1119                }
1120                if let Some(h) = own_handler.as_mut() {
1121                    feedback = h(&drag.payload, local, &mut ctx);
1122                }
1123            }
1124            if let Some(node) = self.arena.get_mut(target_id) {
1125                node.external_handlers.on_drag_hover = ext_handler;
1126                node.handlers.on_drag_hover = own_handler;
1127            }
1128            self.collect_from_ctx(ctx, target_id);
1129            self.arena.mark_needs_paint(target_id);
1130        } else if let Some(node) = self.arena.get_mut(target_id) {
1131            node.external_handlers.on_drag_hover = ext_handler;
1132            node.handlers.on_drag_hover = own_handler;
1133        }
1134        feedback
1135    }
1136
1137    /// The next drop target strictly above `id` (its nearest ancestor with a
1138    /// drop handler) — used to bubble a drag past a non-accepting target.
1139    fn next_drop_target_above(&self, id: WidgetId) -> Option<WidgetId> {
1140        let parent = self.arena.parent(id)?;
1141        self.find_drop_target_at_or_above(parent)
1142    }
1143
1144    /// Complete the drag: fire `on_drop` on the target widget and end the
1145    /// session. Returns how the drag ended, `None` when there was no session.
1146    pub(super) fn handle_drag_drop(
1147        &mut self,
1148        position: teksilo_canvas::Point,
1149        ops: &mut dyn crate::window::WindowOps,
1150    ) -> Option<crate::drag_payload::DropOutcome> {
1151        // Released while the platform was still starting the native drag the
1152        // in-app drag asked for: the drag ends as `Cancelled`, with no drop.
1153        // The drop belongs to whatever the native drag would have been dropped
1154        // on, which nothing knows yet, so landing it in-app could be wrong.
1155        if self.os_drag_pending.is_some() && self.active_drag.is_some() {
1156            self.cancel_active_drag(&mut *ops);
1157            return Some(crate::drag_payload::DropOutcome::Cancelled);
1158        }
1159
1160        // Clean up preview overlay
1161        self.cleanup_drag_preview();
1162
1163        self.active_drag.as_ref()?;
1164
1165        // Determine the drop target while the session is still live. Normally
1166        // it's the target the last hover ENGAGED (drop-target bubbling already
1167        // chose it). For a drop with no prior hover (a quick drag, or a
1168        // programmatic `start_drag` + release), re-run the bubbling engagement at
1169        // the drop position so the drop still lands — and bubbles past a
1170        // non-accepting per-row target exactly as a hover would.
1171        // Ignore a `current_target` whose widget was destroyed since the last
1172        // hover (a rebuild tore it down mid-drag) — otherwise the drop resolves
1173        // to a dead arena id and is silently lost. Fall through to the
1174        // re-hit-test below so the drop still lands on whatever is live now.
1175        let mut drop_target = self
1176            .active_drag
1177            .as_ref()
1178            .and_then(|d| d.current_target)
1179            .filter(|&t| self.arena.is_active(t));
1180        if drop_target.is_none() {
1181            let dropping = self.current_input.pointer;
1182            let hit = self.hit_test_for(position, &dropping);
1183            let mut candidate = hit.and_then(|t| self.find_drop_target_at_or_above(t));
1184            while let Some(cand) = candidate {
1185                if self
1186                    .fire_on_drag_hover(cand, position, &mut *ops)
1187                    .is_engaged()
1188                {
1189                    drop_target = Some(cand);
1190                    break;
1191                }
1192                // Clear the bubbled-past target's hover state so it doesn't stay
1193                // highlighted after the drag ends.
1194                self.fire_on_drag_leave(cand, &mut *ops);
1195                candidate = self.next_drop_target_above(cand);
1196            }
1197        }
1198
1199        // Take the drag session
1200        let drag = self.active_drag.take()?;
1201        self.os_drop_accepted = None;
1202        self.release_drag_capture(drag.source_widget);
1203        self.current_cursor = crate::widget::CursorIcon::Default;
1204        // Source widget so an in-app drop notifies its originator via
1205        // `on_drag_ended`. External drags carry no source.
1206        let source = drag.source_widget;
1207        // Default: landed on nothing ⇒ cancelled. Set to `InApp { accepted }`
1208        // when a drop handler actually runs.
1209        let mut outcome = crate::drag_payload::DropOutcome::Cancelled;
1210
1211        // Fire on_drag_leave on the engaged target before on_drop runs — widgets
1212        // own their feedback state and must be given a chance to clear it
1213        // regardless of whether the drop is accepted.
1214        if let Some(prev) = drop_target {
1215            self.fire_on_drag_leave(prev, &mut *ops);
1216        }
1217
1218        // on_drop is a "decision" handler (returns bool). Prefer own over
1219        // external: the widget's own drop semantics trump any external
1220        // listener. If the own bucket doesn't have it, fall back to
1221        // external. Fires exactly once, not both.
1222        if let Some(target_id) = drop_target {
1223            let target_bounds = self.arena.bounds(target_id);
1224            let local = teksilo_canvas::Point::new(
1225                position.x - target_bounds.x,
1226                position.y - target_bounds.y,
1227            );
1228            let (taken_own, taken_ext) = match self.arena.get_mut(target_id) {
1229                Some(node) => {
1230                    let own = node.handlers.on_drop.take();
1231                    let ext = if own.is_none() {
1232                        node.external_handlers.on_drop.take()
1233                    } else {
1234                        None
1235                    };
1236                    (own, ext)
1237                }
1238                None => (None, None),
1239            };
1240            let picked = if let Some(h) = taken_own {
1241                Some((h, /*is_own=*/ true))
1242            } else {
1243                taken_ext.map(|h| (h, /*is_own=*/ false))
1244            };
1245            if let Some((mut handler, is_own)) = picked {
1246                let mut ctx = self.make_event_context(&mut *ops);
1247                let accepted = handler(drag.payload, local, &mut ctx);
1248                outcome = crate::drag_payload::DropOutcome::InApp { accepted };
1249                if let Some(node) = self.arena.get_mut(target_id) {
1250                    if is_own {
1251                        node.handlers.on_drop = Some(handler);
1252                    } else {
1253                        node.external_handlers.on_drop = Some(handler);
1254                    }
1255                }
1256                self.collect_from_ctx(ctx, target_id);
1257                self.arena.mark_needs_paint(target_id);
1258            }
1259        }
1260        // Notify the source the drag it started has ended (in-app drops only;
1261        // external drags carry no source). Payload was moved into the handler
1262        // above, or dropped (Rust Drop) if unaccepted.
1263        if let Some(src) = source {
1264            self.fire_on_drag_ended(src, outcome, &mut *ops);
1265        }
1266        Some(outcome)
1267    }
1268
1269    /// Walk up from a widget to find the nearest ancestor (or self) with a
1270    /// drop handler (`on_drop` or `on_drag_hover`) in either bucket.
1271    fn find_drop_target_at_or_above(&self, start: WidgetId) -> Option<WidgetId> {
1272        let mut current = Some(start);
1273        while let Some(id) = current {
1274            if let Some(node) = self.arena.get(id)
1275                && node.any_handler(|h| h.on_drop.is_some() || h.on_drag_hover.is_some())
1276            {
1277                return Some(id);
1278            }
1279            current = self.arena.parent(id);
1280        }
1281        None
1282    }
1283}
1284
1285#[cfg(test)]
1286mod tests {
1287    use super::*;
1288    use crate::test_widgets::{FillWidget, StackWidget};
1289    use crate::widget::CursorIcon;
1290    use crate::widget_builder::WidgetBuilder;
1291
1292    #[test]
1293    fn start_drag_creates_session() {
1294        let mut tree = WidgetTree::new();
1295        let source = tree.add(FillWidget::new().on_tap({
1296            move |_pos, ctx: &mut crate::widget::EventContext| {
1297                ctx.start_drag(
1298                    ctx.focus_requests.first().copied().unwrap_or_default(),
1299                    crate::drag_payload::DragPayload::typed(42_u32),
1300                );
1301            }
1302        }));
1303        tree.layout(SizeProposal::exact(100.0, 50.0));
1304
1305        // Manually start a drag via EventContext
1306        let mut ctx = crate::widget::EventContext::new();
1307        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(42_u32));
1308        tree.collect_from_ctx(ctx, source);
1309
1310        assert!(tree.active_drag.is_some());
1311        let drag = tree.active_drag.as_ref().unwrap();
1312        assert_eq!(drag.source_widget, Some(source));
1313        assert!(!drag.is_external);
1314        assert!(drag.payload.has_typed::<u32>());
1315    }
1316
1317    #[test]
1318    fn drag_move_updates_position() {
1319        let mut tree = WidgetTree::new();
1320        let source = tree.add(FillWidget::new());
1321        tree.layout(SizeProposal::exact(200.0, 100.0));
1322
1323        // Start a drag session
1324        let mut ctx = crate::widget::EventContext::new();
1325        ctx.start_drag(source, crate::drag_payload::DragPayload::typed("hello"));
1326        tree.collect_from_ctx(ctx, source);
1327        assert!(tree.active_drag.is_some());
1328
1329        // Move the pointer
1330        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(50.0, 30.0)));
1331
1332        let drag = tree.active_drag.as_ref().unwrap();
1333        assert!((drag.current_position.x - 50.0).abs() < 0.01);
1334        assert!((drag.current_position.y - 30.0).abs() < 0.01);
1335    }
1336
1337    #[test]
1338    fn escape_cancels_drag() {
1339        let mut tree = WidgetTree::new();
1340        let source = tree.add(FillWidget::new());
1341        tree.layout(SizeProposal::exact(200.0, 100.0));
1342
1343        let mut ctx = crate::widget::EventContext::new();
1344        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(99_i32));
1345        tree.collect_from_ctx(ctx, source);
1346        assert!(tree.active_drag.is_some());
1347
1348        tree.press_key(Key::Escape, Modifiers::NONE);
1349        assert!(tree.active_drag.is_none(), "drag should be cancelled");
1350    }
1351
1352    #[test]
1353    fn drop_on_target_fires_handler() {
1354        use std::cell::Cell;
1355        use std::rc::Rc;
1356
1357        let dropped = Rc::new(Cell::new(false));
1358        let dropped_value = Rc::new(Cell::new(0_u32));
1359        let d = dropped.clone();
1360        let dv = dropped_value.clone();
1361
1362        let mut tree = WidgetTree::new();
1363        let source = tree.add(FillWidget::new());
1364        // Target occupies right half (100..200, 0..100)
1365        let _target = tree.add(FillWidget::new().on_drop(move |mut payload, _pos, _ctx| {
1366            d.set(true);
1367            if let Some(val) = payload.take_typed::<u32>() {
1368                dv.set(val);
1369            }
1370            true
1371        }));
1372        tree.layout(SizeProposal::exact(200.0, 100.0));
1373
1374        // Start drag from source
1375        let mut ctx = crate::widget::EventContext::new();
1376        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(42_u32));
1377        tree.collect_from_ctx(ctx, source);
1378
1379        // Drop at a position over the target
1380        tree.dispatch_event(WidgetEvent::pointer_up(
1381            Point::new(150.0, 50.0),
1382            PointerButton::Primary,
1383            Modifiers::NONE,
1384        ));
1385
1386        assert!(tree.active_drag.is_none(), "drag session should be cleared");
1387        assert!(dropped.get(), "on_drop should have been called");
1388        assert_eq!(dropped_value.get(), 42);
1389    }
1390
1391    #[test]
1392    fn drop_on_no_target_cancels() {
1393        let mut tree = WidgetTree::new();
1394        let source = tree.add(FillWidget::new());
1395        tree.layout(SizeProposal::exact(100.0, 50.0));
1396
1397        let mut ctx = crate::widget::EventContext::new();
1398        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(42_u32));
1399        tree.collect_from_ctx(ctx, source);
1400
1401        // Drop outside any widget
1402        tree.dispatch_event(WidgetEvent::pointer_up(
1403            Point::new(999.0, 999.0),
1404            PointerButton::Primary,
1405            Modifiers::NONE,
1406        ));
1407
1408        assert!(tree.active_drag.is_none(), "drag session should be cleared");
1409    }
1410
1411    #[test]
1412    fn drop_falls_through_a_destroyed_current_target() {
1413        // A rebuild that destroys the hovered drop target mid-drag (e.g. a
1414        // docking side disabled while dragging over its rail) must not leave a
1415        // stale `current_target` that swallows the drop into a dead arena id.
1416        // The drop should re-hit-test and land on the live target beneath.
1417        use std::cell::Cell;
1418        use std::rc::Rc;
1419
1420        let bg_dropped = Rc::new(Cell::new(false));
1421        let bg_sink = bg_dropped.clone();
1422
1423        let mut tree = WidgetTree::new();
1424        // Children stack (topmost = last added). Source at the bottom (just the
1425        // drag origin), then the background drop target, then the foreground
1426        // drop target on top.
1427        let source = tree.add(FillWidget::new());
1428        let _bg = tree.add(FillWidget::new().on_drop(move |_p, _pos, _ctx| {
1429            bg_sink.set(true);
1430            true
1431        }));
1432        // Foreground drop target on top — engages on hover so it becomes the
1433        // drag's `current_target`.
1434        let fg = tree.add(
1435            FillWidget::new()
1436                .on_drag_hover(|_payload, _pos, _ctx| {
1437                    crate::drag_state::DropFeedback::InsertionLine {
1438                        y: 50.0,
1439                        width: 200.0,
1440                    }
1441                })
1442                .on_drop(|_, _, _| true),
1443        );
1444        tree.layout(SizeProposal::exact(200.0, 100.0));
1445
1446        let mut ctx = crate::widget::EventContext::new();
1447        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(7_u32));
1448        tree.collect_from_ctx(ctx, source);
1449
1450        // Hover over the foreground target → it becomes `current_target`.
1451        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(100.0, 50.0)));
1452        assert_eq!(
1453            tree.active_drag.as_ref().unwrap().current_target,
1454            Some(fg),
1455            "fg engaged as the current drop target"
1456        );
1457
1458        // Tear the foreground target down mid-drag.
1459        tree.arena.destroy(fg);
1460        assert!(!tree.arena.is_active(fg));
1461
1462        // Drop where fg used to be → must fall through to the live bg, not
1463        // vanish into the destroyed fg id.
1464        tree.dispatch_event(WidgetEvent::pointer_up(
1465            Point::new(100.0, 50.0),
1466            PointerButton::Primary,
1467            Modifiers::NONE,
1468        ));
1469
1470        assert!(tree.active_drag.is_none(), "drag session cleared");
1471        assert!(
1472            bg_dropped.get(),
1473            "drop landed on the live background target, not the destroyed one"
1474        );
1475    }
1476
1477    /// Every competitor the current mouse press enrolled, innermost first.
1478    ///
1479    /// The successor to the deleted `armed_drag_observers()`: the same
1480    /// question, asked of the `PointerSequence` that replaced
1481    /// `drag_observers`.
1482    fn mouse_members(
1483        tree: &WidgetTree,
1484    ) -> Vec<(
1485        WidgetId,
1486        crate::gesture::MemberRole,
1487        crate::gesture::MemberState,
1488    )> {
1489        tree.sequence_members(crate::pointer::PointerId::MOUSE)
1490    }
1491
1492    #[test]
1493    fn drag_arming_walks_to_an_ancestor_without_a_dead_zone() {
1494        // Baseline: pressing a button inside a draggable ancestor enrols the
1495        // ancestor as a `Gesture` member (so a press-drag can start the
1496        // ancestor drag — the cross-widget tap/drag disambiguation).
1497        use crate::gesture::{MemberRole, MemberState};
1498        let mut tree = WidgetTree::new();
1499        let button = tree.add(FillWidget::new().on_tap(|_e, _ctx| {}));
1500        let inner = tree.add(StackWidget::new().child(button));
1501        let ancestor = tree.add(StackWidget::new().child(inner).on_drag(|_phase, _ctx| {}));
1502        tree.layout(SizeProposal::exact(100.0, 100.0));
1503
1504        let b = tree.bounds(button);
1505        tree.pointer_down_button(
1506            Point::new(b.x + b.width / 2.0, b.y + b.height / 2.0),
1507            PointerButton::Primary,
1508        );
1509        assert_eq!(
1510            mouse_members(&tree),
1511            vec![(ancestor, MemberRole::Gesture, MemberState::Possible)],
1512            "the draggable ancestor competes when the button press is not in a dead zone"
1513        );
1514        tree.pointer_up_button(
1515            Point::new(b.x + b.width / 2.0, b.y + b.height / 2.0),
1516            PointerButton::Primary,
1517        );
1518    }
1519
1520    #[test]
1521    fn gesture_dead_zone_blocks_ancestor_drag_arming() {
1522        // The fix: a `gesture_dead_zone` boundary between the button and the
1523        // draggable ancestor stops the enrolment walk — the ancestor is NEVER
1524        // a member, so no amount of pointer jitter while clicking the button
1525        // can start the ancestor's drag (capture-release-proof, unlike a
1526        // recognizer-shadowing absorber).
1527        use crate::widget_builder::WidgetBuilder;
1528        let mut tree = WidgetTree::new();
1529        let button = tree.add(FillWidget::new().on_tap(|_e, _ctx| {}));
1530        let dead_zone = tree.add(StackWidget::new().child(button).gesture_dead_zone(true));
1531        let _ancestor = tree.add(
1532            StackWidget::new()
1533                .child(dead_zone)
1534                .on_drag(|_phase, _ctx| {}),
1535        );
1536        tree.layout(SizeProposal::exact(100.0, 100.0));
1537
1538        let b = tree.bounds(button);
1539        tree.pointer_down_button(
1540            Point::new(b.x + b.width / 2.0, b.y + b.height / 2.0),
1541            PointerButton::Primary,
1542        );
1543        assert!(
1544            mouse_members(&tree).is_empty(),
1545            "a dead zone blocks the draggable ancestor from competing"
1546        );
1547        tree.pointer_up_button(
1548            Point::new(b.x + b.width / 2.0, b.y + b.height / 2.0),
1549            PointerButton::Primary,
1550        );
1551    }
1552
1553    #[test]
1554    fn a_dead_zone_boundary_blocks_a_mouse_exactly_as_it_blocks_a_finger() {
1555        // `gesture_dead_zone` is NOT sugar for `touch_action(NONE)`: a mouse
1556        // ignores touch actions entirely, so the substitution would delete the
1557        // mouse behaviour the flag exists for. Same tree, same press, two
1558        // pointer kinds, one answer.
1559        use crate::pointer::{
1560            BackendDeviceKey, PointerIdAllocator, PointerInfo, PointerPhase, PointerSample,
1561        };
1562        use crate::widget_builder::WidgetBuilder;
1563
1564        let mut tree = WidgetTree::new();
1565        let button = tree.add(FillWidget::new().on_tap(|_e, _ctx| {}));
1566        let dead_zone = tree.add(StackWidget::new().child(button).gesture_dead_zone(true));
1567        tree.add(
1568            StackWidget::new()
1569                .child(dead_zone)
1570                .on_drag(|_phase, _ctx| {}),
1571        );
1572        tree.layout(SizeProposal::exact(100.0, 100.0));
1573        let b = tree.bounds(button);
1574        let at = Point::new(b.x + b.width / 2.0, b.y + b.height / 2.0);
1575
1576        tree.pointer_down_button(at, PointerButton::Primary);
1577        assert!(
1578            mouse_members(&tree).is_empty(),
1579            "the mouse enrols no ancestor across the dead zone"
1580        );
1581        tree.pointer_up_button(at, PointerButton::Primary);
1582
1583        let contact = PointerIdAllocator::global().begin(BackendDeviceKey::DEFAULT, 41);
1584        let sample = |phase| PointerSample {
1585            pointer: PointerInfo::touch(contact, crate::pointer::EventTime::from_millis(1)),
1586            phase,
1587            position: at,
1588            button: None,
1589            modifiers: Modifiers::NONE,
1590            coalesced: Vec::new(),
1591        };
1592        tree.dispatch_pointer(sample(PointerPhase::Down));
1593        assert!(
1594            tree.sequence_members(contact).is_empty(),
1595            "and neither does a finger"
1596        );
1597        tree.dispatch_pointer(sample(PointerPhase::Up));
1598    }
1599
1600    #[test]
1601    fn drag_hover_calls_on_drag_hover() {
1602        use std::cell::Cell;
1603        use std::rc::Rc;
1604
1605        let hover_count = Rc::new(Cell::new(0));
1606        let hc = hover_count.clone();
1607
1608        let mut tree = WidgetTree::new();
1609        let source = tree.add(FillWidget::new());
1610        let _target = tree.add(
1611            FillWidget::new()
1612                .on_drag_hover(move |_payload, _pos, _ctx| {
1613                    hc.set(hc.get() + 1);
1614                    crate::drag_state::DropFeedback::InsertionLine {
1615                        y: 50.0,
1616                        width: 200.0,
1617                    }
1618                })
1619                .on_drop(|_, _, _| true),
1620        );
1621        tree.layout(SizeProposal::exact(200.0, 100.0));
1622
1623        // Start drag
1624        let mut ctx = crate::widget::EventContext::new();
1625        ctx.start_drag(source, crate::drag_payload::DragPayload::typed("test"));
1626        tree.collect_from_ctx(ctx, source);
1627
1628        // Move over the target
1629        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(150.0, 50.0)));
1630
1631        assert!(
1632            hover_count.get() > 0,
1633            "on_drag_hover should have been called"
1634        );
1635    }
1636
1637    /// Regression: a rejecting per-row target nested under an engaging ancestor
1638    /// must receive exactly ONE `on_drag_leave` for the pointer move that flips
1639    /// the ancestor from idle to engaged — not two. The per-frame rejecter
1640    /// cleanup (it's in `bubbled_past`) and the tracked-target-change cleanup
1641    /// (it was last frame's `current_target`) used to fire independently.
1642    #[test]
1643    fn rejecter_under_engaging_ancestor_leaves_once() {
1644        use std::cell::Cell;
1645        use std::rc::Rc;
1646
1647        let leaves = Rc::new(Cell::new(0));
1648        let lv = leaves.clone();
1649        // The ancestor only engages once we flip this between the two moves,
1650        // reproducing "frame 1 nothing engages, frame 2 the ancestor does".
1651        let engage = Rc::new(Cell::new(false));
1652        let eg = engage.clone();
1653
1654        let mut tree = WidgetTree::new();
1655        let source = tree.add(FillWidget::new());
1656
1657        // Deepest target: always rejects (NoFeedback), counts its leaves.
1658        let child = tree.add(
1659            FillWidget::new()
1660                .on_drag_hover(|_payload, _pos, _ctx| crate::drag_state::DropFeedback::NoFeedback)
1661                .on_drag_leave(move |_ctx| lv.set(lv.get() + 1)),
1662        );
1663        // Ancestor container wrapping the child: engages conditionally.
1664        let _ancestor = tree.add(StackWidget::new().child(child).on_drag_hover(
1665            move |_payload, _pos, _ctx| {
1666                if eg.get() {
1667                    crate::drag_state::DropFeedback::Accept
1668                } else {
1669                    crate::drag_state::DropFeedback::NoFeedback
1670                }
1671            },
1672        ));
1673        tree.layout(SizeProposal::exact(200.0, 100.0));
1674
1675        let mut ctx = crate::widget::EventContext::new();
1676        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(7_u32));
1677        tree.collect_from_ctx(ctx, source);
1678
1679        // Frame 1: nothing engages → child becomes the tracked (rejecting) target.
1680        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(100.0, 50.0)));
1681        assert_eq!(
1682            tree.active_drag.as_ref().unwrap().current_target,
1683            Some(child)
1684        );
1685        assert_eq!(leaves.get(), 0, "no leave yet — child is freshly tracked");
1686
1687        // Frame 2: ancestor engages while child still rejects.
1688        engage.set(true);
1689        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(101.0, 50.0)));
1690
1691        assert_eq!(
1692            leaves.get(),
1693            1,
1694            "child must receive exactly one on_drag_leave, not two"
1695        );
1696    }
1697
1698    #[test]
1699    fn drop_outside_window_cancels() {
1700        let mut tree = WidgetTree::new();
1701        let source = tree.add(FillWidget::new());
1702        tree.layout(SizeProposal::exact(100.0, 50.0));
1703
1704        let mut ctx = crate::widget::EventContext::new();
1705        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(42_u32));
1706        tree.collect_from_ctx(ctx, source);
1707        assert!(tree.active_drag.is_some());
1708
1709        // PointerUp far outside any widget
1710        tree.dispatch_event(WidgetEvent::pointer_up(
1711            Point::new(-100.0, -100.0),
1712            PointerButton::Primary,
1713            Modifiers::NONE,
1714        ));
1715
1716        assert!(tree.active_drag.is_none(), "drag should be cleared");
1717    }
1718
1719    #[test]
1720    fn drop_target_rejects_wrong_type() {
1721        use std::cell::Cell;
1722        use std::rc::Rc;
1723
1724        let accepted = Rc::new(Cell::new(false));
1725        let a = accepted.clone();
1726
1727        let mut tree = WidgetTree::new();
1728        let source = tree.add(FillWidget::new());
1729        // Target only accepts String payloads
1730        let _target = tree.add(
1731            FillWidget::new()
1732                .on_drag_hover(|payload, _pos, _ctx| {
1733                    if payload.has_typed::<String>() {
1734                        crate::drag_state::DropFeedback::InsertionLine {
1735                            y: 0.0,
1736                            width: 100.0,
1737                        }
1738                    } else {
1739                        crate::drag_state::DropFeedback::NoFeedback
1740                    }
1741                })
1742                .on_drop(move |payload, _pos, _ctx| {
1743                    if payload.has_typed::<String>() {
1744                        a.set(true);
1745                        true
1746                    } else {
1747                        false
1748                    }
1749                }),
1750        );
1751        tree.layout(SizeProposal::exact(200.0, 100.0));
1752
1753        // Drag a u32 (not String)
1754        let mut ctx = crate::widget::EventContext::new();
1755        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(42_u32));
1756        tree.collect_from_ctx(ctx, source);
1757
1758        tree.dispatch_event(WidgetEvent::pointer_up(
1759            Point::new(150.0, 50.0),
1760            PointerButton::Primary,
1761            Modifiers::NONE,
1762        ));
1763
1764        assert!(!accepted.get(), "on_drop should reject wrong payload type");
1765    }
1766
1767    #[test]
1768    fn inter_widget_drop_transfers_payload() {
1769        use std::cell::Cell;
1770        use std::rc::Rc;
1771
1772        let received_value = Rc::new(Cell::new(0_u32));
1773        let rv = received_value.clone();
1774
1775        let mut tree = WidgetTree::new();
1776        let source = tree.add(FillWidget::new());
1777        let _target = tree.add(
1778            FillWidget::new()
1779                .on_drag_hover(|_payload, _pos, _ctx| {
1780                    crate::drag_state::DropFeedback::InsertionLine {
1781                        y: 0.0,
1782                        width: 100.0,
1783                    }
1784                })
1785                .on_drop(move |mut payload, _pos, _ctx| {
1786                    if let Some(val) = payload.take_typed::<u32>() {
1787                        rv.set(val);
1788                        true
1789                    } else {
1790                        false
1791                    }
1792                }),
1793        );
1794        tree.layout(SizeProposal::exact(200.0, 100.0));
1795
1796        // Start drag from source with typed payload
1797        let mut ctx = crate::widget::EventContext::new();
1798        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(777_u32));
1799        tree.collect_from_ctx(ctx, source);
1800
1801        // Drop on target
1802        tree.dispatch_event(WidgetEvent::pointer_up(
1803            Point::new(150.0, 50.0),
1804            PointerButton::Primary,
1805            Modifiers::NONE,
1806        ));
1807
1808        assert_eq!(
1809            received_value.get(),
1810            777,
1811            "Target should receive the typed payload from source"
1812        );
1813    }
1814
1815    #[test]
1816    fn drop_on_child_walks_up_to_ancestor_drop_target() {
1817        use crate::test_widgets::StackWidget;
1818        use std::cell::Cell;
1819        use std::rc::Rc;
1820
1821        // Parent container with `on_drop`; child has no drop handler. The
1822        // framework should walk up from the hit target to find the parent.
1823        let parent_fired = Rc::new(Cell::new(false));
1824        let pf = parent_fired.clone();
1825
1826        let mut tree = WidgetTree::new();
1827        let source = tree.add(FillWidget::new());
1828        let child = tree.add(FillWidget::new());
1829        let _parent = tree.add(StackWidget::new().child(child).on_drop(
1830            move |_payload, _pos, _ctx| {
1831                pf.set(true);
1832                true
1833            },
1834        ));
1835        tree.layout(SizeProposal::exact(200.0, 100.0));
1836
1837        // Start a drag.
1838        let mut ctx = crate::widget::EventContext::new();
1839        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(1_u8));
1840        tree.collect_from_ctx(ctx, source);
1841
1842        // Drop at the child's center. Hit test lands on the child; drop
1843        // should bubble up to the parent StackWidget.
1844        tree.dispatch_event(WidgetEvent::pointer_up(
1845            Point::new(100.0, 50.0),
1846            PointerButton::Primary,
1847            Modifiers::NONE,
1848        ));
1849
1850        assert!(
1851            parent_fired.get(),
1852            "Parent's on_drop should fire via ancestor walk"
1853        );
1854    }
1855
1856    #[test]
1857    fn drop_bubbles_past_a_rejecting_child_to_ancestor() {
1858        use crate::test_widgets::StackWidget;
1859        use std::cell::Cell;
1860        use std::rc::Rc;
1861
1862        // A child drop target that REJECTS this payload (its `on_drag_hover`
1863        // returns `NoFeedback` and `on_drop` returns `false`) must NOT swallow
1864        // the drag — it bubbles to the accepting parent. This is the
1865        // per-row-`DropTarget`-over-a-reorderable-view case.
1866        let child_drop = Rc::new(Cell::new(false));
1867        let parent_drop = Rc::new(Cell::new(false));
1868        let cd = child_drop.clone();
1869        let pd = parent_drop.clone();
1870
1871        let mut tree = WidgetTree::new();
1872        let source = tree.add(FillWidget::new());
1873        let child = tree.add(
1874            FillWidget::new()
1875                .on_drag_hover(|_p, _pos, _ctx| crate::drag_state::DropFeedback::NoFeedback)
1876                .on_drop(move |_p, _pos, _ctx| {
1877                    cd.set(true);
1878                    false // reject → the framework should bubble past
1879                }),
1880        );
1881        let _parent = tree.add(
1882            StackWidget::new()
1883                .child(child)
1884                .on_drop(move |_p, _pos, _ctx| {
1885                    pd.set(true);
1886                    true
1887                }),
1888        );
1889        tree.layout(SizeProposal::exact(200.0, 100.0));
1890
1891        let mut ctx = crate::widget::EventContext::new();
1892        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(7_u8));
1893        tree.collect_from_ctx(ctx, source);
1894
1895        // Hover over the child (its on_drag_hover runs → NoFeedback → bubble),
1896        // then release there.
1897        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(100.0, 50.0)));
1898        tree.dispatch_event(WidgetEvent::pointer_up(
1899            Point::new(100.0, 50.0),
1900            PointerButton::Primary,
1901            Modifiers::NONE,
1902        ));
1903
1904        assert!(parent_drop.get(), "drop bubbles to the accepting ancestor");
1905        assert!(
1906            !child_drop.get(),
1907            "the rejecting child must not receive the drop"
1908        );
1909    }
1910
1911    #[test]
1912    fn drag_preview_overlay_created_and_dismissed() {
1913        let mut tree = WidgetTree::new();
1914        let source = tree.add(FillWidget::new());
1915        tree.layout(SizeProposal::exact(100.0, 50.0));
1916
1917        let overlay_count_before = tree.overlay_manager().len();
1918
1919        // Start drag with a preview widget.
1920        let mut ctx = crate::widget::EventContext::new();
1921        ctx.start_drag_with_preview(
1922            source,
1923            crate::drag_payload::DragPayload::typed(0_u32),
1924            Box::new(FillWidget::new()),
1925        );
1926        tree.collect_from_ctx(ctx, source);
1927
1928        assert!(tree.active_drag.is_some(), "drag session should be active");
1929        assert!(
1930            tree.active_drag
1931                .as_ref()
1932                .unwrap()
1933                .preview_overlay_id
1934                .is_some(),
1935            "preview overlay id should be recorded"
1936        );
1937        assert_eq!(
1938            tree.overlay_manager().len(),
1939            overlay_count_before + 1,
1940            "overlay count should increase by one for the preview"
1941        );
1942
1943        // Drop outside any target — cleanup should remove the overlay.
1944        tree.dispatch_event(WidgetEvent::pointer_up(
1945            Point::new(999.0, 999.0),
1946            PointerButton::Primary,
1947            Modifiers::NONE,
1948        ));
1949
1950        assert!(tree.active_drag.is_none(), "drag session should be cleared");
1951        assert_eq!(
1952            tree.overlay_manager().len(),
1953            overlay_count_before,
1954            "preview overlay should be dismissed on drop"
1955        );
1956    }
1957
1958    #[test]
1959    fn drag_preview_teardown_releases_what_its_content_registered() {
1960        #[derive(Debug)]
1961        struct SpinningPreview;
1962        impl Widget for SpinningPreview {
1963            fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
1964                let _ = ctx.animated_quad(crate::animated_quad::AnimatedQuadKind::SpinnerArc {
1965                    period: std::time::Duration::from_secs(1),
1966                    arc_fraction: 0.25,
1967                    stroke_fraction: 0.12,
1968                    color: teksilo_tokens::Color::RED.into(),
1969                });
1970                Vec::new()
1971            }
1972            fn layout_response(
1973                &self,
1974                _: SizeProposal,
1975                _: &crate::widget::LayoutContext,
1976            ) -> crate::widget::LayoutResponse {
1977                teksilo_canvas::Size::new(20.0, 20.0).into()
1978            }
1979        }
1980
1981        let mut tree = WidgetTree::new();
1982        let source = tree.add(FillWidget::new());
1983        tree.layout(SizeProposal::exact(100.0, 50.0));
1984        let mut ctx = crate::widget::EventContext::new();
1985        ctx.start_drag_with_preview(
1986            source,
1987            crate::drag_payload::DragPayload::typed(0_u32),
1988            Box::new(SpinningPreview),
1989        );
1990        tree.collect_from_ctx(ctx, source);
1991        assert_eq!(tree.animated_quad_count(), 1, "the preview's build ran");
1992
1993        tree.dispatch_event(WidgetEvent::pointer_up(
1994            Point::new(999.0, 999.0),
1995            PointerButton::Primary,
1996            Modifiers::NONE,
1997        ));
1998        assert!(tree.active_drag.is_none());
1999        assert_eq!(
2000            tree.animated_quad_count(),
2001            0,
2002            "tearing the preview down must release its animated-quad slot"
2003        );
2004    }
2005
2006    #[test]
2007    fn drag_preview_follows_pointer_position() {
2008        let mut tree = WidgetTree::new();
2009        let source = tree.add(FillWidget::new());
2010        tree.layout(SizeProposal::exact(200.0, 100.0));
2011
2012        let mut ctx = crate::widget::EventContext::new();
2013        ctx.start_drag_with_preview(
2014            source,
2015            crate::drag_payload::DragPayload::typed("p"),
2016            Box::new(FillWidget::new()),
2017        );
2018        tree.collect_from_ctx(ctx, source);
2019
2020        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(73.0, 41.0)));
2021
2022        let drag = tree.active_drag.as_ref().expect("active drag");
2023        assert!(
2024            (drag.current_position.x - 73.0).abs() < 0.01
2025                && (drag.current_position.y - 41.0).abs() < 0.01,
2026            "drag session position should track the pointer"
2027        );
2028
2029        let overlay_id = drag.preview_overlay_id.expect("preview overlay");
2030        let overlay = tree
2031            .overlay_manager()
2032            .overlay(overlay_id)
2033            .expect("overlay looked up by id");
2034        match &overlay.placement {
2035            crate::overlay::OverlayPlacement::AtPointer(p) => {
2036                assert!(
2037                    (p.x - 73.0).abs() < 0.01 && (p.y - 41.0).abs() < 0.01,
2038                    "preview overlay placement should follow pointer"
2039                );
2040            }
2041            other => panic!("expected AtPointer placement, got {:?}", other),
2042        }
2043    }
2044
2045    #[test]
2046    fn escape_during_hover_dismisses_preview() {
2047        let mut tree = WidgetTree::new();
2048        let source = tree.add(FillWidget::new());
2049        let _target = tree.add(
2050            FillWidget::new()
2051                .on_drag_hover(|_payload, _pos, _ctx| {
2052                    crate::drag_state::DropFeedback::InsertionLine {
2053                        y: 0.0,
2054                        width: 100.0,
2055                    }
2056                })
2057                .on_drop(|_, _, _| true),
2058        );
2059        tree.layout(SizeProposal::exact(200.0, 100.0));
2060
2061        let overlay_count_before = tree.overlay_manager().len();
2062
2063        let mut ctx = crate::widget::EventContext::new();
2064        ctx.start_drag_with_preview(
2065            source,
2066            crate::drag_payload::DragPayload::typed(0_u32),
2067            Box::new(FillWidget::new()),
2068        );
2069        tree.collect_from_ctx(ctx, source);
2070
2071        // Move over the target to establish feedback.
2072        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(150.0, 50.0)));
2073
2074        assert!(tree.active_drag.is_some());
2075        assert_eq!(tree.overlay_manager().len(), overlay_count_before + 1);
2076
2077        // Escape cancels: session cleared AND preview overlay dismissed.
2078        tree.press_key(Key::Escape, Modifiers::NONE);
2079
2080        assert!(tree.active_drag.is_none(), "drag must be cancelled");
2081        assert_eq!(
2082            tree.overlay_manager().len(),
2083            overlay_count_before,
2084            "preview overlay must be dismissed after Escape"
2085        );
2086    }
2087
2088    #[test]
2089    fn active_drag_blocks_on_tap_on_other_widgets() {
2090        use std::cell::Cell;
2091        use std::rc::Rc;
2092
2093        // While a drag is in progress, PointerMove and PointerUp must go
2094        // through the drag pipeline (handle_drag_move / handle_drag_drop) —
2095        // NOT be dispatched to the hovered widget. A widget with `on_tap` in
2096        // the drop location should not receive it.
2097        let tap_fired = Rc::new(Cell::new(false));
2098        let tf = tap_fired.clone();
2099
2100        let mut tree = WidgetTree::new();
2101        let source = tree.add(FillWidget::new());
2102        let _other = tree.add(FillWidget::new().on_tap(move |_pos, _ctx| {
2103            tf.set(true);
2104        }));
2105        tree.layout(SizeProposal::exact(200.0, 100.0));
2106
2107        let mut ctx = crate::widget::EventContext::new();
2108        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(0_u32));
2109        tree.collect_from_ctx(ctx, source);
2110
2111        // Move over and release on the `on_tap` widget. Normally this would
2112        // synthesize a Tap gesture — but an active drag short-circuits.
2113        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(150.0, 50.0)));
2114        tree.dispatch_event(WidgetEvent::pointer_up(
2115            Point::new(150.0, 50.0),
2116            PointerButton::Primary,
2117            Modifiers::NONE,
2118        ));
2119
2120        assert!(
2121            !tap_fired.get(),
2122            "on_tap must not fire during an active drag"
2123        );
2124    }
2125
2126    // --- on_drag_leave lifecycle ---------------------------------------
2127
2128    #[test]
2129    fn on_drag_leave_fires_when_pointer_leaves_target_bounds() {
2130        // Single drop target wrapped in an InsetWidget so its bounds do
2131        // NOT fill the viewport — the pointer can be "inside the scene
2132        // but outside the target" so a target-change (target → None) is
2133        // reachable without destroying widgets. That is the main
2134        // semantic we want `on_drag_leave` to cover.
2135        use crate::test_widgets::InsetWidget;
2136        use std::cell::Cell;
2137        use std::rc::Rc;
2138
2139        let leave = Rc::new(Cell::new(0_u32));
2140        let l = leave.clone();
2141
2142        let mut tree = WidgetTree::new();
2143        let source = tree.add(FillWidget::new());
2144        let target = tree.add(
2145            FillWidget::new()
2146                .on_drag_hover(
2147                    |_p, _pos, _ctx| crate::drag_state::DropFeedback::InsertionLine {
2148                        y: 0.0,
2149                        width: 10.0,
2150                    },
2151                )
2152                .on_drag_leave(move |_ctx| l.set(l.get() + 1))
2153                .on_drop(|_, _, _| true),
2154        );
2155        let _wrapper = tree.add(InsetWidget::new(40.0).set_child(target));
2156        tree.layout(SizeProposal::exact(200.0, 100.0));
2157
2158        let mut ctx = crate::widget::EventContext::new();
2159        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(0_u32));
2160        tree.collect_from_ctx(ctx, source);
2161
2162        // Pointer inside the inset (where the target lives).
2163        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(100.0, 50.0)));
2164        assert_eq!(leave.get(), 0, "no leave yet — target just became active");
2165
2166        // Pointer in the inset area, outside the target's bounds — the
2167        // only hit is the InsetWidget which has no drag handlers, so
2168        // drop_target becomes None. Target changed → leave fires on the
2169        // old target.
2170        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(10.0, 10.0)));
2171        assert_eq!(
2172            leave.get(),
2173            1,
2174            "on_drag_leave fires when pointer exits the target's bounds"
2175        );
2176
2177        // Moving back in shouldn't fire again.
2178        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(100.0, 50.0)));
2179        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(100.0, 50.0)));
2180        assert_eq!(
2181            leave.get(),
2182            1,
2183            "leave fires at most once per leave transition"
2184        );
2185
2186        // Leaving again fires a second time.
2187        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(10.0, 10.0)));
2188        assert_eq!(leave.get(), 2);
2189    }
2190
2191    #[test]
2192    fn on_drag_leave_fires_on_drop() {
2193        use std::cell::Cell;
2194        use std::rc::Rc;
2195
2196        let leave = Rc::new(Cell::new(0_u32));
2197        let l = leave.clone();
2198
2199        let mut tree = WidgetTree::new();
2200        let source = tree.add(FillWidget::new());
2201        let _target = tree.add(
2202            FillWidget::new()
2203                .on_drag_hover(
2204                    |_p, _pos, _ctx| crate::drag_state::DropFeedback::InsertionLine {
2205                        y: 0.0,
2206                        width: 10.0,
2207                    },
2208                )
2209                .on_drag_leave(move |_ctx| l.set(l.get() + 1))
2210                .on_drop(|_, _, _| true),
2211        );
2212        tree.layout(SizeProposal::exact(200.0, 100.0));
2213
2214        let mut ctx = crate::widget::EventContext::new();
2215        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(0_u32));
2216        tree.collect_from_ctx(ctx, source);
2217        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(100.0, 50.0)));
2218        tree.dispatch_event(WidgetEvent::pointer_up(
2219            Point::new(100.0, 50.0),
2220            PointerButton::Primary,
2221            Modifiers::NONE,
2222        ));
2223
2224        assert_eq!(leave.get(), 1, "on_drag_leave fires exactly once on drop");
2225    }
2226
2227    #[test]
2228    fn on_drag_leave_fires_on_escape_cancel() {
2229        use std::cell::Cell;
2230        use std::rc::Rc;
2231
2232        let leave = Rc::new(Cell::new(0_u32));
2233        let l = leave.clone();
2234
2235        let mut tree = WidgetTree::new();
2236        let source = tree.add(FillWidget::new());
2237        let _target = tree.add(
2238            FillWidget::new()
2239                .on_drag_hover(
2240                    |_p, _pos, _ctx| crate::drag_state::DropFeedback::InsertionLine {
2241                        y: 0.0,
2242                        width: 10.0,
2243                    },
2244                )
2245                .on_drag_leave(move |_ctx| l.set(l.get() + 1))
2246                .on_drop(|_, _, _| true),
2247        );
2248        tree.layout(SizeProposal::exact(200.0, 100.0));
2249
2250        let mut ctx = crate::widget::EventContext::new();
2251        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(0_u32));
2252        tree.collect_from_ctx(ctx, source);
2253        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(100.0, 50.0)));
2254        tree.press_key(Key::Escape, Modifiers::NONE);
2255
2256        assert_eq!(
2257            leave.get(),
2258            1,
2259            "Escape cancel must fire on_drag_leave on the current target"
2260        );
2261    }
2262
2263    #[test]
2264    fn on_drag_leave_fires_when_source_destroyed_mid_drag() {
2265        use std::cell::Cell;
2266        use std::rc::Rc;
2267
2268        let leave = Rc::new(Cell::new(0_u32));
2269        let l = leave.clone();
2270
2271        let mut tree = WidgetTree::new();
2272        let source = tree.add(FillWidget::new());
2273        let _target = tree.add(
2274            FillWidget::new()
2275                .on_drag_hover(
2276                    |_p, _pos, _ctx| crate::drag_state::DropFeedback::InsertionLine {
2277                        y: 0.0,
2278                        width: 10.0,
2279                    },
2280                )
2281                .on_drag_leave(move |_ctx| l.set(l.get() + 1))
2282                .on_drop(|_, _, _| true),
2283        );
2284        tree.layout(SizeProposal::exact(200.0, 100.0));
2285
2286        let mut ctx = crate::widget::EventContext::new();
2287        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(0_u32));
2288        tree.collect_from_ctx(ctx, source);
2289        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(100.0, 50.0)));
2290
2291        tree.arena.destroy(source);
2292        // revalidate_interaction_state runs on the next process_pending_rebuilds
2293        // — drive it by a no-op layout call.
2294        tree.layout(SizeProposal::exact(200.0, 100.0));
2295
2296        assert!(
2297            tree.active_drag.is_none(),
2298            "active drag should have been cancelled"
2299        );
2300        assert_eq!(
2301            leave.get(),
2302            1,
2303            "on_drag_leave fires on the drop target when the source is torn down"
2304        );
2305    }
2306
2307    #[test]
2308    fn on_drag_tick_fires_per_layout_pass() {
2309        use std::cell::Cell;
2310        use std::rc::Rc;
2311
2312        let ticks = Rc::new(Cell::new(0_u32));
2313        let t = ticks.clone();
2314
2315        let mut tree = WidgetTree::new();
2316        let source = tree.add(FillWidget::new());
2317        let _target = tree.add(
2318            FillWidget::new()
2319                .on_drag_hover(
2320                    |_p, _pos, _ctx| crate::drag_state::DropFeedback::InsertionLine {
2321                        y: 0.0,
2322                        width: 10.0,
2323                    },
2324                )
2325                .on_drag_tick(move |_pos, _ctx| t.set(t.get() + 1))
2326                .on_drop(|_, _, _| true),
2327        );
2328        tree.layout(SizeProposal::exact(200.0, 100.0));
2329
2330        let mut ctx = crate::widget::EventContext::new();
2331        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(0_u32));
2332        tree.collect_from_ctx(ctx, source);
2333        // Move over the target so it becomes the current drop target.
2334        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(100.0, 50.0)));
2335        assert_eq!(ticks.get(), 0, "tick shouldn't have fired yet");
2336
2337        tree.layout(SizeProposal::exact(200.0, 100.0));
2338        assert_eq!(ticks.get(), 1);
2339        tree.layout(SizeProposal::exact(200.0, 100.0));
2340        tree.layout(SizeProposal::exact(200.0, 100.0));
2341        assert_eq!(ticks.get(), 3);
2342
2343        // End the drag; ticks stop.
2344        tree.dispatch_event(WidgetEvent::pointer_up(
2345            Point::new(100.0, 50.0),
2346            PointerButton::Primary,
2347            Modifiers::NONE,
2348        ));
2349        let after_drop = ticks.get();
2350        tree.layout(SizeProposal::exact(200.0, 100.0));
2351        tree.layout(SizeProposal::exact(200.0, 100.0));
2352        assert_eq!(
2353            ticks.get(),
2354            after_drop,
2355            "on_drag_tick must not fire after drag ends"
2356        );
2357    }
2358
2359    #[test]
2360    fn on_drag_hover_and_on_drop_receive_widget_local_coordinates() {
2361        // Regression for "drop indicator is always 2 items below the
2362        // cursor": `on_drag_hover` and `on_drop` must receive the
2363        // pointer in the target's local coordinates, not tree coords.
2364        // Otherwise a widget placed below a header computes insertion
2365        // indices against an absolute Y and the line renders offset by
2366        // the header's height divided by row height.
2367        use crate::test_widgets::InsetWidget;
2368        use std::cell::Cell;
2369        use std::rc::Rc;
2370
2371        let hover_local = Rc::new(Cell::new(Point::new(-1.0, -1.0)));
2372        let drop_local = Rc::new(Cell::new(Point::new(-1.0, -1.0)));
2373        let h = hover_local.clone();
2374        let d = drop_local.clone();
2375
2376        let mut tree = WidgetTree::new();
2377        let source = tree.add(FillWidget::new());
2378        // Inset 40 pushes the drop target to (40, 40) in tree coords.
2379        let target = tree.add(
2380            FillWidget::new()
2381                .on_drag_hover(move |_p, pos, _ctx| {
2382                    h.set(pos);
2383                    crate::drag_state::DropFeedback::InsertionLine {
2384                        y: 0.0,
2385                        width: 10.0,
2386                    }
2387                })
2388                .on_drop(move |_payload, pos, _ctx| {
2389                    d.set(pos);
2390                    true
2391                }),
2392        );
2393        let _wrapper = tree.add(InsetWidget::new(40.0).set_child(target));
2394        tree.layout(SizeProposal::exact(200.0, 100.0));
2395
2396        let mut ctx = crate::widget::EventContext::new();
2397        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(0_u32));
2398        tree.collect_from_ctx(ctx, source);
2399
2400        // Move pointer to (100, 60) in tree coords — inside the inset
2401        // target whose origin is (40, 40). Local position should be
2402        // (60, 20).
2403        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(100.0, 60.0)));
2404        let hov = hover_local.get();
2405        assert!(
2406            (hov.x - 60.0).abs() < 0.01 && (hov.y - 20.0).abs() < 0.01,
2407            "on_drag_hover should receive local coords, got {:?}",
2408            hov,
2409        );
2410
2411        // Drop at (110, 55) tree coords → local (70, 15).
2412        tree.dispatch_event(WidgetEvent::pointer_up(
2413            Point::new(110.0, 55.0),
2414            PointerButton::Primary,
2415            Modifiers::NONE,
2416        ));
2417        let drp = drop_local.get();
2418        assert!(
2419            (drp.x - 70.0).abs() < 0.01 && (drp.y - 15.0).abs() < 0.01,
2420            "on_drop should receive local coords, got {:?}",
2421            drp,
2422        );
2423    }
2424
2425    #[test]
2426    fn active_drag_sets_grabbing_cursor() {
2427        // Starting a drag with a preview must switch the tree's cursor
2428        // to `Grabbing`; dropping or cancelling must reset to `Default`.
2429        // teksilo-app applies the tree's cursor to the winit window after
2430        // each pointer event, so this is what the user actually sees.
2431        let mut tree = WidgetTree::new();
2432        let source = tree.add(FillWidget::new());
2433        tree.layout(SizeProposal::exact(100.0, 50.0));
2434
2435        assert_eq!(tree.current_cursor(), CursorIcon::Default);
2436
2437        let mut ctx = crate::widget::EventContext::new();
2438        ctx.start_drag_with_preview(
2439            source,
2440            crate::drag_payload::DragPayload::typed(0_u32),
2441            Box::new(FillWidget::new()),
2442        );
2443        tree.collect_from_ctx(ctx, source);
2444        assert_eq!(tree.current_cursor(), CursorIcon::Grabbing);
2445
2446        // Drop somewhere.
2447        tree.dispatch_event(WidgetEvent::pointer_up(
2448            Point::new(50.0, 25.0),
2449            PointerButton::Primary,
2450            Modifiers::NONE,
2451        ));
2452        assert_eq!(tree.current_cursor(), CursorIcon::Default);
2453    }
2454
2455    #[test]
2456    fn escape_cancel_resets_cursor() {
2457        let mut tree = WidgetTree::new();
2458        let source = tree.add(FillWidget::new());
2459        tree.layout(SizeProposal::exact(100.0, 50.0));
2460
2461        let mut ctx = crate::widget::EventContext::new();
2462        ctx.start_drag_with_preview(
2463            source,
2464            crate::drag_payload::DragPayload::typed(0_u32),
2465            Box::new(FillWidget::new()),
2466        );
2467        tree.collect_from_ctx(ctx, source);
2468        assert_eq!(tree.current_cursor(), CursorIcon::Grabbing);
2469
2470        tree.press_key(Key::Escape, Modifiers::NONE);
2471        assert_eq!(tree.current_cursor(), CursorIcon::Default);
2472    }
2473
2474    #[test]
2475    fn drag_preview_composite_gets_built() {
2476        // Regression — composite preview widgets must have their `build()`
2477        // called after `start_drag_with_preview`. A plain `arena.insert`
2478        // inserts the node but never runs build, leaving the preview tree
2479        // empty (no children, zero area of useful content) and the overlay
2480        // invisible. The fix routes through `add_boxed` so build fires.
2481        use std::cell::Cell;
2482        use std::rc::Rc;
2483
2484        let built = Rc::new(Cell::new(false));
2485        let b = built.clone();
2486
2487        #[derive(Debug)]
2488        struct CheckingWidget {
2489            built: Rc<Cell<bool>>,
2490        }
2491        impl Widget for CheckingWidget {
2492            fn build(&mut self, _ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
2493                self.built.set(true);
2494                Vec::new()
2495            }
2496            fn layout_response(
2497                &self,
2498                _: SizeProposal,
2499                _: &crate::widget::LayoutContext,
2500            ) -> crate::widget::LayoutResponse {
2501                teksilo_canvas::Size::new(50.0, 20.0).into()
2502            }
2503        }
2504
2505        let mut tree = WidgetTree::new();
2506        let source = tree.add(FillWidget::new());
2507        tree.layout(SizeProposal::exact(200.0, 100.0));
2508
2509        let mut ctx = crate::widget::EventContext::new();
2510        ctx.start_drag_with_preview(
2511            source,
2512            crate::drag_payload::DragPayload::typed(0_u32),
2513            Box::new(CheckingWidget { built: b }),
2514        );
2515        tree.collect_from_ctx(ctx, source);
2516
2517        assert!(built.get(), "preview's build() must fire on drag start");
2518    }
2519
2520    #[test]
2521    fn preview_placement_drives_layout_needs() {
2522        // Regression for "preview stays at (0, 0)": each pointer move
2523        // during drag updates the overlay placement via
2524        // `update_placement`, but the overlay's bounds are only
2525        // recomputed by `position_overlays` inside `layout()` — which
2526        // early-returns when nothing is `needs_layout`. Verify the
2527        // drag path marks the preview content dirty so layout actually
2528        // runs.
2529        let mut tree = WidgetTree::new();
2530        let source = tree.add(FillWidget::new());
2531        tree.layout(SizeProposal::exact(200.0, 200.0));
2532
2533        let mut ctx = crate::widget::EventContext::new();
2534        ctx.start_drag_with_preview(
2535            source,
2536            crate::drag_payload::DragPayload::typed(0_u32),
2537            Box::new(FillWidget::new()),
2538        );
2539        tree.collect_from_ctx(ctx, source);
2540
2541        // Right after drag start, the preview content should need layout
2542        // so the first layout pass positions it.
2543        assert!(
2544            tree.needs_layout(),
2545            "drag start must mark preview content for layout"
2546        );
2547        tree.layout(SizeProposal::exact(200.0, 200.0));
2548        assert!(
2549            !tree.needs_layout(),
2550            "layout should have cleared dirty flag"
2551        );
2552
2553        // A subsequent PointerMove must remark the preview so its
2554        // overlay bounds get repositioned on the next layout pass.
2555        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(75.0, 120.0)));
2556        assert!(
2557            tree.needs_layout(),
2558            "PointerMove during drag must mark preview for layout"
2559        );
2560    }
2561
2562    #[test]
2563    fn scroll_during_drag_routes_to_drop_target() {
2564        use std::cell::Cell;
2565        use std::rc::Rc;
2566
2567        let scroll_count = Rc::new(Cell::new(0_u32));
2568        let sc = scroll_count.clone();
2569
2570        let mut tree = WidgetTree::new();
2571        let source = tree.add(FillWidget::new());
2572        let _target = tree.add(
2573            FillWidget::new()
2574                .on_drag_hover(
2575                    |_p, _pos, _ctx| crate::drag_state::DropFeedback::InsertionLine {
2576                        y: 0.0,
2577                        width: 10.0,
2578                    },
2579                )
2580                .on_scroll(move |event, _ctx| match event {
2581                    WidgetEvent::Scroll { .. } => {
2582                        sc.set(sc.get() + 1);
2583                        EventResponse::Handled
2584                    }
2585                    _ => EventResponse::Ignored,
2586                })
2587                .on_drop(|_, _, _| true),
2588        );
2589        tree.layout(SizeProposal::exact(200.0, 100.0));
2590
2591        let mut ctx = crate::widget::EventContext::new();
2592        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(0_u32));
2593        tree.collect_from_ctx(ctx, source);
2594        // Make target the current drop target.
2595        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(100.0, 50.0)));
2596
2597        // A wheel event during drag should reach the drop target (not the
2598        // stale hover from before the drag started).
2599        tree.dispatch_event(WidgetEvent::scroll(
2600            crate::event::ScrollDelta::Pixels { x: 0.0, y: 40.0 },
2601            Default::default(),
2602        ));
2603        assert_eq!(
2604            scroll_count.get(),
2605            1,
2606            "Scroll during drag must route to the current drop target"
2607        );
2608    }
2609
2610    // --- External (OS) drag-and-drop -----------------------------------
2611
2612    /// A drag over a target with an `on_drag_tick` handler asks for the frame
2613    /// tick, so the tick runs on a deadline whether or not anything else lays
2614    /// the window out: on entering, on a move, and after each tick. A target
2615    /// without the handler asks for nothing, and the request lapses after the
2616    /// drag.
2617    #[test]
2618    fn a_drag_over_a_ticking_target_asks_for_the_frame_tick() {
2619        use crate::drag_payload::ExternalDropData;
2620        use teksilo_canvas::Point;
2621
2622        let proposal = SizeProposal::exact(200.0, 100.0);
2623        let at = Point::new(100.0, 50.0);
2624        let mut noop = crate::window::NoopWindowOps;
2625        let target = |ticks: bool| {
2626            let mut tree = WidgetTree::new();
2627            let accept = FillWidget::new()
2628                .on_drag_hover(|_payload, _at, _ctx| crate::drag_state::DropFeedback::Accept);
2629            if ticks {
2630                tree.add(accept.on_drag_tick(|_at, _ctx| {}));
2631            } else {
2632                tree.add(accept);
2633            }
2634            tree.layout(proposal);
2635            tree
2636        };
2637
2638        let mut plain = target(false);
2639        plain.begin_external_drag(at, ExternalDropData::default(), &mut noop);
2640        assert!(
2641            plain.frame_tick_deadline().is_none(),
2642            "a target with no tick handler asks for no frame"
2643        );
2644
2645        let mut ticking = target(true);
2646        ticking.begin_external_drag(at, ExternalDropData::default(), &mut noop);
2647        assert!(ticking.frame_tick_deadline().is_some(), "entering asks");
2648        ticking.layout(proposal);
2649        assert!(
2650            ticking.frame_tick_deadline().is_some(),
2651            "the tick asks again, with the pointer held still"
2652        );
2653        ticking.update_external_drag(Point::new(101.0, 50.0), &mut noop);
2654        ticking.layout(proposal);
2655        assert!(ticking.frame_tick_deadline().is_some(), "and after a move");
2656
2657        ticking.cancel_external_drag(&mut noop);
2658        ticking.layout(proposal);
2659        assert!(
2660            ticking.frame_tick_deadline().is_none(),
2661            "and lapses after the drag"
2662        );
2663    }
2664
2665    #[test]
2666    fn external_drop_delivers_files_and_marks_external() {
2667        use crate::drag_payload::ExternalDropData;
2668        use std::cell::RefCell;
2669        use std::path::PathBuf;
2670        use std::rc::Rc;
2671
2672        let dropped_files: Rc<RefCell<Vec<PathBuf>>> = Rc::new(RefCell::new(Vec::new()));
2673        let was_external = Rc::new(std::cell::Cell::new(false));
2674        let df = dropped_files.clone();
2675        let we = was_external.clone();
2676
2677        let mut tree = WidgetTree::new();
2678        let _target = tree.add(
2679            FillWidget::new()
2680                .on_drag_hover(|payload, _pos, _ctx| {
2681                    // External file drags are accepted with a highlight.
2682                    if payload.is_external() && !payload.files().is_empty() {
2683                        crate::drag_state::DropFeedback::HighlightRect {
2684                            rect: teksilo_canvas::Rect::new(0.0, 0.0, 10.0, 10.0),
2685                            color: teksilo_tokens::Color::WHITE,
2686                        }
2687                    } else {
2688                        crate::drag_state::DropFeedback::NoFeedback
2689                    }
2690                })
2691                .on_drop(move |payload, _pos, _ctx| {
2692                    we.set(payload.is_external());
2693                    *df.borrow_mut() = payload.files().to_vec();
2694                    true
2695                }),
2696        );
2697        tree.layout(SizeProposal::exact(200.0, 100.0));
2698
2699        let mut noop = crate::window::NoopWindowOps;
2700        let data = ExternalDropData {
2701            files: vec![PathBuf::from("/tmp/a.png"), PathBuf::from("/tmp/b.png")],
2702            ..Default::default()
2703        };
2704        tree.begin_external_drag(Point::new(100.0, 50.0), data, &mut noop);
2705        assert!(tree.active_drag.is_some());
2706        assert!(tree.active_drag.as_ref().unwrap().is_external);
2707
2708        tree.update_external_drag(Point::new(110.0, 55.0), &mut noop);
2709        // Pass the same files again at drop — exercises the payload-refresh path.
2710        let drop_data = ExternalDropData {
2711            files: vec![PathBuf::from("/tmp/a.png"), PathBuf::from("/tmp/b.png")],
2712            ..Default::default()
2713        };
2714        tree.end_external_drag(Point::new(110.0, 55.0), drop_data, &mut noop);
2715
2716        assert!(
2717            tree.active_drag.is_none(),
2718            "external drag must clear on drop"
2719        );
2720        assert!(was_external.get(), "payload should report external origin");
2721        assert_eq!(
2722            *dropped_files.borrow(),
2723            vec![PathBuf::from("/tmp/a.png"), PathBuf::from("/tmp/b.png")],
2724        );
2725    }
2726
2727    #[test]
2728    fn external_drop_passes_local_coordinates() {
2729        use crate::drag_payload::ExternalDropData;
2730        use crate::test_widgets::InsetWidget;
2731        use std::cell::Cell;
2732        use std::path::PathBuf;
2733        use std::rc::Rc;
2734
2735        let drop_local = Rc::new(Cell::new(Point::new(-1.0, -1.0)));
2736        let d = drop_local.clone();
2737
2738        let mut tree = WidgetTree::new();
2739        // Inset 40 → target origin at (40, 40).
2740        let target = tree.add(
2741            FillWidget::new()
2742                .on_drag_hover(
2743                    |_p, _pos, _ctx| crate::drag_state::DropFeedback::HighlightRect {
2744                        rect: teksilo_canvas::Rect::new(0.0, 0.0, 10.0, 10.0),
2745                        color: teksilo_tokens::Color::WHITE,
2746                    },
2747                )
2748                .on_drop(move |_payload, pos, _ctx| {
2749                    d.set(pos);
2750                    true
2751                }),
2752        );
2753        let _wrapper = tree.add(InsetWidget::new(40.0).set_child(target));
2754        tree.layout(SizeProposal::exact(200.0, 100.0));
2755
2756        let mut noop = crate::window::NoopWindowOps;
2757        let data = ExternalDropData {
2758            files: vec![PathBuf::from("/tmp/x")],
2759            ..Default::default()
2760        };
2761        // Drop at tree (110, 55) → target-local (70, 15).
2762        tree.begin_external_drag(Point::new(110.0, 55.0), data, &mut noop);
2763        tree.end_external_drag(
2764            Point::new(110.0, 55.0),
2765            ExternalDropData::default(),
2766            &mut noop,
2767        );
2768
2769        let drp = drop_local.get();
2770        assert!(
2771            (drp.x - 70.0).abs() < 0.01 && (drp.y - 15.0).abs() < 0.01,
2772            "external on_drop should receive local coords, got {:?}",
2773            drp,
2774        );
2775    }
2776
2777    #[test]
2778    fn cancel_external_drag_clears_session_and_fires_leave() {
2779        use crate::drag_payload::ExternalDropData;
2780        use std::cell::Cell;
2781        use std::path::PathBuf;
2782        use std::rc::Rc;
2783
2784        let left = Rc::new(Cell::new(0_u32));
2785        let l = left.clone();
2786
2787        let mut tree = WidgetTree::new();
2788        let _target = tree.add(
2789            FillWidget::new()
2790                .on_drag_hover(
2791                    |_p, _pos, _ctx| crate::drag_state::DropFeedback::HighlightRect {
2792                        rect: teksilo_canvas::Rect::new(0.0, 0.0, 10.0, 10.0),
2793                        color: teksilo_tokens::Color::WHITE,
2794                    },
2795                )
2796                .on_drag_leave(move |_ctx| l.set(l.get() + 1))
2797                .on_drop(|_, _, _| true),
2798        );
2799        tree.layout(SizeProposal::exact(200.0, 100.0));
2800
2801        let mut noop = crate::window::NoopWindowOps;
2802        let data = ExternalDropData {
2803            files: vec![PathBuf::from("/tmp/x")],
2804            ..Default::default()
2805        };
2806        tree.begin_external_drag(Point::new(100.0, 50.0), data, &mut noop);
2807        assert!(tree.active_drag.is_some());
2808
2809        tree.cancel_external_drag(&mut noop);
2810        assert!(tree.active_drag.is_none(), "cancel must clear the session");
2811        assert_eq!(
2812            left.get(),
2813            1,
2814            "cancel must fire on_drag_leave on the target"
2815        );
2816    }
2817
2818    #[test]
2819    fn external_drag_helpers_noop_without_session() {
2820        // update/end/cancel are no-ops when no external session is active.
2821        let mut tree = WidgetTree::new();
2822        let _t = tree.add(FillWidget::new());
2823        tree.layout(SizeProposal::exact(100.0, 50.0));
2824
2825        let mut noop = crate::window::NoopWindowOps;
2826        tree.update_external_drag(Point::new(10.0, 10.0), &mut noop);
2827        tree.end_external_drag(
2828            Point::new(10.0, 10.0),
2829            crate::drag_payload::ExternalDropData::default(),
2830            &mut noop,
2831        );
2832        tree.cancel_external_drag(&mut noop);
2833        assert!(tree.active_drag.is_none());
2834    }
2835
2836    // --- Outbound (app → OS) escalation + unified on_drag_ended ----------
2837
2838    /// `WindowOps` sink that records `begin_os_drag` calls and reports a
2839    /// configurable success, standing in for the platform backend.
2840    struct RecordingWindowOps {
2841        started: std::rc::Rc<std::cell::RefCell<Vec<crate::drag_payload::OutboundDragData>>>,
2842        /// The pointer kind each `begin_os_drag` was told about, in order.
2843        started_kinds: std::rc::Rc<std::cell::RefCell<Vec<teksilo_tokens::PointerKind>>>,
2844        /// What every `begin_os_drag` answers. A `Pending` answer carries a
2845        /// fresh id each time, recorded in `pending_ids`.
2846        start: crate::drag_payload::OsDragStart,
2847        pending_ids: std::rc::Rc<std::cell::RefCell<Vec<crate::drag_payload::OsDragId>>>,
2848        cancels: std::rc::Rc<std::cell::Cell<usize>>,
2849        /// Every `set_drop_accepted` the tree pushed, in order.
2850        accepts: std::rc::Rc<std::cell::RefCell<Vec<bool>>>,
2851    }
2852
2853    impl RecordingWindowOps {
2854        fn new(succeed: bool) -> Self {
2855            Self::answering(if succeed {
2856                crate::drag_payload::OsDragStart::Started
2857            } else {
2858                crate::drag_payload::OsDragStart::Declined
2859            })
2860        }
2861
2862        fn answering(start: crate::drag_payload::OsDragStart) -> Self {
2863            Self {
2864                started: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
2865                started_kinds: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
2866                start,
2867                pending_ids: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
2868                cancels: std::rc::Rc::new(std::cell::Cell::new(0)),
2869                accepts: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
2870            }
2871        }
2872    }
2873    impl crate::window::WindowOps for RecordingWindowOps {
2874        fn open_window(
2875            &mut self,
2876            _c: crate::window::WindowConfig,
2877        ) -> crate::window::TeksiloWindowId {
2878            panic!("not used in these tests")
2879        }
2880        fn find_window(&self, _s: &str) -> Option<crate::window::TeksiloWindowId> {
2881            None
2882        }
2883        fn window_state(
2884            &self,
2885            _id: crate::window::TeksiloWindowId,
2886        ) -> Option<crate::window::WindowState> {
2887            None
2888        }
2889        fn windows(&self) -> Vec<crate::window::WindowState> {
2890            Vec::new()
2891        }
2892        fn focus_window(&mut self, _id: crate::window::TeksiloWindowId) {}
2893        fn close_window_by_id(&mut self, _id: crate::window::TeksiloWindowId) {}
2894        fn begin_os_drag(
2895            &mut self,
2896            data: crate::drag_payload::OutboundDragData,
2897            _image: Option<crate::drag_payload::DragImageData>,
2898            pointer: teksilo_tokens::PointerKind,
2899        ) -> crate::drag_payload::OsDragStart {
2900            self.started.borrow_mut().push(data);
2901            self.started_kinds.borrow_mut().push(pointer);
2902            match self.start {
2903                crate::drag_payload::OsDragStart::Pending(_) => {
2904                    let id = crate::drag_payload::OsDragId::next();
2905                    self.pending_ids.borrow_mut().push(id);
2906                    crate::drag_payload::OsDragStart::Pending(id)
2907                }
2908                other => other,
2909            }
2910        }
2911        fn cancel_os_drag(&mut self) {
2912            self.cancels.set(self.cancels.get() + 1);
2913        }
2914        fn set_drop_accepted(&mut self, accepted: bool) {
2915            self.accepts.borrow_mut().push(accepted);
2916        }
2917    }
2918
2919    fn exportable_payload() -> crate::drag_payload::DragPayload {
2920        crate::drag_payload::DragPayload::typed(7_u32).with_mime("text/plain", b"hi".to_vec())
2921    }
2922
2923    #[test]
2924    fn internal_exportable_drag_escalates_when_leaving_window() {
2925        let started = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
2926        let mut ops = RecordingWindowOps {
2927            started: started.clone(),
2928            started_kinds: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
2929            start: crate::drag_payload::OsDragStart::Started,
2930            pending_ids: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
2931            cancels: std::rc::Rc::new(std::cell::Cell::new(0)),
2932            accepts: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
2933        };
2934
2935        let mut tree = WidgetTree::new();
2936        let source = tree.add(FillWidget::new());
2937        tree.layout(SizeProposal::exact(200.0, 100.0));
2938
2939        let mut ctx = crate::widget::EventContext::new();
2940        ctx.start_drag(source, exportable_payload());
2941        tree.collect_from_ctx(ctx, source);
2942        assert!(tree.active_drag.is_some());
2943
2944        // Inside the window: no escalation.
2945        tree.handle_drag_move(Point::new(100.0, 50.0), &mut ops);
2946        assert!(started.borrow().is_empty());
2947        assert!(tree.active_drag.is_some());
2948
2949        // Pointer leaves the window: escalate.
2950        tree.handle_drag_move(Point::new(-5.0, 50.0), &mut ops);
2951        assert_eq!(started.borrow().len(), 1, "begin_os_drag called once");
2952        assert!(
2953            started.borrow()[0].mime.contains_key("text/plain"),
2954            "outbound data carries the payload's mime"
2955        );
2956        assert!(tree.active_drag.is_none(), "in-app session torn down");
2957        assert_eq!(tree.outbound_drag_source, Some(source));
2958    }
2959
2960    #[test]
2961    fn os_drag_ended_fires_source_on_drag_ended() {
2962        use crate::drag_payload::DropOutcome;
2963        use std::cell::Cell;
2964        use std::rc::Rc;
2965
2966        let outcome = Rc::new(Cell::new(None));
2967        let o = outcome.clone();
2968
2969        let started = Rc::new(std::cell::RefCell::new(Vec::new()));
2970        let mut ops = RecordingWindowOps {
2971            started,
2972            started_kinds: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
2973            start: crate::drag_payload::OsDragStart::Started,
2974            pending_ids: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
2975            cancels: std::rc::Rc::new(std::cell::Cell::new(0)),
2976            accepts: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
2977        };
2978
2979        let mut tree = WidgetTree::new();
2980        let source =
2981            tree.add(FillWidget::new().on_drag_ended(move |outcome, _ctx| o.set(Some(outcome))));
2982        tree.layout(SizeProposal::exact(200.0, 100.0));
2983
2984        let mut ctx = crate::widget::EventContext::new();
2985        ctx.start_drag(source, exportable_payload());
2986        tree.collect_from_ctx(ctx, source);
2987        tree.handle_drag_move(Point::new(-5.0, 50.0), &mut ops); // escalate
2988        assert_eq!(tree.outbound_drag_source, Some(source));
2989
2990        tree.handle_os_drag_ended(DropOutcome::OsMove, &mut ops);
2991        assert_eq!(outcome.get(), Some(DropOutcome::OsMove));
2992        assert!(
2993            tree.outbound_drag_source.is_none(),
2994            "cleared after delivery"
2995        );
2996    }
2997
2998    #[test]
2999    fn escape_during_an_escalated_drag_asks_the_platform_to_cancel() {
3000        // The in-app session is gone once the platform accepts the hand-off,
3001        // so this cannot ride the `active_drag` Escape path. Routing it through
3002        // `WindowOps` (rather than special-casing it in a backend's own event
3003        // loop) is what makes it observable here at all.
3004        let mut ops = RecordingWindowOps::new(true);
3005        let cancels = ops.cancels.clone();
3006
3007        let mut tree = WidgetTree::new();
3008        let source = tree.add(FillWidget::new());
3009        tree.layout(SizeProposal::exact(200.0, 100.0));
3010
3011        let mut ctx = crate::widget::EventContext::new();
3012        ctx.start_drag(source, exportable_payload());
3013        tree.collect_from_ctx(ctx, source);
3014        tree.handle_drag_move(Point::new(-5.0, 50.0), &mut ops); // escalate
3015        assert_eq!(tree.outbound_drag_source, Some(source));
3016
3017        tree.dispatch_event_with_ops(
3018            crate::event::WidgetEvent::KeyDown {
3019                key: crate::event::Key::Escape,
3020                modifiers: crate::event::Modifiers::NONE,
3021                text: None,
3022            },
3023            &mut ops,
3024        );
3025        assert_eq!(cancels.get(), 1, "the platform must be asked to cancel");
3026        assert_eq!(
3027            tree.outbound_drag_source,
3028            Some(source),
3029            "the session stays until the backend reports its terminal outcome — \
3030             tearing it down here would drop the source's on_drag_ended"
3031        );
3032    }
3033
3034    #[test]
3035    fn escape_without_an_os_drag_does_not_touch_the_platform() {
3036        let mut ops = RecordingWindowOps::new(true);
3037        let cancels = ops.cancels.clone();
3038
3039        let mut tree = WidgetTree::new();
3040        tree.add(FillWidget::new());
3041        tree.layout(SizeProposal::exact(200.0, 100.0));
3042
3043        tree.dispatch_event_with_ops(
3044            crate::event::WidgetEvent::KeyDown {
3045                key: crate::event::Key::Escape,
3046                modifiers: crate::event::Modifiers::NONE,
3047                text: None,
3048            },
3049            &mut ops,
3050        );
3051        assert_eq!(cancels.get(), 0);
3052    }
3053
3054    #[test]
3055    fn no_backend_keeps_session_active_on_leave() {
3056        // begin_os_drag returns false (no outbound backend): the in-app
3057        // drag stays active so the user can drag back in — current behavior.
3058        let started = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
3059        let mut ops = RecordingWindowOps {
3060            started: started.clone(),
3061            started_kinds: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3062            start: crate::drag_payload::OsDragStart::Declined,
3063            pending_ids: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3064            cancels: std::rc::Rc::new(std::cell::Cell::new(0)),
3065            accepts: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3066        };
3067
3068        let mut tree = WidgetTree::new();
3069        let source = tree.add(FillWidget::new());
3070        tree.layout(SizeProposal::exact(200.0, 100.0));
3071
3072        let mut ctx = crate::widget::EventContext::new();
3073        ctx.start_drag(source, exportable_payload());
3074        tree.collect_from_ctx(ctx, source);
3075        tree.handle_drag_move(Point::new(-5.0, 50.0), &mut ops);
3076
3077        assert_eq!(started.borrow().len(), 1, "escalation was attempted");
3078        assert!(tree.active_drag.is_some(), "session kept (no backend)");
3079        assert!(tree.outbound_drag_source.is_none());
3080    }
3081
3082    #[test]
3083    fn non_exportable_drag_does_not_escalate() {
3084        let started = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
3085        let mut ops = RecordingWindowOps {
3086            started: started.clone(),
3087            started_kinds: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3088            start: crate::drag_payload::OsDragStart::Started,
3089            pending_ids: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3090            cancels: std::rc::Rc::new(std::cell::Cell::new(0)),
3091            accepts: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3092        };
3093
3094        let mut tree = WidgetTree::new();
3095        let source = tree.add(FillWidget::new());
3096        tree.layout(SizeProposal::exact(200.0, 100.0));
3097
3098        // Plain typed payload, no mime ⇒ not OS-exportable.
3099        let mut ctx = crate::widget::EventContext::new();
3100        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(1_u32));
3101        tree.collect_from_ctx(ctx, source);
3102        tree.handle_drag_move(Point::new(-5.0, 50.0), &mut ops);
3103
3104        assert!(started.borrow().is_empty(), "no escalation attempt");
3105        assert!(tree.active_drag.is_some(), "session unaffected");
3106    }
3107
3108    #[test]
3109    fn in_app_drop_fires_source_on_drag_ended_with_accepted() {
3110        use crate::drag_payload::DropOutcome;
3111        use std::cell::Cell;
3112        use std::rc::Rc;
3113
3114        let outcome = Rc::new(Cell::new(None));
3115        let o = outcome.clone();
3116
3117        let mut tree = WidgetTree::new();
3118        let source =
3119            tree.add(FillWidget::new().on_drag_ended(move |outcome, _ctx| o.set(Some(outcome))));
3120        let _target = tree.add(FillWidget::new().on_drop(|_, _, _| true));
3121        tree.layout(SizeProposal::exact(200.0, 100.0));
3122
3123        let mut ctx = crate::widget::EventContext::new();
3124        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(42_u32));
3125        tree.collect_from_ctx(ctx, source);
3126
3127        tree.dispatch_event(WidgetEvent::pointer_up(
3128            Point::new(150.0, 50.0),
3129            PointerButton::Primary,
3130            Modifiers::NONE,
3131        ));
3132
3133        assert_eq!(outcome.get(), Some(DropOutcome::InApp { accepted: true }));
3134    }
3135
3136    #[test]
3137    fn escape_fires_source_on_drag_ended_cancelled() {
3138        use crate::drag_payload::DropOutcome;
3139        use std::cell::Cell;
3140        use std::rc::Rc;
3141
3142        let outcome = Rc::new(Cell::new(None));
3143        let o = outcome.clone();
3144
3145        let mut tree = WidgetTree::new();
3146        let source =
3147            tree.add(FillWidget::new().on_drag_ended(move |outcome, _ctx| o.set(Some(outcome))));
3148        tree.layout(SizeProposal::exact(200.0, 100.0));
3149
3150        let mut ctx = crate::widget::EventContext::new();
3151        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(0_u32));
3152        tree.collect_from_ctx(ctx, source);
3153
3154        tree.press_key(Key::Escape, Modifiers::NONE);
3155        assert_eq!(outcome.get(), Some(DropOutcome::Cancelled));
3156    }
3157
3158    /// Drag out (escalate to OS), then the OS drag re-enters the same window
3159    /// and drops on an in-app target: the original *typed* payload is
3160    /// recovered (not lost to the file/text round-trip), and the source's
3161    /// `on_drag_ended` fires exactly once, with the in-app outcome.
3162    #[test]
3163    fn os_drag_reentry_recovers_typed_payload_for_in_app_drop() {
3164        use crate::drag_payload::{DragPayload, DropOutcome};
3165        use std::cell::Cell;
3166        use std::rc::Rc;
3167
3168        let started = Rc::new(std::cell::RefCell::new(Vec::new()));
3169        let mut ops = RecordingWindowOps {
3170            started,
3171            started_kinds: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3172            start: crate::drag_payload::OsDragStart::Started,
3173            pending_ids: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3174            cancels: std::rc::Rc::new(std::cell::Cell::new(0)),
3175            accepts: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3176        };
3177
3178        let got_typed = Rc::new(Cell::new(0_u32));
3179        let ended = Rc::new(Cell::new(0_u32));
3180        let last_outcome = Rc::new(Cell::new(None));
3181        let g = got_typed.clone();
3182        let e = ended.clone();
3183        let lo = last_outcome.clone();
3184
3185        let mut tree = WidgetTree::new();
3186        let source = tree.add(FillWidget::new().on_drag_ended(move |outcome, _ctx| {
3187            e.set(e.get() + 1);
3188            lo.set(Some(outcome));
3189        }));
3190        let _target =
3191            tree.add(
3192                FillWidget::new().on_drop(move |mut p, _, _| match p.take_typed::<u32>() {
3193                    Some(v) => {
3194                        g.set(v);
3195                        true
3196                    }
3197                    None => false,
3198                }),
3199            );
3200        tree.layout(SizeProposal::exact(200.0, 100.0));
3201
3202        // Internal drag with a typed value AND an exportable MIME rep.
3203        let mut ctx = crate::widget::EventContext::new();
3204        ctx.start_drag(
3205            source,
3206            DragPayload::typed(123_u32).with_mime("text/plain", b"x".to_vec()),
3207        );
3208        tree.collect_from_ctx(ctx, source);
3209
3210        // Leave the window → escalate to OS drag (typed payload stashed).
3211        tree.handle_drag_move(Point::new(-5.0, 50.0), &mut ops);
3212        assert!(tree.active_drag.is_none());
3213        assert!(
3214            super::has_outbound_typed(),
3215            "typed payload stashed globally"
3216        );
3217
3218        // OS drag re-enters → restored as an internal session with the typed
3219        // value (not an external file/text drop).
3220        tree.begin_external_drag(
3221            Point::new(100.0, 50.0),
3222            crate::drag_payload::ExternalDropData::default(),
3223            &mut ops,
3224        );
3225        let d = tree.active_drag.as_ref().expect("re-entered session");
3226        assert!(!d.is_external, "re-entry is an internal session");
3227        assert!(d.payload.has_typed::<u32>(), "typed payload recovered");
3228        assert_eq!(
3229            d.payload.text(),
3230            Some("x"),
3231            "external view enriched from MIME so DropZone-style targets also accept"
3232        );
3233        assert!(!super::has_outbound_typed(), "stash taken by the re-entry");
3234
3235        // Drop inside on the target → on_drop receives the typed value.
3236        tree.end_external_drag(
3237            Point::new(150.0, 50.0),
3238            crate::drag_payload::ExternalDropData::default(),
3239            &mut ops,
3240        );
3241        assert_eq!(got_typed.get(), 123, "target received the typed payload");
3242        assert_eq!(
3243            ended.get(),
3244            0,
3245            "source on_drag_ended not fired by the drop itself"
3246        );
3247
3248        // OS posts the terminal event on the source window → exactly one
3249        // on_drag_ended, and since the drop landed back on the window that
3250        // started the drag, with the in-app outcome rather than the
3251        // platform's copy.
3252        tree.handle_os_drag_ended(DropOutcome::OsCopy, &mut ops);
3253        assert_eq!(ended.get(), 1, "on_drag_ended fired exactly once");
3254        assert_eq!(
3255            last_outcome.get(),
3256            Some(DropOutcome::InApp { accepted: true })
3257        );
3258    }
3259
3260    /// The same recovery works across two windows of the same app: window A
3261    /// starts the drag, the OS drag enters window B, and B's target receives
3262    /// the original typed payload.
3263    #[test]
3264    fn os_drag_reentry_recovers_typed_payload_across_windows() {
3265        use crate::drag_payload::{DragPayload, DropOutcome};
3266        use std::cell::Cell;
3267        use std::rc::Rc;
3268
3269        let started = Rc::new(std::cell::RefCell::new(Vec::new()));
3270        let mut ops = RecordingWindowOps {
3271            started,
3272            started_kinds: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3273            start: crate::drag_payload::OsDragStart::Started,
3274            pending_ids: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3275            cancels: std::rc::Rc::new(std::cell::Cell::new(0)),
3276            accepts: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3277        };
3278
3279        // Window A: starts and escalates.
3280        let mut tree_a = WidgetTree::new();
3281        let src = tree_a.add(FillWidget::new());
3282        tree_a.layout(SizeProposal::exact(200.0, 100.0));
3283        let mut ctx = crate::widget::EventContext::new();
3284        ctx.start_drag(
3285            src,
3286            DragPayload::typed(77_u32).with_mime("text/plain", b"x".to_vec()),
3287        );
3288        tree_a.collect_from_ctx(ctx, src);
3289        tree_a.handle_drag_move(Point::new(-5.0, 50.0), &mut ops);
3290        assert!(super::has_outbound_typed());
3291        assert_eq!(tree_a.outbound_drag_source, Some(src));
3292
3293        // Window B (separate tree, same thread ⇒ same global stash): the OS
3294        // drag enters and drops on B's target, which gets the typed value.
3295        let got = Rc::new(Cell::new(0_u32));
3296        let g = got.clone();
3297        let mut tree_b = WidgetTree::new();
3298        let _t = tree_b.add(FillWidget::new().on_drop(
3299            move |mut p, _, _| match p.take_typed::<u32>() {
3300                Some(v) => {
3301                    g.set(v);
3302                    true
3303                }
3304                None => false,
3305            },
3306        ));
3307        tree_b.layout(SizeProposal::exact(200.0, 100.0));
3308
3309        tree_b.begin_external_drag(
3310            Point::new(50.0, 50.0),
3311            crate::drag_payload::ExternalDropData::default(),
3312            &mut ops,
3313        );
3314        assert!(
3315            tree_b
3316                .active_drag
3317                .as_ref()
3318                .is_some_and(|d| d.payload.has_typed::<u32>()),
3319            "window B recovered the typed payload"
3320        );
3321        tree_b.end_external_drag(
3322            Point::new(50.0, 50.0),
3323            crate::drag_payload::ExternalDropData::default(),
3324            &mut ops,
3325        );
3326        assert_eq!(
3327            got.get(),
3328            77,
3329            "window B's target received the typed payload"
3330        );
3331
3332        // Source window A reports the terminal outcome.
3333        tree_a.handle_os_drag_ended(DropOutcome::OsCopy, &mut ops);
3334    }
3335
3336    /// A re-entered OS drag that leaves the window again re-stashes the typed
3337    /// payload (does not start a second OS drag, does not fire on_drag_ended),
3338    /// so a later window can still recover it.
3339    #[test]
3340    fn os_drag_reexit_restashes_payload() {
3341        use crate::drag_payload::DragPayload;
3342        use std::rc::Rc;
3343
3344        let started = Rc::new(std::cell::RefCell::new(Vec::new()));
3345        let mut ops = RecordingWindowOps {
3346            started: started.clone(),
3347            started_kinds: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3348            start: crate::drag_payload::OsDragStart::Started,
3349            pending_ids: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3350            cancels: std::rc::Rc::new(std::cell::Cell::new(0)),
3351            accepts: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3352        };
3353
3354        let mut tree = WidgetTree::new();
3355        let source = tree.add(FillWidget::new());
3356        tree.layout(SizeProposal::exact(200.0, 100.0));
3357        let mut ctx = crate::widget::EventContext::new();
3358        ctx.start_drag(
3359            source,
3360            DragPayload::typed(9_u32).with_mime("text/plain", b"x".to_vec()),
3361        );
3362        tree.collect_from_ctx(ctx, source);
3363
3364        // Escalate, then re-enter, then leave again.
3365        tree.handle_drag_move(Point::new(-5.0, 50.0), &mut ops);
3366        assert_eq!(started.borrow().len(), 1, "OS drag started once");
3367        tree.begin_external_drag(
3368            Point::new(100.0, 50.0),
3369            crate::drag_payload::ExternalDropData::default(),
3370            &mut ops,
3371        );
3372        assert!(tree.os_drag_reentered);
3373        tree.handle_drag_move(Point::new(-5.0, 50.0), &mut ops); // leave again
3374
3375        assert!(!tree.os_drag_reentered, "re-exited");
3376        assert!(tree.active_drag.is_none(), "session torn down on re-exit");
3377        assert!(super::has_outbound_typed(), "payload re-stashed");
3378        assert_eq!(
3379            started.borrow().len(),
3380            1,
3381            "no second OS drag started on re-exit"
3382        );
3383    }
3384
3385    /// Closing the source window mid-OS-drag clears the global stash, so a
3386    /// later genuine external drag from another app is NOT misrecovered as the
3387    /// stale typed payload. (Regression for the CRITICAL stash-leak finding.)
3388    #[test]
3389    fn source_window_close_clears_stash_no_hijack() {
3390        use crate::drag_payload::{DragPayload, ExternalDropData};
3391        use std::path::PathBuf;
3392        use std::rc::Rc;
3393
3394        let started = Rc::new(std::cell::RefCell::new(Vec::new()));
3395        let mut ops = RecordingWindowOps {
3396            started,
3397            started_kinds: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3398            start: crate::drag_payload::OsDragStart::Started,
3399            pending_ids: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3400            cancels: std::rc::Rc::new(std::cell::Cell::new(0)),
3401            accepts: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
3402        };
3403
3404        let mut tree = WidgetTree::new();
3405        let source = tree.add(FillWidget::new());
3406        let _target = tree.add(FillWidget::new().on_drop(|_, _, _| true));
3407        tree.layout(SizeProposal::exact(200.0, 100.0));
3408        let mut ctx = crate::widget::EventContext::new();
3409        ctx.start_drag(
3410            source,
3411            DragPayload::typed(5_u32).with_mime("text/plain", b"x".to_vec()),
3412        );
3413        tree.collect_from_ctx(ctx, source);
3414        tree.handle_drag_move(Point::new(-5.0, 50.0), &mut ops); // escalate
3415        assert!(super::has_outbound_typed());
3416        assert_eq!(tree.outbound_drag_source, Some(source));
3417
3418        // Window closes mid-drag.
3419        tree.abort_outbound_drag();
3420        assert!(
3421            !super::has_outbound_typed(),
3422            "stash cleared when the source window closes"
3423        );
3424        assert!(tree.outbound_drag_source.is_none());
3425
3426        // A later real external drag (another app) must present as external,
3427        // NOT recover the stale typed payload.
3428        tree.begin_external_drag(
3429            Point::new(50.0, 50.0),
3430            ExternalDropData {
3431                files: vec![PathBuf::from("/tmp/real")],
3432                ..Default::default()
3433            },
3434            &mut ops,
3435        );
3436        let d = tree.active_drag.as_ref().expect("external session");
3437        assert!(
3438            d.is_external,
3439            "stale stash did not hijack the new external drag"
3440        );
3441        assert!(
3442            !d.payload.has_typed::<u32>(),
3443            "no stale typed payload leaked in"
3444        );
3445        assert_eq!(d.payload.files(), &[PathBuf::from("/tmp/real")]);
3446    }
3447
3448    // ---------------------------------------------------------------
3449    // P31: the drag's own pointer, outside any sample
3450    // ---------------------------------------------------------------
3451
3452    use std::cell::{Cell, RefCell};
3453    use std::rc::Rc;
3454
3455    /// A leaf that arms a drag on its own `PointerDown`, the way a real widget's
3456    /// long-press or `on_drag` handler does.
3457    ///
3458    /// The drag HAS to be armed from inside the contact's own dispatch: that is
3459    /// the only place `current_input` names the finger, so it is the only place
3460    /// the session can record it. Building the payload from a factory keeps
3461    /// `DragPayload` (not `Clone`) out of the closure's captured state.
3462    fn drag_arming_leaf(
3463        slot: Rc<Cell<Option<WidgetId>>>,
3464        payload: impl Fn() -> crate::drag_payload::DragPayload + 'static,
3465    ) -> impl crate::widget::Widget {
3466        let armed = Cell::new(false);
3467        FillWidget::new().on_pointer_event(move |event, ctx| {
3468            if matches!(event, crate::event::WidgetEvent::PointerDown { .. })
3469                && !armed.replace(true)
3470                && let Some(id) = slot.get()
3471            {
3472                ctx.start_drag(id, payload());
3473            }
3474            crate::event::EventResponse::Ignored
3475        })
3476    }
3477
3478    /// Press a fresh touch contact at `at`, returning its id.
3479    fn touch_press(
3480        tree: &mut WidgetTree,
3481        at: Point,
3482        ops: &mut dyn crate::window::WindowOps,
3483    ) -> crate::pointer::PointerId {
3484        use crate::pointer::{
3485            BackendDeviceKey, PointerIdAllocator, PointerInfo, PointerPhase, PointerSample,
3486        };
3487        use std::sync::atomic::{AtomicU64, Ordering};
3488        static NEXT: AtomicU64 = AtomicU64::new(91_000);
3489        let contact = PointerIdAllocator::global().begin(
3490            BackendDeviceKey::DEFAULT,
3491            NEXT.fetch_add(1, Ordering::Relaxed),
3492        );
3493        tree.dispatch_pointer_with_ops(
3494            PointerSample {
3495                pointer: PointerInfo::touch(contact, crate::pointer::EventTime::from_millis(1)),
3496                phase: PointerPhase::Down,
3497                position: at,
3498                button: None,
3499                modifiers: Modifiers::NONE,
3500                coalesced: Vec::new(),
3501            },
3502            ops,
3503        );
3504        contact
3505    }
3506
3507    /// The placement an overlay currently carries.
3508    fn placement_of(
3509        tree: &WidgetTree,
3510        id: crate::overlay::OverlayId,
3511    ) -> crate::overlay::OverlayPlacement {
3512        tree.overlay_manager
3513            .stack
3514            .iter()
3515            .find(|o| o.id == id)
3516            .map(|o| o.placement.clone())
3517            .expect("the overlay is in the stack")
3518    }
3519
3520    /// The drag tick fires from `layout()`, outside any sample — and it must
3521    /// still tell its handler which device is dragging.
3522    ///
3523    /// This is the whole of the coarse auto-scroll band's reachability: every
3524    /// data view's `on_drag_tick` asks `ctx.pointer_kind()` for the band, and
3525    /// before the session carried a pointer the answer was `Mouse` for the whole
3526    /// of a finger drag, so the wider band could never apply.
3527    #[test]
3528    fn a_drag_tick_reports_the_device_that_started_the_drag() {
3529        let seen: Rc<RefCell<Vec<teksilo_tokens::PointerKind>>> = Rc::new(RefCell::new(Vec::new()));
3530        let s = seen.clone();
3531
3532        let mut tree = WidgetTree::new();
3533        let target = tree.add(
3534            FillWidget::new()
3535                .on_drop(|_, _, _| true)
3536                .on_drag_tick(move |_pos, ctx| s.borrow_mut().push(ctx.pointer_kind())),
3537        );
3538        tree.layout(SizeProposal::exact(200.0, 100.0));
3539
3540        // A mouse drag first: the pre-existing answer, unchanged.
3541        let mut ctx = crate::widget::EventContext::new();
3542        ctx.start_drag(target, crate::drag_payload::DragPayload::typed(1_u8));
3543        tree.collect_from_ctx(ctx, target);
3544        tree.handle_drag_move(Point::new(50.0, 50.0), &mut crate::window::NoopWindowOps);
3545        tree.layout(SizeProposal::exact(200.0, 100.0));
3546        assert_eq!(
3547            *seen.borrow(),
3548            vec![teksilo_tokens::PointerKind::Mouse],
3549            "a mouse drag still reports the mouse"
3550        );
3551        tree.cancel_active_drag(&mut crate::window::NoopWindowOps);
3552        seen.borrow_mut().clear();
3553
3554        // Now a finger, arming its drag from inside its own press. The same node
3555        // is source, drop target and tick owner — a row of a reorderable list.
3556        let mut ops = crate::window::NoopWindowOps;
3557        let s = seen.clone();
3558        let slot: Rc<Cell<Option<WidgetId>>> = Rc::new(Cell::new(None));
3559        let armed = Cell::new(false);
3560        let s2 = slot.clone();
3561        let mut tree = WidgetTree::new();
3562        let row = tree.add(
3563            FillWidget::new()
3564                .on_pointer_event(move |event, ctx| {
3565                    if matches!(event, crate::event::WidgetEvent::PointerDown { .. })
3566                        && !armed.replace(true)
3567                        && let Some(id) = s2.get()
3568                    {
3569                        ctx.start_drag(id, crate::drag_payload::DragPayload::typed(2_u8));
3570                    }
3571                    crate::event::EventResponse::Ignored
3572                })
3573                .on_drop(|_, _, _| true)
3574                .on_drag_tick(move |_pos, ctx| s.borrow_mut().push(ctx.pointer_kind())),
3575        );
3576        slot.set(Some(row));
3577        tree.layout(SizeProposal::exact(200.0, 100.0));
3578        touch_press(&mut tree, Point::new(50.0, 50.0), &mut ops);
3579        assert!(tree.active_drag.is_some(), "the finger armed a drag");
3580        tree.handle_drag_move(Point::new(50.0, 50.0), &mut ops);
3581        tree.layout(SizeProposal::exact(200.0, 100.0));
3582        assert_eq!(
3583            *seen.borrow(),
3584            vec![teksilo_tokens::PointerKind::Touch],
3585            "and a finger drag reports the finger, from a tick that has no sample"
3586        );
3587    }
3588
3589    /// The preview is placed clear of a coarse contact and byte-identically at
3590    /// the point for a mouse.
3591    ///
3592    /// A preview pinned to the pixel a finger reported sits under the hand
3593    /// carrying it, so the user drags something they cannot see. `AtPointer`
3594    /// stays exactly `AtPointer` for a cursor, which is what keeps mouse
3595    /// placement unchanged.
3596    #[test]
3597    fn the_preview_avoids_a_coarse_contact_and_still_pins_a_cursor() {
3598        use crate::overlay::OverlayPlacement;
3599
3600        let mut ops = crate::window::NoopWindowOps;
3601        let at = Point::new(60.0, 40.0);
3602
3603        // Mouse.
3604        let mut tree = WidgetTree::new();
3605        let source = tree.add(FillWidget::new());
3606        tree.layout(SizeProposal::exact(200.0, 100.0));
3607        let mut ctx = crate::widget::EventContext::new();
3608        ctx.start_drag_with_preview(
3609            source,
3610            crate::drag_payload::DragPayload::typed(1_u8),
3611            Box::new(FillWidget::new()),
3612        );
3613        tree.collect_from_ctx(ctx, source);
3614        tree.handle_drag_move(at, &mut ops);
3615        let overlay = tree
3616            .active_drag
3617            .as_ref()
3618            .and_then(|d| d.preview_overlay_id)
3619            .expect("the preview overlay exists");
3620        assert!(
3621            matches!(placement_of(&tree, overlay), OverlayPlacement::AtPointer(p) if p == at),
3622            "a mouse keeps AtPointer at the reported point, unchanged",
3623        );
3624
3625        // Finger: the same drag, armed from inside a contact's press so the
3626        // session records it, with a preview attached the way the router does.
3627        let mut tree = WidgetTree::new();
3628        let slot: Rc<Cell<Option<WidgetId>>> = Rc::new(Cell::new(None));
3629        let source = tree.add(drag_arming_leaf_with_preview(slot.clone()));
3630        slot.set(Some(source));
3631        tree.layout(SizeProposal::exact(200.0, 100.0));
3632        touch_press(&mut tree, at, &mut ops);
3633        assert_eq!(
3634            tree.active_drag.as_ref().map(|d| d.pointer.kind),
3635            Some(teksilo_tokens::PointerKind::Touch),
3636            "the session recorded the finger",
3637        );
3638        tree.handle_drag_move(at, &mut ops);
3639        let overlay = tree
3640            .active_drag
3641            .as_ref()
3642            .and_then(|d| d.preview_overlay_id)
3643            .expect("the preview overlay exists");
3644        match placement_of(&tree, overlay) {
3645            OverlayPlacement::AtPointerAvoiding { point, avoid } => {
3646                assert_eq!(point, at);
3647                assert!(
3648                    avoid.contains(at),
3649                    "the rectangle to clear is centred on the contact, so no \
3650                     placement that honours it can put the preview under the hand",
3651                );
3652            }
3653            other => panic!("a coarse pointer must avoid its own contact, got {other:?}"),
3654        }
3655    }
3656
3657    /// The `drag_arming_leaf` above, but with a preview — the shape
3658    /// `ListView`/`TreeView` use.
3659    fn drag_arming_leaf_with_preview(
3660        slot: Rc<Cell<Option<WidgetId>>>,
3661    ) -> impl crate::widget::Widget {
3662        let armed = Cell::new(false);
3663        FillWidget::new().on_pointer_event(move |event, ctx| {
3664            if matches!(event, crate::event::WidgetEvent::PointerDown { .. })
3665                && !armed.replace(true)
3666                && let Some(id) = slot.get()
3667            {
3668                ctx.start_drag_with_preview(
3669                    id,
3670                    crate::drag_payload::DragPayload::typed(1_u8),
3671                    Box::new(FillWidget::new()),
3672                );
3673            }
3674            crate::event::EventResponse::Ignored
3675        })
3676    }
3677
3678    /// Escalation revokes the pointer that was **dragging**, not whichever
3679    /// pointer the singular accessor happens to name.
3680    ///
3681    /// A drag tick can move the reported position outside the window (it
3682    /// scrolls the content under a stationary finger), and a tick runs outside
3683    /// any sample — where `current_pointer_id` answers "the mouse". Cancelling
3684    /// the mouse there would leave the real contact armed with a sequence for a
3685    /// drag the OS had taken over.
3686    #[test]
3687    fn an_os_drag_started_by_a_finger_cancels_that_finger() {
3688        let cancelled: Rc<RefCell<Vec<(crate::pointer::PointerId, crate::pointer::CancelReason)>>> =
3689            Rc::new(RefCell::new(Vec::new()));
3690        let c = cancelled.clone();
3691
3692        let mut ops = RecordingWindowOps::new(true);
3693        let kinds = ops.started_kinds.clone();
3694
3695        let mut tree = WidgetTree::new();
3696        let slot: Rc<Cell<Option<WidgetId>>> = Rc::new(Cell::new(None));
3697        let armed = Cell::new(false);
3698        let s2 = slot.clone();
3699        let source = tree.add(
3700            FillWidget::new()
3701                .on_pointer_event(move |event, ctx| {
3702                    if matches!(event, crate::event::WidgetEvent::PointerDown { .. })
3703                        && !armed.replace(true)
3704                        && let Some(id) = s2.get()
3705                    {
3706                        ctx.start_drag(id, exportable_payload());
3707                    }
3708                    crate::event::EventResponse::Ignored
3709                })
3710                .on_pointer_cancel(move |pointer, reason, _ctx| {
3711                    c.borrow_mut().push((pointer.id, reason));
3712                }),
3713        );
3714        slot.set(Some(source));
3715        tree.layout(SizeProposal::exact(200.0, 100.0));
3716
3717        let contact = touch_press(&mut tree, Point::new(20.0, 50.0), &mut ops);
3718        assert!(tree.active_drag.is_some());
3719
3720        // Out of the window: the drag escalates.
3721        tree.handle_drag_move(Point::new(-40.0, 50.0), &mut ops);
3722        assert_eq!(tree.outbound_drag_source, Some(source));
3723        assert_eq!(
3724            *kinds.borrow(),
3725            vec![teksilo_tokens::PointerKind::Touch],
3726            "the platform is told which device is dragging — Wayland needs the \
3727             touch-down serial, not a button serial"
3728        );
3729        assert_eq!(
3730            *cancelled.borrow(),
3731            vec![(contact, crate::pointer::CancelReason::OsDragStarted)],
3732            "the finger is the pointer revoked"
3733        );
3734        tree.handle_os_drag_ended(crate::drag_payload::DropOutcome::Cancelled, &mut ops);
3735    }
3736
3737    /// An Escape-cancelled finger drag still reports the finger to the source.
3738    ///
3739    /// The Escape arrives as a key dispatch, which serves no pointer at all, so
3740    /// without the drag's own pointer installed the source's `on_drag_ended`
3741    /// would be told a mouse cancelled the drag a finger had been carrying —
3742    /// the same divergence as the tick, at the other end of the same drag.
3743    #[test]
3744    fn an_escape_cancelled_finger_drag_reports_the_finger_to_its_source() {
3745        let seen: Rc<RefCell<Vec<teksilo_tokens::PointerKind>>> = Rc::new(RefCell::new(Vec::new()));
3746        let s = seen.clone();
3747
3748        let mut ops = crate::window::NoopWindowOps;
3749        let mut tree = WidgetTree::new();
3750        let slot: Rc<Cell<Option<WidgetId>>> = Rc::new(Cell::new(None));
3751        let armed = Cell::new(false);
3752        let s2 = slot.clone();
3753        let source = tree.add(
3754            FillWidget::new()
3755                .on_pointer_event(move |event, ctx| {
3756                    if matches!(event, crate::event::WidgetEvent::PointerDown { .. })
3757                        && !armed.replace(true)
3758                        && let Some(id) = s2.get()
3759                    {
3760                        ctx.start_drag(id, crate::drag_payload::DragPayload::typed(1_u8));
3761                    }
3762                    crate::event::EventResponse::Ignored
3763                })
3764                .on_drag_ended(move |_outcome, ctx| s.borrow_mut().push(ctx.pointer_kind())),
3765        );
3766        slot.set(Some(source));
3767        tree.layout(SizeProposal::exact(200.0, 100.0));
3768
3769        touch_press(&mut tree, Point::new(50.0, 50.0), &mut ops);
3770        assert!(tree.active_drag.is_some());
3771        tree.dispatch_event_with_ops(
3772            crate::event::WidgetEvent::KeyDown {
3773                key: crate::event::Key::Escape,
3774                modifiers: crate::event::Modifiers::NONE,
3775                text: None,
3776            },
3777            &mut ops,
3778        );
3779        assert_eq!(*seen.borrow(), vec![teksilo_tokens::PointerKind::Touch]);
3780    }
3781
3782    /// The widget's verdict reaches the platform, and only when it changes.
3783    ///
3784    /// An inbound backend has to answer the drag source before the tree has seen
3785    /// the position, so its first answer is about formats alone; without this the
3786    /// OS showed "will accept" over a target that refuses the payload.
3787    #[test]
3788    fn the_accept_setter_receives_the_widget_verdict() {
3789        use crate::drag_state::DropFeedback;
3790
3791        let verdict = Rc::new(Cell::new(false));
3792        let v = verdict.clone();
3793        let mut ops = RecordingWindowOps::new(true);
3794        let accepts = ops.accepts.clone();
3795
3796        let mut tree = WidgetTree::new();
3797        tree.add(
3798            FillWidget::new()
3799                .on_drag_hover(move |_p, _pos, _ctx| {
3800                    if v.get() {
3801                        DropFeedback::Accept
3802                    } else {
3803                        DropFeedback::NoFeedback
3804                    }
3805                })
3806                .on_drop(|_, _, _| true),
3807        );
3808        tree.layout(SizeProposal::exact(200.0, 100.0));
3809
3810        tree.begin_external_drag(
3811            Point::new(50.0, 50.0),
3812            crate::drag_payload::ExternalDropData {
3813                files: vec![std::path::PathBuf::from("/tmp/a.png")],
3814                ..Default::default()
3815            },
3816            &mut ops,
3817        );
3818        assert_eq!(
3819            *accepts.borrow(),
3820            vec![false],
3821            "a refusing target is reported to the OS as a refusal"
3822        );
3823
3824        // Same answer again: nothing more is pushed. The OS side is a round trip
3825        // per call and a motion stream would repeat it every sample.
3826        tree.update_external_drag(Point::new(52.0, 50.0), &mut ops);
3827        assert_eq!(
3828            *accepts.borrow(),
3829            vec![false],
3830            "an unchanged answer is not re-sent"
3831        );
3832
3833        // The target changes its mind.
3834        verdict.set(true);
3835        tree.update_external_drag(Point::new(54.0, 50.0), &mut ops);
3836        assert_eq!(
3837            *accepts.borrow(),
3838            vec![false, true],
3839            "and a change is pushed once"
3840        );
3841    }
3842
3843    /// An in-app drag is not an OS drag, and must not push an accept state to a
3844    /// platform that has nothing in flight to revise.
3845    #[test]
3846    fn an_in_app_drag_pushes_no_os_accept_state() {
3847        let mut ops = RecordingWindowOps::new(true);
3848        let accepts = ops.accepts.clone();
3849
3850        let mut tree = WidgetTree::new();
3851        let source = tree.add(FillWidget::new());
3852        tree.add(FillWidget::new().on_drop(|_, _, _| true));
3853        tree.layout(SizeProposal::exact(200.0, 100.0));
3854
3855        let mut ctx = crate::widget::EventContext::new();
3856        ctx.start_drag(source, crate::drag_payload::DragPayload::typed(1_u8));
3857        tree.collect_from_ctx(ctx, source);
3858        tree.handle_drag_move(Point::new(50.0, 50.0), &mut ops);
3859
3860        assert!(accepts.borrow().is_empty());
3861    }
3862
3863    /// A cancelled OS drag tears the source down **exactly once**, whichever
3864    /// order the platform reports it in.
3865    ///
3866    /// Two independent paths could fire the source's `on_drag_ended`: the
3867    /// terminal `DragEnded` on the window that started the drag, and the abort
3868    /// delivered to whichever window was holding the re-entered session. Only
3869    /// the first owns it, and a backend that reports a terminal twice (some
3870    /// compositors send both `dnd_finished` and `cancelled`) must not double it.
3871    #[test]
3872    fn a_cancelled_os_drag_tears_the_source_down_exactly_once() {
3873        use crate::drag_payload::{DragPayload, DropOutcome};
3874
3875        let ended = Rc::new(RefCell::new(Vec::new()));
3876        let e = ended.clone();
3877        let mut ops = RecordingWindowOps::new(true);
3878
3879        // Window A starts and escalates.
3880        let mut tree_a = WidgetTree::new();
3881        let src = tree_a.add(
3882            FillWidget::new().on_drag_ended(move |outcome, _ctx| e.borrow_mut().push(outcome)),
3883        );
3884        tree_a.layout(SizeProposal::exact(200.0, 100.0));
3885        let mut ctx = crate::widget::EventContext::new();
3886        ctx.start_drag(
3887            src,
3888            DragPayload::typed(5_u32).with_mime("text/plain", b"x".to_vec()),
3889        );
3890        tree_a.collect_from_ctx(ctx, src);
3891        tree_a.handle_drag_move(Point::new(-5.0, 50.0), &mut ops);
3892        assert!(super::outbound_is_live());
3893
3894        // Window B picks the drag up as a re-entered session.
3895        let left = Rc::new(Cell::new(0_u32));
3896        let l = left.clone();
3897        let mut tree_b = WidgetTree::new();
3898        tree_b.add(
3899            FillWidget::new()
3900                .on_drag_hover(|_, _, _| crate::drag_state::DropFeedback::Accept)
3901                .on_drag_leave(move |_ctx| l.set(l.get() + 1))
3902                .on_drop(|_, _, _| true),
3903        );
3904        tree_b.layout(SizeProposal::exact(200.0, 100.0));
3905        let accepts = ops.accepts.clone();
3906        accepts.borrow_mut().clear();
3907        tree_b.begin_external_drag(
3908            Point::new(50.0, 50.0),
3909            crate::drag_payload::ExternalDropData::default(),
3910            &mut ops,
3911        );
3912        assert!(tree_b.os_drag_reentered);
3913        assert_eq!(
3914            *accepts.borrow(),
3915            vec![true],
3916            "a re-entered app drag still negotiates with the OS: its offer is \
3917             live and a refusal must still reach the compositor's cursor",
3918        );
3919
3920        // The OS aborts. B is told, and clears without claiming the source's
3921        // notification — B has no source widget.
3922        tree_b.abort_external_drag(&mut ops);
3923        assert!(tree_b.active_drag.is_none(), "B's session is gone");
3924        assert!(!tree_b.os_drag_reentered);
3925        assert_eq!(left.get(), 1, "B's highlighted target was cleared");
3926        assert!(
3927            ended.borrow().is_empty(),
3928            "the abort must not fire the source's on_drag_ended — the source \
3929             window owns that"
3930        );
3931
3932        // A's terminal event fires it, once.
3933        tree_a.handle_os_drag_ended(DropOutcome::Cancelled, &mut ops);
3934        assert_eq!(*ended.borrow(), vec![DropOutcome::Cancelled]);
3935
3936        // A second terminal from a backend that reports both must add nothing.
3937        tree_a.handle_os_drag_ended(DropOutcome::Cancelled, &mut ops);
3938        assert_eq!(
3939            *ended.borrow(),
3940            vec![DropOutcome::Cancelled],
3941            "exactly once"
3942        );
3943    }
3944
3945    /// A window holding a re-entered OS drag notices when the drag ends
3946    /// elsewhere, and drops the session on its next layout pass.
3947    ///
3948    /// The terminal `DragEnded` goes to the window that *started* the drag, and
3949    /// that is not necessarily the one showing the re-entered session — so
3950    /// without this the other window kept a live `active_drag`, a highlighted
3951    /// drop target and an `os_drag_reentered` flag for a drag that no longer
3952    /// existed, for the rest of the process. Nothing further ever arrives for
3953    /// it from the OS, so the condition has to be noticed from the inside.
3954    #[test]
3955    fn a_reentered_session_is_reaped_when_the_os_drag_ends_elsewhere() {
3956        use crate::drag_payload::{DragPayload, DropOutcome};
3957
3958        let mut ops = RecordingWindowOps::new(true);
3959
3960        let mut tree_a = WidgetTree::new();
3961        let src = tree_a.add(FillWidget::new());
3962        tree_a.layout(SizeProposal::exact(200.0, 100.0));
3963        let mut ctx = crate::widget::EventContext::new();
3964        ctx.start_drag(
3965            src,
3966            DragPayload::typed(9_u32).with_mime("text/plain", b"x".to_vec()),
3967        );
3968        tree_a.collect_from_ctx(ctx, src);
3969        tree_a.handle_drag_move(Point::new(-5.0, 50.0), &mut ops);
3970
3971        let left = Rc::new(Cell::new(0_u32));
3972        let l = left.clone();
3973        let mut tree_b = WidgetTree::new();
3974        tree_b.add(
3975            FillWidget::new()
3976                .on_drag_hover(|_, _, _| crate::drag_state::DropFeedback::Accept)
3977                .on_drag_leave(move |_ctx| l.set(l.get() + 1))
3978                .on_drop(|_, _, _| true),
3979        );
3980        tree_b.layout(SizeProposal::exact(200.0, 100.0));
3981        tree_b.begin_external_drag(
3982            Point::new(50.0, 50.0),
3983            crate::drag_payload::ExternalDropData::default(),
3984            &mut ops,
3985        );
3986        assert!(tree_b.active_drag.is_some() && tree_b.os_drag_reentered);
3987
3988        // A's window reports the terminal outcome. B hears nothing.
3989        tree_a.handle_os_drag_ended(DropOutcome::Cancelled, &mut ops);
3990        assert!(
3991            tree_b.active_drag.is_some(),
3992            "B has not been told anything yet"
3993        );
3994
3995        // B's next layout pass notices the stash is dead.
3996        tree_b.layout(SizeProposal::exact(200.0, 100.0));
3997        assert!(tree_b.active_drag.is_none(), "the dead session was reaped");
3998        assert!(!tree_b.os_drag_reentered);
3999        assert_eq!(left.get(), 1, "and its highlighted target was cleared");
4000    }
4001
4002    /// A re-entered app drag carries the device that started it, so the window
4003    /// it lands in reads the finger — the one case where an inbound OS drag's
4004    /// kind is knowable at all.
4005    #[test]
4006    fn a_reentered_app_drag_recovers_the_device_that_started_it() {
4007        let mut ops = RecordingWindowOps::new(true);
4008
4009        let mut tree_a = WidgetTree::new();
4010        let slot: Rc<Cell<Option<WidgetId>>> = Rc::new(Cell::new(None));
4011        let src = tree_a.add(drag_arming_leaf(slot.clone(), exportable_payload));
4012        slot.set(Some(src));
4013        tree_a.layout(SizeProposal::exact(200.0, 100.0));
4014        touch_press(&mut tree_a, Point::new(20.0, 50.0), &mut ops);
4015        tree_a.handle_drag_move(Point::new(-5.0, 50.0), &mut ops);
4016        assert!(super::outbound_is_live());
4017
4018        let mut tree_b = WidgetTree::new();
4019        tree_b.add(FillWidget::new().on_drop(|_, _, _| true));
4020        tree_b.layout(SizeProposal::exact(200.0, 100.0));
4021        tree_b.begin_external_drag(
4022            Point::new(50.0, 50.0),
4023            crate::drag_payload::ExternalDropData::default(),
4024            &mut ops,
4025        );
4026        assert_eq!(
4027            tree_b.active_drag.as_ref().map(|d| d.pointer.kind),
4028            Some(teksilo_tokens::PointerKind::Touch),
4029        );
4030
4031        // A foreign drag, by contrast, is credited to no device at all.
4032        let mut tree_c = WidgetTree::new();
4033        tree_c.add(FillWidget::new().on_drop(|_, _, _| true));
4034        tree_c.layout(SizeProposal::exact(200.0, 100.0));
4035        tree_a.handle_os_drag_ended(crate::drag_payload::DropOutcome::Cancelled, &mut ops);
4036        tree_c.begin_external_drag(
4037            Point::new(50.0, 50.0),
4038            crate::drag_payload::ExternalDropData::default(),
4039            &mut ops,
4040        );
4041        assert_eq!(
4042            tree_c.active_drag.as_ref().map(|d| d.pointer.kind),
4043            Some(teksilo_tokens::PointerKind::Unknown),
4044            "no OS names the source's device to a destination",
4045        );
4046    }
4047
4048    /// A re-stash that races in *after* the drag's terminal event must not
4049    /// resurrect a finished drag (cross-window drop-on-nothing race). Tests the
4050    /// liveness gate directly. (Regression for the HIGH race finding.)
4051    #[test]
4052    fn restash_after_drag_ended_is_noop() {
4053        use crate::drag_payload::DragPayload;
4054
4055        super::outbound_begin(
4056            DragPayload::typed(1_u32).with_mime("text/plain", b"x".to_vec()),
4057            crate::pointer::PointerInfo::mouse(crate::pointer::EventTime::ZERO),
4058        );
4059        assert!(super::has_outbound_typed());
4060        // A window re-entered and took the payload.
4061        let held = super::outbound_take_if_live().expect("payload taken while live");
4062        assert!(!super::has_outbound_typed());
4063        // The source window's terminal DragEnded ends the drag first.
4064        super::outbound_end();
4065        // The other window's late re-stash must be dropped, not resurrected.
4066        super::outbound_restash(held);
4067        assert!(
4068            !super::has_outbound_typed(),
4069            "ended drag is not resurrected by a racing re-stash"
4070        );
4071        // And a take after end yields nothing.
4072        assert!(super::outbound_take_if_live().is_none());
4073    }
4074
4075    // ---------------------------------------------------------------
4076    // OsHandoff::Eager and the two-phase native start
4077    // ---------------------------------------------------------------
4078
4079    fn pending() -> crate::drag_payload::OsDragStart {
4080        crate::drag_payload::OsDragStart::Pending(crate::drag_payload::OsDragId::next())
4081    }
4082
4083    /// The id of the last start `ops` answered `Pending`.
4084    fn last_pending(ops: &RecordingWindowOps) -> crate::drag_payload::OsDragId {
4085        *ops.pending_ids.borrow().last().expect("a pending start")
4086    }
4087
4088    fn eager_payload() -> crate::drag_payload::DragPayload {
4089        exportable_payload().with_os_handoff(crate::drag_payload::OsHandoff::Eager)
4090    }
4091
4092    /// A tree with an exportable drag in flight from `source`, which records
4093    /// every `on_drag_ended` outcome in `ended`.
4094    fn tree_dragging(
4095        payload: crate::drag_payload::DragPayload,
4096    ) -> (
4097        WidgetTree,
4098        WidgetId,
4099        Rc<RefCell<Vec<crate::drag_payload::DropOutcome>>>,
4100    ) {
4101        let ended: Rc<RefCell<Vec<crate::drag_payload::DropOutcome>>> =
4102            Rc::new(RefCell::new(Vec::new()));
4103        let e = ended.clone();
4104        let mut tree = WidgetTree::new();
4105        let source =
4106            tree.add(FillWidget::new().on_drag_ended(move |o, _ctx| e.borrow_mut().push(o)));
4107        tree.layout(SizeProposal::exact(200.0, 100.0));
4108        let mut ctx = crate::widget::EventContext::new();
4109        ctx.start_drag(source, payload);
4110        tree.collect_from_ctx(ctx, source);
4111        assert!(tree.active_drag.is_some());
4112        (tree, source, ended)
4113    }
4114
4115    #[test]
4116    fn an_eager_drag_hands_off_on_the_first_pointer_move_inside_the_window() {
4117        let mut ops = RecordingWindowOps::new(true);
4118        let started = ops.started.clone();
4119        let (mut tree, source, ended) = tree_dragging(eager_payload());
4120
4121        // A real pointer sample, through the router, well inside the window.
4122        tree.dispatch_event_with_ops(WidgetEvent::pointer_move(Point::new(100.0, 50.0)), &mut ops);
4123        assert_eq!(started.borrow().len(), 1, "begin_os_drag asked once");
4124        assert!(tree.active_drag.is_none(), "in-app session handed over");
4125        assert_eq!(tree.outbound_drag_source, Some(source));
4126        assert!(super::has_outbound_typed(), "typed payload parked");
4127
4128        // Further moves are the OS's; nothing asks again.
4129        tree.dispatch_event_with_ops(WidgetEvent::pointer_move(Point::new(120.0, 50.0)), &mut ops);
4130        assert_eq!(started.borrow().len(), 1);
4131        tree.handle_os_drag_ended(crate::drag_payload::DropOutcome::OsCopy, &mut ops);
4132        assert_eq!(
4133            *ended.borrow(),
4134            vec![crate::drag_payload::DropOutcome::OsCopy]
4135        );
4136    }
4137
4138    #[test]
4139    fn an_at_window_edge_drag_stays_in_app_while_the_pointer_is_inside() {
4140        let mut ops = RecordingWindowOps::new(true);
4141        let started = ops.started.clone();
4142        let (mut tree, source, _ended) = tree_dragging(exportable_payload());
4143        tree.dispatch_event_with_ops(WidgetEvent::pointer_move(Point::new(100.0, 50.0)), &mut ops);
4144        assert!(started.borrow().is_empty());
4145        assert!(tree.active_drag.is_some());
4146        tree.handle_drag_sample(Point::new(-5.0, 50.0), &mut ops);
4147        assert_eq!(started.borrow().len(), 1, "the window edge still hands off");
4148        assert_eq!(tree.outbound_drag_source, Some(source));
4149        tree.handle_os_drag_ended(crate::drag_payload::DropOutcome::Cancelled, &mut ops);
4150    }
4151
4152    #[test]
4153    fn an_eager_drag_waits_for_a_pointer_sample_rather_than_a_drag_tick() {
4154        let mut ops = RecordingWindowOps::new(true);
4155        let started = ops.started.clone();
4156        let (mut tree, _source, _ended) = tree_dragging(eager_payload());
4157
4158        // A drag tick (and every other move that is not a sample) runs outside
4159        // any input event; macOS cannot start a drag there.
4160        tree.handle_drag_move(Point::new(100.0, 50.0), &mut ops);
4161        tree.layout(SizeProposal::exact(200.0, 100.0));
4162        assert!(started.borrow().is_empty(), "no handoff from a tick");
4163        assert!(tree.active_drag.is_some());
4164
4165        tree.handle_drag_sample(Point::new(101.0, 50.0), &mut ops);
4166        assert_eq!(started.borrow().len(), 1, "the next sample hands off");
4167        tree.handle_os_drag_ended(crate::drag_payload::DropOutcome::Cancelled, &mut ops);
4168    }
4169
4170    #[test]
4171    fn a_refused_eager_handoff_is_asked_again_on_the_next_sample() {
4172        let mut ops = RecordingWindowOps::new(false);
4173        let started = ops.started.clone();
4174        let (mut tree, source, _ended) = tree_dragging(eager_payload());
4175
4176        tree.handle_drag_sample(Point::new(100.0, 50.0), &mut ops);
4177        assert_eq!(started.borrow().len(), 1);
4178        assert!(
4179            tree.active_drag.is_some(),
4180            "a refusal keeps the in-app drag"
4181        );
4182        tree.handle_drag_sample(Point::new(101.0, 50.0), &mut ops);
4183        assert_eq!(
4184            started.borrow().len(),
4185            2,
4186            "no latch: the next move asks again"
4187        );
4188
4189        ops.start = crate::drag_payload::OsDragStart::Started;
4190        tree.handle_drag_sample(Point::new(102.0, 50.0), &mut ops);
4191        assert_eq!(started.borrow().len(), 3);
4192        assert_eq!(tree.outbound_drag_source, Some(source), "handed off once");
4193        tree.handle_drag_sample(Point::new(103.0, 50.0), &mut ops);
4194        assert_eq!(started.borrow().len(), 3);
4195        tree.handle_os_drag_ended(crate::drag_payload::DropOutcome::Cancelled, &mut ops);
4196    }
4197
4198    #[test]
4199    fn eager_without_anything_to_export_never_hands_off() {
4200        let mut ops = RecordingWindowOps::new(true);
4201        let started = ops.started.clone();
4202        let (mut tree, _source, _ended) = tree_dragging(
4203            crate::drag_payload::DragPayload::typed(1_u32)
4204                .with_os_handoff(crate::drag_payload::OsHandoff::Eager),
4205        );
4206        tree.handle_drag_sample(Point::new(100.0, 50.0), &mut ops);
4207        tree.handle_drag_sample(Point::new(-5.0, 50.0), &mut ops);
4208        assert!(started.borrow().is_empty());
4209        assert!(tree.active_drag.is_some());
4210
4211        // An inbound drag from another application never escalates either.
4212        let mut tree = WidgetTree::new();
4213        tree.add(FillWidget::new().on_drop(|_, _, _| true));
4214        tree.layout(SizeProposal::exact(200.0, 100.0));
4215        let data = crate::drag_payload::ExternalDropData {
4216            text: Some("x".into()),
4217            ..Default::default()
4218        };
4219        tree.begin_external_drag(Point::new(10.0, 10.0), data, &mut ops);
4220        tree.update_external_drag(Point::new(-5.0, 10.0), &mut ops);
4221        assert!(started.borrow().is_empty());
4222    }
4223
4224    #[test]
4225    fn a_pending_start_keeps_the_in_app_drag_until_the_platform_confirms_it() {
4226        let mut ops = RecordingWindowOps::answering(pending());
4227        let started = ops.started.clone();
4228        let (mut tree, source, ended) = tree_dragging(eager_payload());
4229
4230        tree.handle_drag_sample(Point::new(100.0, 50.0), &mut ops);
4231        assert_eq!(started.borrow().len(), 1);
4232        assert!(
4233            tree.active_drag.is_some(),
4234            "the session waits for the platform"
4235        );
4236        assert!(tree.outbound_drag_source.is_none());
4237        assert!(
4238            !super::has_outbound_typed(),
4239            "nothing parked before the start"
4240        );
4241
4242        // A start is in flight: more moves keep the in-app drag going and do not
4243        // ask a second time.
4244        tree.handle_drag_sample(Point::new(110.0, 50.0), &mut ops);
4245        tree.handle_drag_sample(Point::new(-5.0, 50.0), &mut ops);
4246        assert_eq!(started.borrow().len(), 1, "one request per start");
4247        assert!(tree.active_drag.is_some());
4248
4249        tree.confirm_os_drag(last_pending(&ops), &mut ops);
4250        assert!(
4251            tree.active_drag.is_none(),
4252            "handed over at the confirmation"
4253        );
4254        assert_eq!(tree.outbound_drag_source, Some(source));
4255        assert!(super::has_outbound_typed());
4256        assert!(ended.borrow().is_empty());
4257        tree.handle_os_drag_ended(crate::drag_payload::DropOutcome::OsCopy, &mut ops);
4258        assert_eq!(
4259            *ended.borrow(),
4260            vec![crate::drag_payload::DropOutcome::OsCopy]
4261        );
4262    }
4263
4264    #[test]
4265    fn a_release_before_the_native_drag_starts_ends_the_drag_as_cancelled() {
4266        use crate::drag_payload::DropOutcome;
4267        let mut ops = RecordingWindowOps::answering(pending());
4268        let cancels = ops.cancels.clone();
4269        let dropped = Rc::new(Cell::new(0_u32));
4270        let d = dropped.clone();
4271        let (mut tree, _source, ended) = tree_dragging(eager_payload());
4272        tree.add(FillWidget::new().on_drop(move |_, _, _| {
4273            d.set(d.get() + 1);
4274            true
4275        }));
4276        tree.layout(SizeProposal::exact(200.0, 100.0));
4277
4278        tree.handle_drag_sample(Point::new(150.0, 50.0), &mut ops);
4279        tree.dispatch_event_with_ops(
4280            WidgetEvent::pointer_up(
4281                Point::new(150.0, 50.0),
4282                PointerButton::Primary,
4283                Modifiers::NONE,
4284            ),
4285            &mut ops,
4286        );
4287        assert!(tree.active_drag.is_none());
4288        assert_eq!(dropped.get(), 0, "no drop is delivered");
4289        assert_eq!(*ended.borrow(), vec![DropOutcome::Cancelled]);
4290        assert_eq!(cancels.get(), 1, "the platform is told to drop the start");
4291
4292        // The platform's late confirmation finds nothing waiting and asks it to
4293        // end the native drag nothing owns; its terminal event is silent.
4294        tree.confirm_os_drag(last_pending(&ops), &mut ops);
4295        assert_eq!(cancels.get(), 2);
4296        assert!(tree.outbound_drag_source.is_none());
4297        tree.handle_os_drag_ended(DropOutcome::Cancelled, &mut ops);
4298        assert_eq!(ended.borrow().len(), 1, "on_drag_ended fired once");
4299        tree.assert_no_leaked_pointer_state();
4300    }
4301
4302    #[test]
4303    fn escape_before_the_native_drag_starts_abandons_the_start() {
4304        use crate::drag_payload::DropOutcome;
4305        let mut ops = RecordingWindowOps::answering(pending());
4306        let cancels = ops.cancels.clone();
4307        let (mut tree, _source, ended) = tree_dragging(eager_payload());
4308        tree.handle_drag_sample(Point::new(100.0, 50.0), &mut ops);
4309        tree.dispatch_event_with_ops(
4310            WidgetEvent::KeyDown {
4311                key: Key::Escape,
4312                modifiers: Modifiers::NONE,
4313                text: None,
4314            },
4315            &mut ops,
4316        );
4317        assert_eq!(cancels.get(), 1);
4318        assert!(tree.os_drag_pending.is_none());
4319        assert_eq!(*ended.borrow(), vec![DropOutcome::Cancelled]);
4320    }
4321
4322    #[test]
4323    fn a_start_that_fails_on_the_platform_ends_the_drag_once() {
4324        use crate::drag_payload::DropOutcome;
4325        let mut ops = RecordingWindowOps::answering(pending());
4326        let cancels = ops.cancels.clone();
4327        let (mut tree, _source, ended) = tree_dragging(eager_payload());
4328        tree.handle_drag_sample(Point::new(100.0, 50.0), &mut ops);
4329
4330        // No press serial, no selection ownership: the backend reports the
4331        // drag ended without starting it.
4332        tree.handle_os_drag_ended(DropOutcome::Cancelled, &mut ops);
4333        assert!(tree.active_drag.is_none());
4334        assert!(tree.os_drag_pending.is_none());
4335        assert_eq!(*ended.borrow(), vec![DropOutcome::Cancelled]);
4336        assert_eq!(cancels.get(), 0, "the backend ended it already");
4337    }
4338
4339    #[test]
4340    fn closing_the_window_drops_a_pending_start() {
4341        let mut ops = RecordingWindowOps::answering(pending());
4342        let (mut tree, _source, _ended) = tree_dragging(eager_payload());
4343        tree.handle_drag_sample(Point::new(100.0, 50.0), &mut ops);
4344        assert!(tree.os_drag_pending.is_some());
4345        tree.abort_outbound_drag();
4346        assert!(tree.os_drag_pending.is_none());
4347        assert!(!super::outbound_is_live());
4348    }
4349
4350    #[test]
4351    fn an_inbound_drag_before_the_confirmation_is_the_native_drag_itself() {
4352        let mut ops = RecordingWindowOps::answering(pending());
4353        let (mut tree, source, _ended) = tree_dragging(eager_payload());
4354        tree.handle_drag_sample(Point::new(100.0, 50.0), &mut ops);
4355
4356        tree.begin_external_drag(
4357            Point::new(100.0, 50.0),
4358            crate::drag_payload::ExternalDropData::default(),
4359            &mut ops,
4360        );
4361        assert_eq!(tree.outbound_drag_source, Some(source), "handed over first");
4362        assert!(tree.os_drag_reentered, "then re-entered as our own drag");
4363        assert!(
4364            tree.active_drag
4365                .as_ref()
4366                .is_some_and(|d| d.payload.has_typed::<u32>()),
4367            "with the typed payload recovered"
4368        );
4369        tree.handle_os_drag_ended(crate::drag_payload::DropOutcome::Cancelled, &mut ops);
4370    }
4371
4372    /// The reported case: a file manager lying wholly inside the source window.
4373    /// The compositor sends this window `leave` while the pointer is still
4374    /// inside its rectangle, and that `Left` must park the payload again
4375    /// rather than end the drag, so the destination's drop completes it.
4376    #[test]
4377    fn a_leave_while_the_pointer_is_inside_the_window_keeps_the_os_drag_alive() {
4378        use crate::drag_payload::DropOutcome;
4379        let mut ops = RecordingWindowOps::new(true);
4380        let (mut tree, _source, ended) = tree_dragging(eager_payload());
4381        tree.handle_drag_sample(Point::new(100.0, 50.0), &mut ops);
4382        tree.begin_external_drag(
4383            Point::new(100.0, 50.0),
4384            crate::drag_payload::ExternalDropData::default(),
4385            &mut ops,
4386        );
4387        assert!(tree.os_drag_reentered);
4388
4389        tree.update_external_drag(Point::new(110.0, 50.0), &mut ops);
4390        tree.cancel_external_drag(&mut ops);
4391        assert!(!tree.os_drag_reentered);
4392        assert!(tree.active_drag.is_none());
4393        assert!(super::has_outbound_typed(), "payload parked again");
4394        assert!(ended.borrow().is_empty(), "the drag is not over");
4395
4396        tree.handle_os_drag_ended(DropOutcome::OsCopy, &mut ops);
4397        assert_eq!(*ended.borrow(), vec![DropOutcome::OsCopy]);
4398    }
4399
4400    #[test]
4401    fn an_eager_drag_dropped_back_on_its_own_window_reports_the_in_app_outcome() {
4402        use crate::drag_payload::DropOutcome;
4403        for accepts in [true, false] {
4404            let mut ops = RecordingWindowOps::new(true);
4405            let (mut tree, _source, ended) = tree_dragging(eager_payload());
4406            tree.add(FillWidget::new().on_drop(move |_, _, _| accepts));
4407            tree.layout(SizeProposal::exact(200.0, 100.0));
4408
4409            tree.handle_drag_sample(Point::new(150.0, 50.0), &mut ops);
4410            tree.begin_external_drag(
4411                Point::new(150.0, 50.0),
4412                crate::drag_payload::ExternalDropData::default(),
4413                &mut ops,
4414            );
4415            tree.end_external_drag(
4416                Point::new(150.0, 50.0),
4417                crate::drag_payload::ExternalDropData::default(),
4418                &mut ops,
4419            );
4420            assert!(
4421                ended.borrow().is_empty(),
4422                "the platform still has to end it"
4423            );
4424            // Every backend advertises copy only, so the platform says copy.
4425            tree.handle_os_drag_ended(DropOutcome::OsCopy, &mut ops);
4426            assert_eq!(
4427                *ended.borrow(),
4428                vec![DropOutcome::InApp { accepted: accepts }]
4429            );
4430        }
4431
4432        // A drag that came back and left again was not dropped here: the
4433        // platform's outcome stands.
4434        let mut ops = RecordingWindowOps::new(true);
4435        let (mut tree, _source, ended) = tree_dragging(eager_payload());
4436        tree.handle_drag_sample(Point::new(150.0, 50.0), &mut ops);
4437        tree.begin_external_drag(
4438            Point::new(150.0, 50.0),
4439            crate::drag_payload::ExternalDropData::default(),
4440            &mut ops,
4441        );
4442        tree.cancel_external_drag(&mut ops);
4443        tree.handle_os_drag_ended(DropOutcome::OsCopy, &mut ops);
4444        assert_eq!(*ended.borrow(), vec![DropOutcome::OsCopy]);
4445    }
4446
4447    #[test]
4448    fn an_eager_drag_asks_the_platform_once_however_often_it_comes_back() {
4449        let mut ops = RecordingWindowOps::new(true);
4450        let started = ops.started.clone();
4451        for round in 1..=2 {
4452            let (mut tree, _source, _ended) = tree_dragging(eager_payload());
4453            tree.handle_drag_sample(Point::new(100.0, 50.0), &mut ops);
4454            for _ in 0..2 {
4455                tree.begin_external_drag(
4456                    Point::new(100.0, 50.0),
4457                    crate::drag_payload::ExternalDropData::default(),
4458                    &mut ops,
4459                );
4460                tree.update_external_drag(Point::new(-5.0, 50.0), &mut ops);
4461                assert!(!tree.os_drag_reentered, "re-exited");
4462            }
4463            assert_eq!(started.borrow().len(), round, "one start per drag");
4464            tree.handle_os_drag_ended(crate::drag_payload::DropOutcome::Cancelled, &mut ops);
4465        }
4466    }
4467
4468    #[test]
4469    fn an_eager_finger_drag_tells_the_platform_it_is_a_finger_and_revokes_it() {
4470        let cancelled: Rc<RefCell<Vec<(crate::pointer::PointerId, crate::pointer::CancelReason)>>> =
4471            Rc::new(RefCell::new(Vec::new()));
4472        let c = cancelled.clone();
4473        let mut ops = RecordingWindowOps::answering(pending());
4474        let kinds = ops.started_kinds.clone();
4475
4476        let mut tree = WidgetTree::new();
4477        let slot: Rc<Cell<Option<WidgetId>>> = Rc::new(Cell::new(None));
4478        let source = tree.add(
4479            drag_arming_leaf(slot.clone(), eager_payload).on_pointer_cancel(
4480                move |pointer, reason, _ctx| {
4481                    c.borrow_mut().push((pointer.id, reason));
4482                },
4483            ),
4484        );
4485        slot.set(Some(source));
4486        tree.layout(SizeProposal::exact(200.0, 100.0));
4487        let contact = touch_press(&mut tree, Point::new(20.0, 50.0), &mut ops);
4488        assert!(tree.active_drag.is_some());
4489
4490        tree.dispatch_pointer_with_ops(
4491            crate::pointer::PointerSample {
4492                pointer: crate::pointer::PointerInfo::touch(
4493                    contact,
4494                    crate::pointer::EventTime::from_millis(30),
4495                ),
4496                phase: crate::pointer::PointerPhase::Move,
4497                position: Point::new(40.0, 50.0),
4498                button: None,
4499                modifiers: Modifiers::NONE,
4500                coalesced: Vec::new(),
4501            },
4502            &mut ops,
4503        );
4504        assert_eq!(*kinds.borrow(), vec![teksilo_tokens::PointerKind::Touch]);
4505        assert!(
4506            cancelled.borrow().is_empty(),
4507            "nothing revoked before the start"
4508        );
4509
4510        // The confirmation arrives from the platform, outside any sample.
4511        tree.confirm_os_drag(last_pending(&ops), &mut ops);
4512        assert_eq!(
4513            *cancelled.borrow(),
4514            vec![(contact, crate::pointer::CancelReason::OsDragStarted)]
4515        );
4516        tree.handle_os_drag_ended(crate::drag_payload::DropOutcome::Cancelled, &mut ops);
4517        tree.assert_no_leaked_pointer_state();
4518    }
4519
4520    /// A late start or end of a drag released before its start is not
4521    /// credited to the next drag, which is waiting for its own start.
4522    #[test]
4523    fn a_late_event_of_an_earlier_drag_does_not_touch_the_next_one() {
4524        use crate::drag_payload::DropOutcome;
4525        let mut ops = RecordingWindowOps::answering(pending());
4526        let cancels = ops.cancels.clone();
4527        let (mut tree, source, ended) = tree_dragging(eager_payload());
4528
4529        // Drag 1 asks, and is released before its start.
4530        tree.handle_drag_sample(Point::new(100.0, 50.0), &mut ops);
4531        let first = last_pending(&ops);
4532        tree.dispatch_event_with_ops(
4533            WidgetEvent::pointer_up(
4534                Point::new(100.0, 50.0),
4535                PointerButton::Primary,
4536                Modifiers::NONE,
4537            ),
4538            &mut ops,
4539        );
4540        assert_eq!(*ended.borrow(), vec![DropOutcome::Cancelled]);
4541        assert_eq!(cancels.get(), 1);
4542
4543        // Drag 2 asks.
4544        let mut ctx = crate::widget::EventContext::new();
4545        ctx.start_drag(source, eager_payload());
4546        tree.collect_from_ctx(ctx, source);
4547        tree.handle_drag_sample(Point::new(110.0, 50.0), &mut ops);
4548        let second = last_pending(&ops);
4549        assert_ne!(first, second);
4550
4551        // Drag 1's late events change nothing for drag 2.
4552        tree.confirm_os_drag(first, &mut ops);
4553        tree.handle_os_drag_ended_for(Some(first), DropOutcome::Cancelled, &mut ops);
4554        assert_eq!(tree.os_drag_pending, Some(second), "drag 2 still waits");
4555        assert!(tree.active_drag.is_some(), "with its in-app session");
4556        assert_eq!(cancels.get(), 1, "and its start is not cancelled");
4557        assert_eq!(ended.borrow().len(), 1);
4558
4559        // Drag 2's own events do.
4560        tree.confirm_os_drag(second, &mut ops);
4561        assert_eq!(tree.outbound_drag_source, Some(source));
4562        tree.handle_os_drag_ended_for(Some(first), DropOutcome::OsCopy, &mut ops);
4563        assert_eq!(ended.borrow().len(), 1, "a stale end does not end drag 2");
4564        tree.handle_os_drag_ended_for(Some(second), DropOutcome::OsCopy, &mut ops);
4565        assert_eq!(
4566            *ended.borrow(),
4567            vec![DropOutcome::Cancelled, DropOutcome::OsCopy]
4568        );
4569    }
4570
4571    /// X11: winit keeps its implicit grab through the XDND drag, so the
4572    /// window that handed its drag to the platform still gets the press's
4573    /// moves and release while the drag is re-entered over it. Those must not
4574    /// drive the re-entered session: the XDND drop does, once, and the source
4575    /// hears the in-app outcome.
4576    #[test]
4577    fn a_reentered_drag_ignores_the_windows_own_pointer_samples() {
4578        use crate::drag_payload::DropOutcome;
4579        let mut ops = RecordingWindowOps::new(true);
4580        let dropped = Rc::new(Cell::new(0_u32));
4581        let d = dropped.clone();
4582        let ended: Rc<RefCell<Vec<DropOutcome>>> = Rc::new(RefCell::new(Vec::new()));
4583        let e = ended.clone();
4584        let mut tree = WidgetTree::new();
4585        let slot: Rc<Cell<Option<WidgetId>>> = Rc::new(Cell::new(None));
4586        let row = tree.add(
4587            drag_arming_leaf(slot.clone(), eager_payload)
4588                .on_drop(move |_, _, _| {
4589                    d.set(d.get() + 1);
4590                    true
4591                })
4592                .on_drag_ended(move |o, _| e.borrow_mut().push(o)),
4593        );
4594        slot.set(Some(row));
4595        tree.layout(SizeProposal::exact(200.0, 100.0));
4596
4597        let at = Point::new(50.0, 50.0);
4598        tree.dispatch_event_with_ops(
4599            WidgetEvent::pointer_down(at, PointerButton::Primary, Modifiers::NONE),
4600            &mut ops,
4601        );
4602        tree.dispatch_event_with_ops(WidgetEvent::pointer_move(Point::new(60.0, 50.0)), &mut ops);
4603        assert_eq!(
4604            tree.outbound_drag_source,
4605            Some(row),
4606            "handed to the platform"
4607        );
4608
4609        // XDND brings the drag back over this window.
4610        tree.begin_external_drag(
4611            at,
4612            crate::drag_payload::ExternalDropData::default(),
4613            &mut ops,
4614        );
4615        assert!(tree.os_drag_reentered);
4616
4617        // winit's own samples of the grabbed press.
4618        tree.dispatch_event_with_ops(WidgetEvent::pointer_move(Point::new(70.0, 50.0)), &mut ops);
4619        tree.dispatch_event_with_ops(
4620            WidgetEvent::pointer_up(
4621                Point::new(70.0, 50.0),
4622                PointerButton::Primary,
4623                Modifiers::NONE,
4624            ),
4625            &mut ops,
4626        );
4627        assert_eq!(dropped.get(), 0, "the window's release is not the drop");
4628        assert!(
4629            tree.os_drag_reentered,
4630            "the re-entered session is still there"
4631        );
4632
4633        // The XDND drop completes it.
4634        tree.end_external_drag(
4635            Point::new(70.0, 50.0),
4636            crate::drag_payload::ExternalDropData::default(),
4637            &mut ops,
4638        );
4639        assert_eq!(dropped.get(), 1);
4640        tree.handle_os_drag_ended(DropOutcome::OsCopy, &mut ops);
4641        assert_eq!(*ended.borrow(), vec![DropOutcome::InApp { accepted: true }]);
4642        tree.assert_no_leaked_pointer_state();
4643    }
4644
4645    /// The window's own samples are kept from a re-entered session for the
4646    /// dragging pointer only: another pointer (a pen hovering) still reaches
4647    /// the widgets under it.
4648    #[test]
4649    fn a_reentered_drag_leaves_other_pointers_alone() {
4650        let mut ops = RecordingWindowOps::new(true);
4651        let hovered = Rc::new(Cell::new(0_u32));
4652        let h = hovered.clone();
4653        let mut tree = WidgetTree::new();
4654        let slot: Rc<Cell<Option<WidgetId>>> = Rc::new(Cell::new(None));
4655        let row = tree.add(drag_arming_leaf(slot.clone(), eager_payload).on_hover(
4656            move |entered, _| {
4657                if entered {
4658                    h.set(h.get() + 1);
4659                }
4660            },
4661        ));
4662        slot.set(Some(row));
4663        tree.layout(SizeProposal::exact(200.0, 100.0));
4664
4665        let at = Point::new(50.0, 50.0);
4666        tree.dispatch_event_with_ops(
4667            WidgetEvent::pointer_down(at, PointerButton::Primary, Modifiers::NONE),
4668            &mut ops,
4669        );
4670        tree.dispatch_event_with_ops(WidgetEvent::pointer_move(Point::new(60.0, 50.0)), &mut ops);
4671        tree.begin_external_drag(
4672            at,
4673            crate::drag_payload::ExternalDropData::default(),
4674            &mut ops,
4675        );
4676        assert!(tree.os_drag_reentered);
4677        let before = hovered.get();
4678
4679        tree.pen_hover(Point::new(70.0, 50.0));
4680        assert!(
4681            hovered.get() > before,
4682            "the pen's hover reaches the widget under it"
4683        );
4684        assert!(tree.os_drag_reentered, "and leaves the session alone");
4685        tree.handle_os_drag_ended(crate::drag_payload::DropOutcome::Cancelled, &mut ops);
4686    }
4687}