Skip to main content

waft_winui/controls/tree_view/
drag.rs

1//! TreeViewList.cpp's drag and drop of nodes, with what it relies on in ListViewBase
2//! (ListViewBase_Partial_Reorder.cpp), ListViewBaseItem_Partial.cpp, TreeViewItem.cpp and
3//! LiveReorderHelper.cpp. Waft's `Draggable` carries the drag from a row, and a `DragTarget`
4//! over the list receives it.
5//!
6//! The drag reaches the tree's elements as the source's drag events do:
7//! - The row drawn under the pointer has DragEnter, DragOver and DragLeave first, which
8//!   TreeViewItem handles: a row accepts a drag of nodes it is not under, and a collapsed row
9//!   with children hovered for a second expands. Over the middle three fifths of a row,
10//!   ListViewBaseItem takes the drag there: the row looks pointed at.
11//! - Elsewhere the list has the drag: TreeViewList finds the empty slot the nodes would move to,
12//!   and ListViewBase opens a gap there after 200 ms and scrolls near the list's edges.
13//! - The drop goes where the last drag over did: into the row under the pointer when that row
14//!   accepted the drag, else, over no row, as in the gap, to the empty slot.
15
16use super::item::{ItemDrag, PressedPart};
17use super::view_model::MovePlan;
18use super::{TreeViewSelectionMode, TreeViewState};
19use crate::*;
20use std::{cell::Cell, rc::Rc, time::Duration};
21use waft_embedder::{Offset, Rect};
22use waft_foundation::{App, Handle, Listener, OptionRetained, Timer};
23use waft_gestures::{GestureMultiDragStartCallback, MultiDragRecognizerRef};
24use waft_widgets::*;
25
26/// XAML `DataPackageOperation`, as a drag within the tree ends.
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
28pub enum DataPackageOperation {
29    /// The drop moved nothing, or the drag ended outside the tree.
30    #[default]
31    None,
32    /// The drop moved the nodes.
33    Move,
34}
35
36/// XAML `TreeViewDragItemsStartingEventArgs`.
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct TreeViewDragItemsStartingEventArgs {
39    /// `Items`: the node the drag starts on, or in Multiple mode with several nodes selected,
40    /// `SelectedNodes`. `DragItemsCompleted` reports them again.
41    pub items: Vec<String>,
42
43    /// `Cancel`: set it to keep the drag from starting.
44    pub cancel: bool,
45}
46
47/// XAML `TreeViewDragItemsCompletedEventArgs`.
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub struct TreeViewDragItemsCompletedEventArgs {
50    /// `DropResult`.
51    pub drop_result: DataPackageOperation,
52
53    /// `Items`, as `DragItemsStarting` left them.
54    pub items: Vec<String>,
55
56    /// `NewParentItem`: the parent of the first of `items` after the drop; `None` for a root
57    /// node.
58    pub new_parent_item: Option<String>,
59}
60
61/// `LISTVIEWITEM_DRAGOVER_OUTSIDE_MARGIN`: the share of a row at each end outside its middle,
62/// where the list has the drag.
63const DRAG_OVER_OUTSIDE_MARGIN: f64 = 0.2;
64
65/// `LISTVIEW_LIVEREORDER_TIMER`: how long the drag stays at a slot before the gap opens.
66const LIVE_REORDER_DELAY: Duration = Duration::from_millis(200);
67
68/// `c_dragOverInterval`: how long a drag hovers a collapsed row before it expands.
69const DRAG_OVER_EXPAND_DELAY: Duration = Duration::from_secs(1);
70
71/// `LISTVIEWBASE_EDGE_SCROLL_EDGE_WIDTH_PX`, `_MIN_SPEED`, `_MAX_SPEED` and
72/// `_START_DELAY_MSEC`: edge scrolling, in pixels and pixels per second.
73const EDGE_SCROLL_EDGE_WIDTH: f64 = 100.0;
74const EDGE_SCROLL_MIN_SPEED: f64 = 150.0;
75const EDGE_SCROLL_MAX_SPEED: f64 = 1500.0;
76const EDGE_SCROLL_START_DELAY: Duration = Duration::from_millis(50);
77
78/// `ScrollViewerScrollRoundingTolerance`.
79const SCROLL_ROUNDING_TOLERANCE: f64 = 0.05;
80
81/// What Waft's drag carries from a row.
82#[derive(Clone, Debug)]
83pub(super) struct TreeDragData {
84    /// The tree the drag started in.
85    source: Handle<TreeViewState>,
86    /// The node the drag started on.
87    id: String,
88    /// Where the pointer is on the preview, which turns the preview's place into the pointer's.
89    anchor: Rc<Cell<Offset>>,
90}
91
92/// The drag state of TreeViewList and the ListViewBase under it.
93#[derive(Default)]
94pub(super) struct TreeDragState {
95    /// `m_tpPrimaryDraggedContainer`: the node the drag started on, while the list is in it.
96    primary: Option<String>,
97    /// `m_draggedTreeViewNode`, which TreeViewList's `DragItemsStarting` handler sets.
98    dragged: Option<String>,
99    /// The drag's items, as `DragItemsStarting` left them.
100    items: Vec<String>,
101    /// `TreeViewItemTemplateSettings.DragItemsCount` of a drag of several selected nodes, in
102    /// `MultipleDraggingPrimary`.
103    multiple: Option<usize>,
104    /// `m_isDraggingOverSelf`.
105    over_self: bool,
106    /// The row the last drag over reached: `m_dragEnterDO`.
107    entered: Option<String>,
108    /// `m_tpDragOverItem`: the row whose middle the drag is over.
109    drag_over_item: Option<String>,
110    /// The accepted operation, carried from one drag event to the next: Move when true.
111    accepted: bool,
112    /// `m_emptySlotIndex`.
113    empty_slot: Option<usize>,
114    /// `m_liveReorderIndices.draggedOverIndex`.
115    live_index: Option<usize>,
116    /// The drag-over index whose gap shows: `m_movedItems`.
117    live_shown: Option<usize>,
118    /// `m_tpLiveReorderTimer`.
119    live_timer: Option<Timer>,
120    /// TreeViewItem's `m_expandContentTimer`, of the entered row.
121    expand_timer: Option<Timer>,
122    /// Where the pointer last was, in global coordinates.
123    position: Option<Offset>,
124    /// `m_currentAutoPanVelocity`: pixels per second toward the start of the list.
125    velocity: f64,
126    /// `m_pendingAutoPanVelocity`.
127    pending_velocity: f64,
128    /// `m_tpStartEdgeScrollTimer`.
129    edge_timer: Option<Timer>,
130    /// The edge scroll's last frame.
131    last_tick: Option<Duration>,
132    /// The drop's accepted operation.
133    result: DataPackageOperation,
134}
135
136/// `GetDragOverIndex`: the row whose slot the gap takes, which moves past a row only once the
137/// drag is past the row's middle.
138fn drag_over_index(closest: usize, insertion: usize, previous: usize) -> usize {
139    if insertion == closest {
140        if previous < insertion {
141            closest - 1
142        } else {
143            closest
144        }
145    } else if previous >= insertion {
146        closest + 1
147    } else {
148        closest
149    }
150}
151
152/// `ComputeEdgeScrollVelocityFromEdgeDistance`.
153fn edge_scroll_speed(distance: f64) -> f64 {
154    if distance <= EDGE_SCROLL_EDGE_WIDTH {
155        EDGE_SCROLL_MAX_SPEED
156            - distance / EDGE_SCROLL_EDGE_WIDTH * (EDGE_SCROLL_MAX_SPEED - EDGE_SCROLL_MIN_SPEED)
157    } else {
158        0.0
159    }
160}
161
162/// Whether `y` is in the middle of `rect`, outside `DRAG_OVER_OUTSIDE_MARGIN` at either end:
163/// `ListViewBaseItem::IsDragOver`.
164fn is_drag_over(rect: Rect, y: f64) -> bool {
165    let location = y - rect.top;
166    let size = rect.height();
167    location > DRAG_OVER_OUTSIDE_MARGIN * size && location < (1.0 - DRAG_OVER_OUTSIDE_MARGIN) * size
168}
169
170/// The draggable around a row, whose start TreeViewList can decline.
171#[derive(Clone, Debug)]
172struct TreeViewItemDraggable {
173    draggable: Draggable<TreeDragData>,
174}
175
176impl DraggableWidget for TreeViewItemDraggable {
177    type Data = TreeDragData;
178
179    fn draggable(&self) -> &Draggable<TreeDragData> {
180        &self.draggable
181    }
182
183    fn create_recognizer(
184        &self,
185        app: &mut App,
186        on_start: GestureMultiDragStartCallback,
187    ) -> MultiDragRecognizerRef {
188        let data = self.draggable.data.clone().expect("a row's drag data");
189        self.draggable.create_recognizer(
190            app,
191            Rc::new(move |app, position| {
192                if !data.source.alive(app) || !data.source.start_drag(app, &data.id) {
193                    return None;
194                }
195                on_start(app, position)
196            }),
197        )
198    }
199}
200
201impl StatefulWidget for TreeViewItemDraggable {
202    type State = DraggableState<Self>;
203
204    fn create_state(&self) -> Self::State {
205        DraggableState::new()
206    }
207}
208
209impl TreeViewState {
210    /// `IsInDragDrop`: a drag started on one of the rows.
211    pub(super) fn is_in_drag(self: Handle<Self>, app: &App) -> bool {
212        app.get(self).drag.primary.is_some()
213    }
214
215    /// What the drag means for the row of `id`; for the drag preview, the row as the drag
216    /// visual takes it, before it becomes a placeholder.
217    pub(super) fn item_drag(self: Handle<Self>, app: &App, id: &str, preview: bool) -> ItemDrag {
218        let drag = &app.get(self).drag;
219        let primary = drag.primary.as_deref() == Some(id);
220        ItemDrag {
221            in_drag: drag.primary.is_some(),
222            primary,
223            captured: !preview,
224            dragged_over: !preview && drag.drag_over_item.as_deref() == Some(id),
225            can_reorder: self.widget(app).can_reorder_items,
226            drag_items_count: drag.items.len(),
227            multiple_dragging_primary: primary && drag.multiple.is_some(),
228            drag_items_count_display: drag.multiple.unwrap_or(0),
229        }
230    }
231
232    /// How far the gap of a live reorder moves the row at `row`: each row between the dragged
233    /// one and the drag-over index takes its neighbour's slot toward the dragged one.
234    fn displacement(self: Handle<Self>, app: &App, row: usize) -> f64 {
235        let state = app.get(self);
236        let (Some(primary), Some(shown)) = (&state.drag.primary, state.drag.live_shown) else {
237            return 0.0;
238        };
239        let Some(dragged) = state.rows.index_of(primary) else {
240            return 0.0;
241        };
242        if dragged < row && row <= shown {
243            -self.row_height(app, state.rows.get(row - 1).unwrap())
244        } else if shown <= row && row < dragged {
245            self.row_height(app, state.rows.get(row).unwrap())
246        } else {
247            0.0
248        }
249    }
250
251    /// The row at `row` as the list draws it: displaced by a live reorder, and draggable while
252    /// the tree can drag or reorder.
253    pub(super) fn drag_source(
254        self: Handle<Self>,
255        app: &mut App,
256        id: &str,
257        row: usize,
258        container: super::item::TreeViewItemContainer,
259    ) -> WidgetRef {
260        let displaced = Transform::translate(Offset::new(0.0, self.displacement(app, row)))
261            .child(container)
262            .into_widget();
263        let widget = self.widget(app).clone();
264        if !widget.is_enabled || !(widget.can_drag_items || widget.can_reorder_items) {
265            return displaced;
266        }
267        let anchor = Rc::new(Cell::new(Offset::ZERO));
268        let data = TreeDragData {
269            source: self,
270            id: id.to_owned(),
271            anchor: anchor.clone(),
272        };
273        let resources = ThemeResources::of(app, self.context(app));
274        let preview = id.to_owned();
275        // The preview is a widget of its own, in the overlay, where the tree's theme does not
276        // reach.
277        let feedback = ThemeScope::with_resources(
278            resources,
279            Builder::new(move |app, _| self.drag_preview(app, &preview)),
280        );
281        let draggable = Draggable::new(displaced, feedback)
282            .data(data)
283            .max_simultaneous_drags(1)
284            .drag_anchor_strategy(Rc::new(move |app, draggable, context, position| {
285                let offset = child_drag_anchor_strategy(app, draggable, context, position);
286                anchor.set(offset);
287                offset
288            }))
289            .on_drag_completed(Listener::new(move |app| self.drag_ended(app, true)))
290            .on_draggable_canceled(Rc::new(move |app, _, _| self.drag_ended(app, false)));
291        TreeViewItemDraggable { draggable }.into_widget()
292    }
293
294    /// The drag visual: the row as it was when the drag started, at its width.
295    fn drag_preview(self: Handle<Self>, app: &mut App, id: &str) -> WidgetRef {
296        if !self.alive(app) || !app.get(self).tree.contains(id) {
297            return SizedBox::shrink().into_widget();
298        }
299        let width = app.get(self).widths.get(id).copied().unwrap_or(0.0);
300        let container = self.container(app, id, None);
301        SizedBox::new().width(width).child(container).into_widget()
302    }
303
304    /// `ListViewBase::OnDragGesture` for a drag starting on the row of `id`, with TreeViewList's
305    /// `OnDragItemsStarting` and TreeView's `DragItemsStarting`: whether the drag starts.
306    fn start_drag(self: Handle<Self>, app: &mut App, id: &str) -> bool {
307        let widget = self.widget(app).clone();
308        if self.is_in_drag(app)
309            || !widget.is_enabled
310            || !(widget.can_drag_items || widget.can_reorder_items)
311            || self.pressed_part_is(app, id, PressedPart::Chevron)
312            || self.pressed_part_is(app, id, PressedPart::CheckBox)
313            || app.get(self).rows.index_of(id).is_none()
314        {
315            return false;
316        }
317        let mut items = vec![id.to_owned()];
318        // `DragItemsStarting` is raised only for a tree that can drag items.
319        if widget.can_drag_items {
320            app.get_mut(self).drag.dragged = Some(id.to_owned());
321            if self.is_multi_select_with_selected_items(app) {
322                let selected = self.selected_nodes(app);
323                if selected.len() > 1 {
324                    app.get_mut(self).drag.multiple = Some(selected.len());
325                    items = selected;
326                }
327            } else {
328                // Outside a selection of several, the dragged node collapses.
329                self.set_node_expanded(app, id, false);
330            }
331            let mut args = TreeViewDragItemsStartingEventArgs {
332                items,
333                cancel: false,
334            };
335            if let Some(handler) = widget.drag_items_starting.clone() {
336                handler(app, &mut args);
337            }
338            if args.cancel || !self.alive(app) {
339                let drag = &mut app.get_mut(self).drag;
340                drag.dragged = None;
341                drag.multiple = None;
342                return false;
343            }
344            items = args.items;
345        }
346        let drag = &mut app.get_mut(self).drag;
347        drag.primary = Some(id.to_owned());
348        drag.items = items;
349        drag.over_self = false;
350        drag.accepted = false;
351        drag.result = DataPackageOperation::None;
352        self.set_state(app, |_| {});
353        true
354    }
355
356    /// The drag ended: dropped on the list, or released elsewhere. `CompleteDrop` ends the
357    /// list's drag, then `DragItemsCompleted` is raised for a tree that can drag items, after
358    /// TreeViewList forgets the dragged node.
359    fn drag_ended(self: Handle<Self>, app: &mut App, dropped: bool) {
360        if !self.alive(app) || !self.is_in_drag(app) {
361            return;
362        }
363        let result = if dropped {
364            app.get(self).drag.result
365        } else {
366            DataPackageOperation::None
367        };
368        self.clear_drag_over(app);
369        let drag = std::mem::take(&mut app.get_mut(self).drag);
370        let widget = self.widget(app).clone();
371        if widget.can_drag_items
372            && let Some(handler) = widget.drag_items_completed
373        {
374            let tree = app.get(self).tree.clone();
375            let new_parent_item = drag
376                .items
377                .first()
378                .filter(|id| tree.contains(id))
379                .and_then(|id| tree.parent(id).map(str::to_owned));
380            handler(
381                app,
382                TreeViewDragItemsCompletedEventArgs {
383                    drop_result: result,
384                    items: drag.items,
385                    new_parent_item,
386                },
387            );
388        }
389        self.set_state(app, |_| {});
390    }
391
392    /// The list as the drag's target.
393    pub(super) fn drop_target(self: Handle<Self>, _app: &mut App, child: WidgetRef) -> WidgetRef {
394        DragTarget::<TreeDragData>::new(move |_, _, _, _| child.clone())
395            .on_will_accept_with_details(Rc::new(move |app, details| {
396                self.drag_entered(app, &details.data)
397            }))
398            .on_move(Rc::new(move |app, details| {
399                if details.data.source == self && self.alive(app) {
400                    let position = details.offset + details.data.anchor.get();
401                    self.drag_over(app, position);
402                }
403            }))
404            .on_leave(Rc::new(move |app, data| {
405                if data.is_some_and(|data| data.source == self) && self.alive(app) {
406                    self.drag_left(app);
407                }
408            }))
409            .on_accept_with_details(Rc::new(move |app, details| {
410                if details.data.source == self && self.alive(app) {
411                    let position = details.offset + details.data.anchor.get();
412                    self.drop(app, position);
413                }
414            }))
415            .into_widget()
416    }
417
418    /// The drag entered the list: `ListViewBase::OnDragEnter` where the list allows drops. The
419    /// tree takes only drags of its own rows.
420    fn drag_entered(self: Handle<Self>, app: &mut App, data: &TreeDragData) -> bool {
421        if data.source != self || !self.alive(app) {
422            return false;
423        }
424        if self.widget(app).allow_drop {
425            let drag = &mut app.get_mut(self).drag;
426            drag.over_self = drag.primary.is_some();
427        }
428        true
429    }
430
431    /// The drag left the list: the entered row's DragLeave, `TreeViewList::OnDragLeave` and
432    /// `ListViewBase::OnDragLeave`.
433    fn drag_left(self: Handle<Self>, app: &mut App) {
434        if let Some(entered) = app.get_mut(self).drag.entered.take() {
435            self.row_drag_left(app, &entered);
436        }
437        let drag = &mut app.get_mut(self).drag;
438        // No element that accepted the drag is under it any more.
439        drag.accepted = false;
440        drag.empty_slot = None;
441        drag.position = None;
442        if self.widget(app).allow_drop {
443            self.set_pending_velocity(app, 0.0);
444            self.reset_live_reorder(app);
445            app.get_mut(self).drag.over_self = false;
446        }
447        self.set_state(app, |_| {});
448    }
449
450    /// One drag over at `position`: the row drawn there has it first, then the list where the
451    /// row leaves it.
452    fn drag_over(self: Handle<Self>, app: &mut App, position: Offset) {
453        if !self.is_in_drag(app) {
454            return;
455        }
456        app.get_mut(self).drag.position = Some(position);
457        let hit = self.row_drawn_at(app, position);
458        let hit_id = hit.as_ref().map(|(_, id, _)| id.clone());
459        if hit_id != app.get(self).drag.entered {
460            if let Some(entered) = app.get_mut(self).drag.entered.take() {
461                self.row_drag_left(app, &entered);
462            }
463            app.get_mut(self).drag.entered = hit_id.clone();
464            if let Some(id) = &hit_id {
465                self.row_drag_entered(app, id);
466            }
467        }
468        let mut handled = false;
469        if let Some((_, id, rect)) = hit {
470            self.row_drag_over(app, &id);
471            // `ListViewBaseItem::OnDragOver`: the middle of the row takes the drag.
472            handled = is_drag_over(rect, position.dy());
473            app.get_mut(self).drag.drag_over_item = handled.then_some(id);
474        }
475        if !handled && self.widget(app).allow_drop {
476            self.list_drag_over(app, position);
477        }
478        self.set_state(app, |_| {});
479    }
480
481    /// `TreeViewItem::OnDragEnter`: the row accepts a drag of nodes it is not within, and a
482    /// collapsed row with children other than the dragged one starts its expand timer.
483    fn row_drag_entered(self: Handle<Self>, app: &mut App, id: &str) {
484        app.get_mut(self).drag.accepted = false;
485        let Some(dragged) = app.get(self).drag.dragged.clone() else {
486            return;
487        };
488        if !self.widget(app).can_reorder_items {
489            return;
490        }
491        let tree = app.get(self).tree.clone();
492        if !tree.is_within(id, &dragged) {
493            app.get_mut(self).drag.accepted = true;
494        }
495        if id != dragged && !tree.is_expanded(id) && tree.has_children(id) {
496            if let Some(timer) = app.get_mut(self).drag.expand_timer.take() {
497                timer.cancel(app);
498            }
499            let row = id.to_owned();
500            let timer = Timer::new(
501                app,
502                DRAG_OVER_EXPAND_DELAY,
503                Listener::new(move |app| {
504                    if self.alive(app) {
505                        self.expand_on_hover(app, &row);
506                    }
507                }),
508            );
509            app.get_mut(self).drag.expand_timer = Some(timer);
510        }
511    }
512
513    /// `TreeViewItem::OnExpandContentTimerTick`: the hovered row expands, and the drag goes over
514    /// what is now under it.
515    fn expand_on_hover(self: Handle<Self>, app: &mut App, id: &str) {
516        app.get_mut(self).drag.expand_timer = None;
517        if !app.get(self).tree.contains(id) || app.get(self).tree.is_expanded(id) {
518            return;
519        }
520        self.set_node_expanded(app, id, true);
521        if let Some(position) = app.get(self).drag.position {
522            self.drag_over(app, position);
523        }
524    }
525
526    /// The row's DragLeave: TreeViewItem stops its expand timer and ListViewBaseItem stops being
527    /// dragged over.
528    fn row_drag_left(self: Handle<Self>, app: &mut App, _id: &str) {
529        if let Some(timer) = app.get_mut(self).drag.expand_timer.take() {
530            timer.cancel(app);
531        }
532        app.get_mut(self).drag.drag_over_item = None;
533    }
534
535    /// `TreeViewItem::OnDragOver`: in Multiple mode with a selection, the row accepts unless it
536    /// is selected; otherwise it accepts a drag of nodes it is not within, and leaves the
537    /// operation as it was for one it is.
538    fn row_drag_over(self: Handle<Self>, app: &mut App, id: &str) {
539        let Some(dragged) = app.get(self).drag.dragged.clone() else {
540            return;
541        };
542        if !self.widget(app).can_reorder_items {
543            return;
544        }
545        if self.is_multi_select_with_selected_items(app) {
546            app.get_mut(self).drag.accepted = !self.is_node_selected(app, id);
547        } else if !app.get(self).tree.is_within(id, &dragged) {
548            app.get_mut(self).drag.accepted = true;
549        }
550    }
551
552    /// `TreeViewList::OnDragOver`, then `ListViewBase::OnDragOver` when TreeViewList leaves it.
553    fn list_drag_over(self: Handle<Self>, app: &mut App, position: Offset) {
554        let widget = self.widget(app).clone();
555        app.get_mut(self).drag.accepted = false;
556        if app.get(self).drag.dragged.is_some() && widget.can_reorder_items {
557            let slot = self.empty_slot(app, position);
558            let rows = app.get(self).rows.clone();
559            let allow = match slot.and_then(|slot| rows.get(slot)) {
560                // A drop beside a selected node would move it among itself.
561                Some(insert_at) if widget.selection_mode == TreeViewSelectionMode::Multiple => {
562                    !self.is_node_selected(app, insert_at)
563                }
564                Some(_) => true,
565                None => false,
566            };
567            let drag = &mut app.get_mut(self).drag;
568            if allow {
569                drag.empty_slot = slot;
570                drag.accepted = true;
571            } else {
572                // Refused, and handled: ListViewBase neither reorders nor scrolls.
573                drag.empty_slot = None;
574                return;
575            }
576        }
577        self.process_live_reorder(app, position);
578        // `DropCausesReorder`.
579        let drag = &app.get(self).drag;
580        if drag.over_self && widget.allow_drop && widget.can_reorder_items {
581            app.get_mut(self).drag.accepted = true;
582        }
583        let velocity = self.edge_scroll_velocity(app, position);
584        self.set_pending_velocity(app, velocity);
585    }
586
587    /// TreeViewList's empty slot: the row index the dragged node would take, from
588    /// `GetInsertionIndexes` and which half of the row beside the insertion the pointer is in.
589    fn empty_slot(self: Handle<Self>, app: &mut App, position: Offset) -> Option<usize> {
590        let size = app.get(self).rows.len();
591        let below = self.insertion_index(app, position)?;
592        if below > size.checked_sub(1)? {
593            return Some(size - 1);
594        }
595        if below == 0 {
596            return Some(0);
597        }
598        let dragged = app.get(self).drag.dragged.clone()?;
599        let dragged_row = app.get(self).rows.index_of(&dragged)?;
600        let row = if dragged_row < below {
601            below
602        } else {
603            below - 1
604        };
605        let rect = self.row_drawn_rect(app, row)?;
606        Some(if position.dy() - rect.top < rect.height() / 2.0 {
607            below - 1
608        } else {
609            below
610        })
611    }
612
613    /// `ProcessDragOverAt`'s live reorder: the drag-over index follows the pointer, and the gap
614    /// moves to it once it has stayed for `LIVE_REORDER_DELAY`.
615    fn process_live_reorder(self: Handle<Self>, app: &mut App, position: Offset) {
616        let widget = self.widget(app).clone();
617        let drag = &app.get(self).drag;
618        // `ShouldPlayLiveReorder`: not while the list edge-scrolls.
619        if !widget.can_reorder_items || !widget.allow_drop || drag.velocity != 0.0 {
620            return;
621        }
622        let Some(primary) = drag.primary.clone() else {
623            return;
624        };
625        let count = app.get(self).rows.len();
626        let Some(dragged) = app.get(self).rows.index_of(&primary) else {
627            return;
628        };
629        let (Some(closest), Some(insertion)) = (
630            self.closest_row(app, position),
631            self.insertion_index(app, position),
632        ) else {
633            return;
634        };
635        let previous = app.get(self).drag.live_index.unwrap_or(dragged);
636        let index = if insertion == count {
637            count
638        } else {
639            drag_over_index(closest, insertion, previous)
640        };
641        app.get_mut(self).drag.live_index = Some(index);
642        if previous == dragged || previous != index {
643            if let Some(timer) = app.get_mut(self).drag.live_timer.take() {
644                timer.cancel(app);
645            }
646            let timer = Timer::new(
647                app,
648                LIVE_REORDER_DELAY,
649                Listener::new(move |app| {
650                    if self.alive(app) && self.is_in_drag(app) {
651                        self.show_live_reorder(app);
652                    }
653                }),
654            );
655            app.get_mut(self).drag.live_timer = Some(timer);
656        }
657    }
658
659    /// `LiveReorderTimerTickHandler`: the gap moves to the drag-over index. The drag then goes
660    /// over what the gap put under the pointer, as the system's next drag over would.
661    fn show_live_reorder(self: Handle<Self>, app: &mut App) {
662        let drag = &mut app.get_mut(self).drag;
663        drag.live_timer = None;
664        drag.live_shown = drag.live_index;
665        let position = drag.position;
666        self.set_state(app, |_| {});
667        if let Some(position) = position {
668            self.drag_over(app, position);
669        }
670    }
671
672    /// `ResetAllItemsForLiveReorder`.
673    fn reset_live_reorder(self: Handle<Self>, app: &mut App) {
674        if let Some(timer) = app.get_mut(self).drag.live_timer.take() {
675            timer.cancel(app);
676        }
677        let drag = &mut app.get_mut(self).drag;
678        drag.live_index = None;
679        drag.live_shown = None;
680    }
681
682    /// `ComputeEdgeScrollVelocity`: toward the start within the edge width of the list's top,
683    /// toward the end within it of its bottom, faster closer to the edge; none against an end.
684    fn edge_scroll_velocity(self: Handle<Self>, app: &mut App, position: Offset) -> f64 {
685        let Some(list) = self.viewport_rect(app) else {
686            return 0.0;
687        };
688        let metrics = self.scroll(app).metrics(app);
689        let y = position.dy() - list.top;
690        let mut velocity = edge_scroll_speed(y);
691        let mut bound = 0.0;
692        if velocity == 0.0 {
693            velocity = -edge_scroll_speed(list.height() - y);
694            bound = metrics.scrollable_length;
695        }
696        if (bound - metrics.offset).abs() < SCROLL_ROUNDING_TOLERANCE {
697            velocity = 0.0;
698        }
699        velocity
700    }
701
702    /// `SetPendingAutoPanVelocity`: a scroll starts after `EDGE_SCROLL_START_DELAY`, changes
703    /// speed at once, and stops at once.
704    fn set_pending_velocity(self: Handle<Self>, app: &mut App, velocity: f64) {
705        if velocity == 0.0 {
706            let drag = &mut app.get_mut(self).drag;
707            drag.velocity = 0.0;
708            drag.pending_velocity = 0.0;
709            if let Some(timer) = drag.edge_timer.take() {
710                timer.cancel(app);
711            }
712            if let Some(ticker) = app.get(self).ticker.handle()
713                && ticker.is_active(app)
714            {
715                ticker.stop(app, false);
716            }
717            return;
718        }
719        if app.get(self).drag.velocity != 0.0 {
720            app.get_mut(self).drag.velocity = velocity;
721            return;
722        }
723        app.get_mut(self).drag.pending_velocity = velocity;
724        if app.get(self).drag.edge_timer.is_none() {
725            let timer = Timer::new(
726                app,
727                EDGE_SCROLL_START_DELAY,
728                Listener::new(move |app| {
729                    if self.alive(app) {
730                        self.start_edge_scroll(app);
731                    }
732                }),
733            );
734            app.get_mut(self).drag.edge_timer = Some(timer);
735        }
736    }
737
738    /// `StartEdgeScrollTimerTick`: the pending velocity becomes the scroll's.
739    fn start_edge_scroll(self: Handle<Self>, app: &mut App) {
740        let drag = &mut app.get_mut(self).drag;
741        drag.edge_timer = None;
742        drag.velocity = std::mem::take(&mut drag.pending_velocity);
743        drag.last_tick = None;
744        if drag.velocity != 0.0
745            && let Some(ticker) = app.get(self).ticker.handle()
746            && !ticker.is_active(app)
747        {
748            ticker.start(app);
749        }
750    }
751
752    /// One frame of edge scrolling at the current velocity. The source's drag keeps reporting
753    /// where it is while the list scrolls under it.
754    pub(super) fn edge_scroll_tick(self: Handle<Self>, app: &mut App, elapsed: Duration) {
755        let drag = &mut app.get_mut(self).drag;
756        let delta = elapsed
757            .saturating_sub(drag.last_tick.unwrap_or(elapsed))
758            .as_secs_f64();
759        drag.last_tick = Some(elapsed);
760        let velocity = drag.velocity;
761        let position = drag.position;
762        if velocity == 0.0 {
763            return;
764        }
765        let scroll = self.scroll(app);
766        scroll.scroll_by(app, -velocity * delta, true);
767        if let Some(position) = position {
768            self.drag_over(app, position);
769        }
770    }
771
772    /// The drop at `position`: the system's drag over there, then `TreeViewItem::OnDrop` on the
773    /// row the drag over reached, and `TreeViewList::OnDrop` where the row leaves it.
774    fn drop(self: Handle<Self>, app: &mut App, position: Offset) {
775        self.drag_over(app, position);
776        let widget = self.widget(app).clone();
777        let tree = app.get(self).tree.clone();
778        let rows = app.get(self).rows.clone();
779        let drag = &app.get(self).drag;
780        let (entered, dragged, slot) =
781            (drag.entered.clone(), drag.dragged.clone(), drag.empty_slot);
782        let mut accepted = drag.accepted;
783        let selected_roots = || tree.roots_of_selected_subtrees(&self.selected_nodes(app));
784        let mut handled = false;
785        let mut plan = MovePlan::default();
786        if let Some(target) = &entered
787            && accepted
788            && let Some(dragged) = &dragged
789        {
790            if self.is_multi_select_with_selected_items(app) {
791                plan = tree.plan_drop_into(&selected_roots(), target);
792                handled = true;
793            } else if dragged != target {
794                plan = tree.plan_drop_into(std::slice::from_ref(dragged), target);
795                handled = true;
796            } else {
797                accepted = false;
798            }
799        }
800        if !handled
801            && widget.allow_drop
802            && accepted
803            && let Some(dragged) = &dragged
804            && let Some(slot) = slot
805            && let Some(insert_at) = rows.get(slot)
806        {
807            let nodes = if self.is_multi_select_with_selected_items(app) {
808                selected_roots()
809            } else {
810                vec![dragged.clone()]
811            };
812            plan = tree.plan_drop_between(&nodes, insert_at, slot);
813        }
814        app.get_mut(self).drag.result = if accepted {
815            DataPackageOperation::Move
816        } else {
817            DataPackageOperation::None
818        };
819        self.request_moves(app, plan);
820        self.clear_drag_over(app);
821    }
822
823    /// Ends what a drag over set: the timers, the gap, edge scrolling and the dragged-over row.
824    fn clear_drag_over(self: Handle<Self>, app: &mut App) {
825        if let Some(timer) = app.get_mut(self).drag.expand_timer.take() {
826            timer.cancel(app);
827        }
828        self.reset_live_reorder(app);
829        self.set_pending_velocity(app, 0.0);
830        let drag = &mut app.get_mut(self).drag;
831        drag.entered = None;
832        drag.drag_over_item = None;
833        drag.empty_slot = None;
834        drag.over_self = false;
835        self.set_state(app, |_| {});
836    }
837
838    /// The application rebuilt the tree during a drag: a gap is kept only while the dragged row
839    /// is still a row.
840    pub(super) fn drag_tree_changed(self: Handle<Self>, app: &mut App) {
841        let state = app.get(self);
842        if let Some(primary) = &state.drag.primary
843            && state.rows.index_of(primary).is_none()
844        {
845            let drag = &mut app.get_mut(self).drag;
846            drag.live_index = None;
847            drag.live_shown = None;
848        }
849    }
850
851    /// Cancels the drag's timers when the tree goes.
852    pub(super) fn dispose_drag(self: Handle<Self>, app: &mut App) {
853        let drag = std::mem::take(&mut app.get_mut(self).drag);
854        for timer in [drag.live_timer, drag.expand_timer, drag.edge_timer]
855            .into_iter()
856            .flatten()
857        {
858            timer.cancel(app);
859        }
860    }
861
862    // MARK: Geometry
863
864    /// The built rows, in order, with where each is laid out before a gap displaces it.
865    fn laid_out_rows(self: Handle<Self>, app: &mut App) -> Vec<(usize, String, Rect)> {
866        let rows = app.get(self).rows.clone();
867        let mut laid_out: Vec<(usize, String, Rect)> = app
868            .get(self)
869            .realized
870            .clone()
871            .into_iter()
872            .filter_map(|id| Some((rows.index_of(&id)?, id)))
873            .filter_map(|(row, id)| {
874                let rect = self.row_rect(app, &id)?;
875                Some((row, id, rect))
876            })
877            .collect();
878        laid_out.sort_by_key(|(row, _, _)| *row);
879        laid_out
880    }
881
882    /// Where the row at `row` is drawn, displaced by a gap, if it is built.
883    fn row_drawn_rect(self: Handle<Self>, app: &mut App, row: usize) -> Option<Rect> {
884        let id = app.get(self).rows.get(row)?.to_owned();
885        let rect = self.row_rect(app, &id)?;
886        Some(rect.translate(0.0, self.displacement(app, row)))
887    }
888
889    /// The row drawn at `position`. Where a displaced row covers the dragged row's placeholder,
890    /// the displaced one is the row.
891    fn row_drawn_at(
892        self: Handle<Self>,
893        app: &mut App,
894        position: Offset,
895    ) -> Option<(usize, String, Rect)> {
896        let primary = app.get(self).drag.primary.clone();
897        let hits: Vec<(usize, String, Rect)> = self
898            .laid_out_rows(app)
899            .into_iter()
900            .map(|(row, id, rect)| {
901                let rect = rect.translate(0.0, self.displacement(app, row));
902                (row, id, rect)
903            })
904            .filter(|(_, _, rect)| rect.contains(position))
905            .collect();
906        hits.iter()
907            .find(|(_, id, _)| Some(id) != primary.as_ref())
908            .or(hits.first())
909            .cloned()
910    }
911
912    /// `GetInsertionIndex` of the ItemsStackPanel, from where the rows are laid out: the row
913    /// under `position`, or the one after it below its middle; the row count below the last.
914    fn insertion_index(self: Handle<Self>, app: &mut App, position: Offset) -> Option<usize> {
915        let count = app.get(self).rows.len();
916        if count == 0 {
917            return Some(0);
918        }
919        let laid_out = self.laid_out_rows(app);
920        let y = position.dy();
921        for (row, _, rect) in &laid_out {
922            if y >= rect.top && y < rect.bottom {
923                return Some(if y - rect.top >= rect.height() / 2.0 {
924                    row + 1
925                } else {
926                    *row
927                });
928            }
929        }
930        let (first, _, first_rect) = laid_out.first()?;
931        let (last, _, _) = laid_out.last()?;
932        Some(if y < first_rect.top { *first } else { last + 1 })
933    }
934
935    /// `GetClosestElementInfo`: the row under `position`, or the nearest built one.
936    fn closest_row(self: Handle<Self>, app: &mut App, position: Offset) -> Option<usize> {
937        let laid_out = self.laid_out_rows(app);
938        let y = position.dy();
939        laid_out
940            .iter()
941            .find(|(_, _, rect)| y >= rect.top && y < rect.bottom)
942            .or_else(|| {
943                if y < laid_out.first()?.2.top {
944                    laid_out.first()
945                } else {
946                    laid_out.last()
947                }
948            })
949            .map(|(row, _, _)| *row)
950    }
951}
952
953#[cfg(test)]
954mod tests {
955    use super::*;
956
957    #[test]
958    fn the_gap_moves_past_a_row_only_beyond_its_middle() {
959        // Dragging down from row 1: over the top half of row 3, the gap stays at row 2.
960        assert_eq!(drag_over_index(3, 3, 2), 2);
961        // Over the bottom half of row 3, it takes row 3.
962        assert_eq!(drag_over_index(3, 4, 2), 3);
963        // Dragging up from row 5: over the bottom half of row 2, it stays at row 3.
964        assert_eq!(drag_over_index(2, 3, 3), 3);
965        // Over the top half of row 2, it takes row 2.
966        assert_eq!(drag_over_index(2, 2, 3), 2);
967    }
968
969    #[test]
970    fn edge_scrolling_slows_linearly_away_from_the_edge() {
971        assert_eq!(edge_scroll_speed(0.0), 1500.0);
972        assert_eq!(edge_scroll_speed(50.0), 825.0);
973        assert_eq!(edge_scroll_speed(100.0), 150.0);
974        assert_eq!(edge_scroll_speed(100.5), 0.0);
975    }
976
977    #[test]
978    fn the_middle_three_fifths_of_a_row_take_a_drop_into_it() {
979        let row = Rect::from_ltwh(0.0, 100.0, 200.0, 30.0);
980        assert!(!is_drag_over(row, 105.0));
981        assert!(is_drag_over(row, 107.0));
982        assert!(is_drag_over(row, 123.0));
983        assert!(!is_drag_over(row, 125.0));
984    }
985}