rust_widgets 2.9.2

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Drag-and-drop: a payload, a placement, and a target that decides whether to
//! accept one.
//!
//! # Why this module exists
//!
//! Twenty-eight files in this crate hand-roll the same gesture: a `MousePress`
//! records an origin, `MouseMove` updates an offset, and `MouseRelease` commits.
//! `dockwidget` drags a window, `splitter` drags a divider, `slider` and
//! `scrollbar` drag their thumbs, `bezier_curve_editor` drags control points,
//! `freeform_shape` drags vertices, `modal_bottom_sheet` drags itself closed, and
//! so on. Each implementation answers the same three questions on its own:
//! *what* is being moved, *where* it can land, and *what happens* when it does.
//!
//! This module answers them once. It is deliberately **not** a widget and produces
//! no `WidgetKind`: it is the shared vocabulary a control uses when it wants to be
//! a source or a destination.
//!
//! # What it does not do
//!
//! It does not deliver events. Which backend events constitute a drag is a control
//! decision (`Event::Drag` under `feature = "touch"`, or the mouse trio), so
//! [`DragSession`] is driven by whoever owns the gesture. That keeps the module
//! free of any assumption about input devices, which is what lets a mouse drag and
//! a touch drag share one state machine.
//!
//! # Example
//!
//! ```
//! use rust_widgets::core::Point;
//! use rust_widgets::event::{DragPayload, DragSession, DropEffect, DropTarget};
//!
//! // A concrete target that accepts cards and moves them on drop.
//! struct CardColumn;
//!
//! impl DropTarget for CardColumn {
//! fn can_accept(&self, payload: &DragPayload) -> bool {
//! payload.is_type("card")
//! }
//!
//! fn on_drop(&mut self, _payload: &DragPayload, _pos: Point) -> DropEffect {
//! DropEffect::Move
//! }
//! }
//!
//! // The source: serialise what is being moved and begin a session.
//! let payload = DragPayload::new("card", "task-42").with_label("Fix the parser");
//! let mut session = DragSession::begin(payload, Point::new(0, 0));
//! let mut target = CardColumn;
//!
//! // A drag becomes active once the pointer travels past the threshold.
//! session.update(Point::new(20, 20), 5);
//!
//! // `drop_on` returns a `DropEffect`, not an `Option`: `DropEffect::None` is a
//! // variant, and `is_accepted` answers "did the target take it?".
//! let effect = session.drop_on(&mut target, Point::new(20, 20));
//! if effect.is_accepted() {
//!     // The target took the payload. `effect` also says whether the source
//!     // should delete its copy (`DropEffect::Move`) or keep it.
//! }
//! assert_eq!(effect, DropEffect::Move);
//! ```

use crate::compat::String;
use crate::core::{ObjectId, Point};

/// What a drag carries.
///
/// # Why a type id and an opaque value rather than a generic parameter
///
/// A payload travels from a source the engine does not know to a target it also
/// does not know, through a single runtime list. A generic `DragPayload<T>` would
/// make the list heterogeneous — the same reason the event queue is not generic
/// over its contents. The `type_id` is the discriminator: a target compares it
/// against the id it expects, which is exactly the check a typed payload would
/// perform, only written down.
///
/// The derive is `PartialEq` without `Eq` because the payload carries a [`Point`],
/// whose fields are `i32`; loosening that to `Eq` would be a silent promise that
/// the geometry can never carry a float-like sentinel.
#[derive(Debug, Clone, PartialEq)]
pub struct DragPayload {
    /// The kind of thing being dragged, e.g. `"card"`, `"tab"`, `"file"`.
    ///
    /// This is the field a target filters on. It is a `String` rather than an enum
    /// because a library cannot enumerate its callers' domain vocabulary, and a
    /// target only ever compares it for equality.
    pub type_id: String,
    /// A stable identifier for the particular item, unique within `type_id`.
    ///
    /// Kept separate from `type_id` because a target usually accepts *some* items
    /// of a type and refuses others (a column with a WIP limit accepts a card but
    /// not when it is full) — and that decision needs to name the item.
    pub item_id: String,
    /// A human-readable label, for a drag preview or an accessibility announcement.
    pub label: String,
    /// The source's own coordinates of the drag origin, in the source's space.
    ///
    /// Carried so a target can describe a drop in the source's terms (\"after item
    /// 7 of this list\") without having to know which control started the drag.
    pub origin: Point,
    /// The control that began the drag, in the control's own id ([`crate::widget::Widget::id`]).
    ///
    /// # Why a target needs to know this
    ///
    /// A reorder and a transfer are the same gesture but not the same operation: dropping a row
    /// back onto the list it came from moves that row, while dropping it on *another* list inserts
    /// it and leaves the source to remove its copy. A target that could not tell the two apart
    /// would either duplicate the row or move an unrelated one, because an index is only
    /// meaningful inside the control that produced it.
    ///
    /// The runtime's coordinator fills this in when it begins a session, so a source does not have
    /// to set it.
    pub source: Option<ObjectId>,
    /// An optional control that travels with the item.
    ///
    /// Used when the item is not only data but also owns a widget: a tab's page, a card's body.
    /// A transfer to another container has to reparent that widget, and the payload is the only
    /// thing that crosses between the two controls, so the id travels with it. Targets that do not
    /// understand the field ignore it.
    pub attached: Option<ObjectId>,
}

impl DragPayload {
    /// Creates a payload with a type and an item id, and no label.
    pub fn new(type_id: impl Into<String>, item_id: impl Into<String>) -> Self {
        Self {
            type_id: type_id.into(),
            item_id: item_id.into(),
            label: String::new(),
            origin: Point::new(0, 0),
            source: None,
            attached: None,
        }
    }

    /// Attaches the control that is part of the item and must move with it.
    pub fn with_attached(mut self, attached: ObjectId) -> Self {
        self.attached = Some(attached);
        self
    }

    /// Sets the control that began the drag.
    ///
    /// Called by the runtime's drag coordinator, which is the only party that knows the control's
    /// own id while a payload is being built; a control building a payload for its own live pointer
    /// path leaves it unset.
    pub fn with_source(mut self, source: ObjectId) -> Self {
        self.source = Some(source);
        self
    }

    /// Returns whether this payload was taken from `source`.
    ///
    /// The comparison a drop target makes to tell a reorder from a transfer, named so every
    /// target spells it the same way.
    pub fn came_from(&self, source: ObjectId) -> bool {
        self.source == Some(source)
    }

    /// Sets the human-readable label.
    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.label = label.into();
        self
    }

    /// Sets the drag origin.
    pub fn with_origin(mut self, origin: Point) -> Self {
        self.origin = origin;
        self
    }

    /// Returns whether this payload is of `type_id`.
    ///
    /// The comparison a target makes, named so both sides spell it the same way.
    pub fn is_type(&self, type_id: &str) -> bool {
        self.type_id == type_id
    }
}

/// What a completed drop means for the source.
///
/// # Why `None` is a variant rather than an `Option` at the call site
///
/// A drop that was refused part-way through a gesture is a *result*, not the
/// absence of one: the caller has to restore the dragged item to where it was.
/// Modelling it as a variant keeps that branch in the same `match` as the others,
/// where the compiler can point out a forgotten arm — an `Option` around the enum
/// would make the restore path the `None` arm of a different type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DropEffect {
    /// The target agreed to nothing; the source must restore its state.
    #[default]
    None,
    /// The item was copied; the source keeps its original.
    Copy,
    /// The item was moved; the source should remove its original.
    Move,
    /// A link or reference was created; the source keeps its original.
    Link,
}

impl DropEffect {
    /// The effect's stable token, for a published event wire.
    ///
    /// The spelling is lower-case and stable because it is what a host's callback receives and
    /// what the generated event table publishes; it matches [`Self::parse`], so the two cannot
    /// drift into a spelling only one of them accepts.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Copy => "copy",
            Self::Move => "move",
            Self::Link => "link",
        }
    }

    /// Parses a token produced by [`Self::as_str`].
    ///
    /// `None` rather than a default, for the same reason the crate's other token parsers answer
    /// `None`: a token this version does not publish is a fact about a version mismatch, and
    /// folding it into `None` would claim the drop was refused.
    pub fn parse(token: &str) -> Option<Self> {
        match token {
            "none" => Some(Self::None),
            "copy" => Some(Self::Copy),
            "move" => Some(Self::Move),
            "link" => Some(Self::Link),
            _ => None,
        }
    }

    /// Returns whether the source should remove its original after this drop.
    ///
    /// Exposed because it is the one decision every source has to make from the
    /// effect, and encoding it as a match at each call site is how one of them ends
    /// up deleting a copy it should have kept.
    pub fn consumes_source(self) -> bool {
        matches!(self, DropEffect::Move)
    }

    /// Returns whether the drop was accepted at all.
    pub fn is_accepted(self) -> bool {
        !matches!(self, DropEffect::None)
    }
}

/// A control that can receive a dropped payload.
///
/// # Why three methods and not one
///
/// `can_accept` and `on_drop` are separate because the answer to \"may I take
/// this\" must be checkable **during** a drag, before any state changes — a drop
/// preview has to be drawn on every pointer move. Merging them would force the
/// target to either commit speculatively or keep the answer in a field beside the
/// question, which is the duplication this trait removes.
///
/// `preview_rect` is separate for the same reason: where a drop would land is not
/// where the target's own rectangle is (a list drops *between* rows), and a preview
/// drawn from the target's bounds would point at the wrong place.
pub trait DropTarget {
    /// Returns whether this target will accept `payload`.
    ///
    /// Must not mutate state: it is called on every pointer move to drive the
    /// preview. A target that refuses must return `false` rather than accept and
    /// then reject in [`Self::on_drop`], because the preview would have promised
    /// something the drop does not deliver.
    fn can_accept(&self, payload: &DragPayload) -> bool;

    /// Commits a drop of `payload` at `pos`, returning what the source should do.
    ///
    /// Called only after [`Self::can_accept`] returned `true` for the same payload,
    /// so an implementation may rely on that check having passed. Returning
    /// [`DropEffect::None`] is still meaningful: a target can discover during the
    /// commit that it cannot proceed (a pending async validation) and the source
    /// then restores.
    fn on_drop(&mut self, payload: &DragPayload, pos: Point) -> DropEffect;

    /// Returns the rectangle a drop of `payload` at `pos` would occupy, when the
    /// target can show a preview.
    ///
    /// `None` means \"no preview\", which is the honest default for a target that
    /// accepts a drop but has no meaningful landing zone to highlight.
    fn preview_rect(&self, payload: &DragPayload, pos: Point) -> Option<crate::core::Rect> {
        let _ = (payload, pos);
        None
    }

    /// Reports that `payload` is now over this target, or changed while over it.
    ///
    /// Called by the runtime's drag coordinator on pointer moves. A target that paints
    /// feedback overrides this; the default does nothing, which is right for a target
    /// whose landing zone is not visual. The target must not change the payload: this is
    /// a preview, and a refusal is expressed by returning `false` from
    /// [`Self::can_accept`], never by mutating state that pretends the drop happened.
    fn report_hover(&mut self, payload: &DragPayload) {
        let _ = payload;
    }

    /// Reports that the drag left this target without dropping.
    ///
    /// The counterpart of [`Self::report_hover`], so a preview is cleared when the
    /// pointer moves away instead of staying lit for a drop that will not happen. The
    /// default does nothing.
    fn report_leave(&mut self) {}
}

/// A control that can begin a cross-control drag.
///
/// # Why this is the mirror of [`DropTarget`]
///
/// A drag has two ends, and before this trait only the receiving end had a name. The
/// source answers two questions the coordinator cannot infer: *what* the pointer is
/// carrying at the press position, and *what to do* once the drop has been committed.
/// Keeping those on the source means a control that already knows its own selection
/// does not have to expose that selection to the runtime just to be draggable.
///
/// # Why both methods have a default
///
/// A control that is not draggable simply does not return itself as a source (see
/// [`crate::widget::Widget::drag_source_mut`]); the defaults make that case explicit
/// and let a source implement only the half it needs while it is being brought up.
/// Returning `None` from [`Self::drag_payload`] means \"this press starts no drag\",
/// which is the answer for a press outside the draggable part of the control.
pub trait DragSource {
    /// Returns the payload a drag beginning at `pos` would carry, or `None` when no
    /// drag should start there.
    ///
    /// Called once, on the press. `pos` is in the control's coordinate space (the same
    /// space its geometry uses), so a source can decide per-pixel — a list row, a
    /// selected run of text, or a tab under the pointer.
    fn drag_payload(&self, pos: Point) -> Option<DragPayload> {
        let _ = pos;
        None
    }

    /// Reports that the drag this source began has finished with `effect`.
    ///
    /// Called exactly once for a session that started from this source, including a
    /// cancelled session (`DropEffect::None`). A source that moves its item should
    /// keep it when `effect.consumes_source()` is `false`.
    fn on_drag_finished(&mut self, _effect: DropEffect) {}
}

/// The state of one in-progress drag.
///
/// # What this holds, and what it deliberately does not
///
/// It holds the payload, where the pointer is now, and where it started. It does
/// **not** hold the list of targets: a drag travels across controls that do not know
/// about each other, so resolving the target is the owner's job (it is the only party
/// that can see them all) — which is also why there is no "current target" field to
/// save.
///
/// That split is what lets a `KanbanBoard` drag a card onto a list that lives in a
/// different branch of the widget tree without either control importing the other.
#[derive(Debug, Clone)]
pub struct DragSession {
    payload: DragPayload,
    /// Where the gesture began, in the owning control's coordinates.
    start: Point,
    /// Where the pointer is now.
    current: Point,
    /// Whether the pointer has travelled far enough to count as a drag rather than
    /// a click.
    active: bool,
}

impl DragSession {
    /// Pointer travel, in logical pixels, after which a press becomes a drag.
    ///
    /// The session owns the number because the distinction between a click and a drag
    /// belongs to the gesture, not to each coordinator or control that drives one. A
    /// caller may still pass a different threshold to [`Self::update`] when a control
    /// has its own reason to be more or less eager.
    pub const ACTIVATION_THRESHOLD: i32 = 5;

    /// Begins a session with `payload` at `start`.
    ///
    /// The session starts **inactive**: a press is not yet a drag. Until the
    /// pointer travels past `threshold`, the gesture is still a candidate click, and
    /// treating it as a drag would cancel the click that a user expected.
    pub fn begin(payload: DragPayload, start: Point) -> Self {
        Self { payload, start, current: start, active: false }
    }

    /// The payload being dragged.
    pub fn payload(&self) -> &DragPayload {
        &self.payload
    }

    /// Where the gesture began.
    pub fn start(&self) -> Point {
        self.start
    }

    /// Where the pointer is now.
    pub fn current(&self) -> Point {
        self.current
    }

    /// Whether the pointer has travelled far enough to be a drag.
    pub fn is_active(&self) -> bool {
        self.active
    }

    /// The offset the pointer has travelled since the gesture began.
    ///
    /// Computed in `i64` and saturated to the `i32` range, so a gesture that moves
    /// between the extremes of a 32-bit axis reports a bounded delta rather than
    /// wrapping. The two coordinates come from `i32` fields, so a plain `x - start.x`
    /// was an overflow away from a panic in debug builds and a wrong sign in release.
    pub fn delta(&self) -> Point {
        Point::new(
            subtract_saturating(self.current.x, self.start.x),
            subtract_saturating(self.current.y, self.start.y),
        )
    }

    /// Moves the pointer to `pos`, activating the drag once `threshold` is
    /// exceeded in either axis.
    ///
    /// Returns whether the session became active on this move, so a caller can
    /// start drawing a preview exactly once rather than on every move.
    pub fn update(&mut self, pos: Point, threshold: i32) -> bool {
        self.current = pos;
        if self.active {
            return false;
        }
        // The distance is taken in `i64` before `abs`: `i32::abs` has no representable
        // result for `i32::MIN`, so `(pos.x - self.start.x).abs()` overflowed on exactly
        // the extreme coordinate this guards against.
        let dx = distance(pos.x, self.start.x);
        let dy = distance(pos.y, self.start.y);
        let threshold = i64::from(threshold);
        if dx >= threshold || dy >= threshold {
            self.active = true;
            return true;
        }
        false
    }

    /// Asks `target` whether it would accept this payload at `pos`.
    ///
    /// A convenience over `target.can_accept(session.payload())` that also refuses
    /// while the gesture is still a click — so a caller cannot forget that a
    /// not-yet-active drag must not highlight anything.
    pub fn target_accepts(&self, target: &dyn DropTarget) -> bool {
        self.active && target.can_accept(&self.payload)
    }

    /// Commits the drop on `target` at `pos`.
    ///
    /// Returns [`DropEffect::None`] when the gesture never became a drag, or when
    /// the target refuses — in both cases the source restores, which is the same
    /// outcome and needs no separate branch at the call site.
    pub fn drop_on(&mut self, target: &mut dyn DropTarget, pos: Point) -> DropEffect {
        if !self.active {
            return DropEffect::None;
        }
        if !target.can_accept(&self.payload) {
            return DropEffect::None;
        }
        target.on_drop(&self.payload, pos)
    }
}

/// The magnitude of `b - a` as an `i64`, well-defined for every `i32` input.
///
/// Subtracting in the wider type and negating there means neither the subtraction
/// nor the `abs` can overflow, unlike the same expression in `i32`.
fn distance(a: i32, b: i32) -> i64 {
    let diff = i64::from(a) - i64::from(b);
    if diff < 0 {
        -diff
    } else {
        diff
    }
}

/// `a - b` computed in `i64` and saturated to the `i32` range.
///
/// The result feeds a [`Point`], whose coordinates are `i32`, so the one value the
/// wide computation cannot represent is clamped to the nearer bound rather than
/// wrapping.
fn subtract_saturating(a: i32, b: i32) -> i32 {
    let diff = i64::from(a) - i64::from(b);
    diff.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::compat::{MiniToString, String, Vec};
    use crate::core::Rect;

    /// A target that accepts one payload type and records what it was given.
    #[derive(Default)]
    struct Recorder {
        dropped: Vec<String>,
        effect: DropEffect,
        preview: Option<Rect>,
    }

    impl DropTarget for Recorder {
        fn can_accept(&self, payload: &DragPayload) -> bool {
            payload.is_type("card")
        }

        fn on_drop(&mut self, payload: &DragPayload, _pos: Point) -> DropEffect {
            self.dropped.push(payload.item_id.clone());
            self.effect
        }

        fn preview_rect(&self, _payload: &DragPayload, _pos: Point) -> Option<Rect> {
            self.preview
        }
    }

    /// A target that refuses everything.
    #[derive(Default)]
    struct Refuser {
        drop_calls: usize,
    }

    impl DropTarget for Refuser {
        fn can_accept(&self, _payload: &DragPayload) -> bool {
            false
        }

        fn on_drop(&mut self, _payload: &DragPayload, _pos: Point) -> DropEffect {
            self.drop_calls += 1;
            DropEffect::Move
        }
    }

    fn card() -> DragPayload {
        DragPayload::new("card", "task-1").with_label("Fix the parser")
    }

    #[test]
    fn payload_type_filter_matches_only_its_own_id() {
        let payload = card();
        assert!(payload.is_type("card"));
        assert!(!payload.is_type("tab"));
        assert_eq!(payload.label, "Fix the parser");
    }

    #[test]
    fn payload_builder_sets_label_and_origin() {
        let payload = DragPayload::new("file", "/tmp/a").with_origin(Point::new(4, 5));
        assert_eq!(payload.origin, Point::new(4, 5));
        assert_eq!(payload.label, "");
    }

    #[test]
    fn a_press_below_threshold_is_not_yet_a_drag() {
        let mut session = DragSession::begin(card(), Point::new(10, 10));
        assert!(!session.is_active());
        // Four pixels of travel is a click with an unsteady hand.
        assert!(!session.update(Point::new(14, 12), 8));
        assert!(!session.is_active());
    }

    #[test]
    fn a_move_past_threshold_activates_the_drag_exactly_once() {
        let mut session = DragSession::begin(card(), Point::new(10, 10));
        assert!(session.update(Point::new(30, 10), 8), "the first crossing reports the change");
        assert!(session.is_active());
        // Later moves do not re-report, so a caller starts one preview.
        assert!(!session.update(Point::new(60, 10), 8));
        assert!(session.is_active());
    }

    #[test]
    fn a_threshold_refuser_is_never_asked_to_drop() {
        let mut session = DragSession::begin(card(), Point::new(0, 0));
        session.update(Point::new(50, 0), 8);
        let mut target = Refuser::default();

        // `target_accepts` gates the preview.
        assert!(!session.target_accepts(&target));

        // And the drop is refused without reaching the target's commit.
        assert_eq!(session.drop_on(&mut target, Point::new(50, 0)), DropEffect::None);
        assert_eq!(target.drop_calls, 0, "a refused payload must not reach on_drop");
    }

    #[test]
    fn an_inactive_session_never_drops() {
        let mut session = DragSession::begin(card(), Point::new(0, 0));
        let mut target = Recorder { effect: DropEffect::Move, ..Recorder::default() };
        // Never moved: still a click, so no drop may be committed even though the
        // target would have accepted.
        assert_eq!(session.drop_on(&mut target, Point::new(0, 0)), DropEffect::None);
        assert!(target.dropped.is_empty());
    }

    #[test]
    fn an_accepted_payload_reaches_the_commit() {
        let mut session = DragSession::begin(card(), Point::new(0, 0));
        session.update(Point::new(40, 0), 8);
        let mut target = Recorder { effect: DropEffect::Move, ..Recorder::default() };

        assert!(session.target_accepts(&target));
        assert_eq!(session.drop_on(&mut target, Point::new(40, 0)), DropEffect::Move);
        assert_eq!(target.dropped, vec!["task-1".to_string()]);
    }

    #[test]
    fn drop_effect_describes_what_the_source_should_do() {
        assert!(DropEffect::Move.consumes_source());
        assert!(!DropEffect::Copy.consumes_source());
        assert!(!DropEffect::Link.consumes_source());
        assert!(!DropEffect::None.consumes_source());

        assert!(DropEffect::Copy.is_accepted());
        assert!(DropEffect::Move.is_accepted());
        assert!(DropEffect::Link.is_accepted());
        assert!(!DropEffect::None.is_accepted());
    }

    #[test]
    fn default_effect_is_none_so_a_forgotten_field_restores() {
        // The default has to be the safe one: a target that forgets to set its
        // effect must not make the source delete its data.
        assert_eq!(DropEffect::default(), DropEffect::None);
        assert!(!DropEffect::default().consumes_source());
    }

    #[test]
    fn delta_tracks_the_pointer_offset() {
        let mut session = DragSession::begin(card(), Point::new(10, 20));
        session.update(Point::new(35, 5), 8);
        assert_eq!(session.delta(), Point::new(25, -15));
        assert_eq!(session.start(), Point::new(10, 20));
        assert_eq!(session.current(), Point::new(35, 5));
    }

    #[test]
    fn preview_rect_defaults_to_none() {
        // A target that accepts but offers no landing zone must say so, rather
        // than have the trait invent one from its own bounds.
        struct NoPreview;
        impl DropTarget for NoPreview {
            fn can_accept(&self, _payload: &DragPayload) -> bool {
                true
            }
            fn on_drop(&mut self, _payload: &DragPayload, _pos: Point) -> DropEffect {
                DropEffect::Copy
            }
        }
        let target = NoPreview;
        assert_eq!(target.preview_rect(&card(), Point::new(1, 1)), None);
    }

    #[test]
    fn preview_rect_is_reported_when_a_target_offers_one() {
        let target = Recorder { preview: Some(Rect::new(0, 10, 100, 4)), ..Recorder::default() };
        assert_eq!(target.preview_rect(&card(), Point::new(5, 5)), Some(Rect::new(0, 10, 100, 4)));
    }

    #[test]
    fn a_target_may_refuse_at_commit_time() {
        // A target can discover during the commit that it cannot proceed, and the
        // source then restores. This is a real case (async validation), not a
        // contradiction of `can_accept`.
        let mut session = DragSession::begin(card(), Point::new(0, 0));
        session.update(Point::new(40, 0), 8);
        let mut target = Recorder { effect: DropEffect::None, ..Recorder::default() };
        assert_eq!(session.drop_on(&mut target, Point::new(40, 0)), DropEffect::None);
        assert_eq!(target.dropped.len(), 1, "the target still saw the attempt");
    }

    #[test]
    fn vertical_travel_alone_activates_the_drag() {
        let mut session = DragSession::begin(card(), Point::new(0, 0));
        // A drag that never moves horizontally must still activate, which is what
        // makes column-to-column board dragging work.
        assert!(session.update(Point::new(2, 40), 8));
        assert!(session.is_active());
    }

    /// A drag spanning the full axis must not overflow, and its delta is saturated.
    ///
    /// `delta()` used i32 subtraction and `update()` used `i32::abs`; both overflow at
    /// the extremes (`i32::MAX - i32::MIN`, and `abs(i32::MIN)`). This pins the wide
    /// arithmetic that makes every input well-defined.
    #[test]
    fn axis_extremes_do_not_overflow() {
        let mut session = DragSession::begin(card(), Point::new(i32::MIN, i32::MIN));
        assert!(session.update(Point::new(i32::MAX, i32::MAX), 8), "full-axis travel is a drag");
        assert!(session.is_active());
        // The delta cannot be represented in i32, so it saturates to the axis bounds.
        assert_eq!(session.delta(), Point::new(i32::MAX, i32::MAX));
    }

    /// A move to `i32::MIN` from the origin must compute a positive distance.
    #[test]
    fn move_to_i32_min_activates_without_abs_overflow() {
        let mut session = DragSession::begin(card(), Point::new(0, 0));
        assert!(
            session.update(Point::new(i32::MIN, 0), 8),
            "moving to i32::MIN is far past the threshold, not a wrapped negative"
        );
        assert_eq!(session.delta(), Point::new(i32::MIN, 0));
    }

    /// Normal drags keep their exact offset after the wide-arithmetic change.
    #[test]
    fn normal_drags_keep_their_exact_delta() {
        let mut session = DragSession::begin(card(), Point::new(-100, 250));
        session.update(Point::new(150, -50), 8);
        assert_eq!(session.delta(), Point::new(250, -300));
    }

    /// A negative-to-positive small drag is not falsely saturated.
    #[test]
    fn ordinary_small_offsets_are_not_saturated() {
        let session = DragSession::begin(card(), Point::new(-1, 1));
        assert_eq!(session.delta(), Point::new(0, 0));
        let mut session = session;
        session.update(Point::new(1, -1), 3);
        assert_eq!(session.delta(), Point::new(2, -2));
    }
}