Skip to main content

gpui_kit_grid/state/
drag.rs

1//! Dragging rows within the application: what a row drag carries, what a
2//! drop names, and what the delegate's `drag_payload` hook knows.
3//!
4//! The source: a press a [`RowDragGesture`] takes starts no drag-selection;
5//! past the gesture's threshold the grid takes the pressed row's command
6//! scope and the delegate's payload and arms the rows' wrapper
7//! (`"live-grid-rows"`) with `on_drag` for the next frame, whose next move
8//! starts GPUI's drag. The wrapper carries an empty `on_click` while the
9//! gesture is enabled, so GPUI records the press it needs. The armed drag
10//! goes on release, or in a frame with no drag and no press.
11//!
12//! The target: the wrapper follows every row drag (`on_drag_move`) and the
13//! application's types it registered: over the rows the [`RowDropPolicy`]
14//! places the drag by the line painted under the pointer, the frame draws
15//! the target by its key, the rows scroll near an edge, and the cursor says
16//! whether the grid takes it. A drop places it again where it lands and
17//! emits `LiveGridEvent::Drop`. GPUI has no "drag ended" callback: the
18//! target goes when the pointer leaves, on any release, and in a frame with
19//! no drag.
20
21use std::{any::Any, fmt, rc::Rc, sync::Arc};
22
23use gpui_kit::base::AutoScroll;
24use gpui_kit::component::ActiveTheme as _;
25use gpui_kit::{
26    AnyElement, App, AppContext as _, Bounds, Context, CursorStyle, Div, DragMoveEvent, EntityId,
27    Hsla, InteractiveElement as _, IntoElement, Modifiers, ParentElement as _, Pixels, Point,
28    Render, SharedString, Stateful, StatefulInteractiveElement as _, Styled as _, Window, div,
29    point, prelude::FluentBuilder as _, px, relative, size,
30};
31use rust_i18n::t;
32
33use super::{
34    CELL_PADDING, KeyOf, LiveGridDelegate, LiveGridEvent, LiveGridState,
35    frame::PaintedLine,
36    ghost::GhostTextStyle,
37    pinned::BodyLine,
38    selection::LineTarget,
39    stats::{profile_elapsed, profile_start},
40};
41use crate::{
42    engine::GroupPath,
43    model::GridRow,
44    policy::{
45        DropLine, NoRowDrag, NoRowDrop, RowDragGesture, RowDragPressContext, RowDropContext,
46        RowDropPolicy, SelectableLine,
47    },
48    store::StoreSnapshot,
49};
50
51/// The payload of a row drag: what GPUI carries while rows are dragged out
52/// of a grid. A drop target outside grids takes it with
53/// `on_drop::<RowDrag<K>>`.
54#[derive(Clone)]
55pub struct RowDrag<K> {
56    grid: EntityId,
57    keys: Arc<[K]>,
58    payload: DragPayload,
59}
60
61impl<K> RowDrag<K> {
62    /// The grid the rows come from.
63    pub fn grid(&self) -> EntityId {
64        self.grid
65    }
66
67    /// The dragged rows in the shown order: the command scope of the press,
68    /// taken when the drag started.
69    pub fn keys(&self) -> &Arc<[K]> {
70        &self.keys
71    }
72
73    /// What the application added (`LiveGridDelegate::drag_payload`).
74    pub fn payload(&self) -> &DragPayload {
75        &self.payload
76    }
77}
78
79impl<K> fmt::Debug for RowDrag<K> {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        f.debug_struct("RowDrag")
82            .field("grid", &self.grid)
83            .field("keys", &self.keys.len())
84            .field("payload", &self.payload)
85            .finish()
86    }
87}
88
89/// Application data riding along a drag, and the label of its ghost.
90#[derive(Clone, Default)]
91pub struct DragPayload {
92    data: Option<Arc<dyn Any>>,
93    label: Option<SharedString>,
94}
95
96impl DragPayload {
97    /// An empty payload: the keys alone are dragged.
98    pub fn new() -> Self {
99        Self::default()
100    }
101
102    /// Adds data for the drop target, read back with [`Self::data`].
103    pub fn with_data<T: 'static>(mut self, data: T) -> Self {
104        self.data = Some(Arc::new(data));
105        self
106    }
107
108    /// The data, if it is a `T`.
109    pub fn data<T: 'static>(&self) -> Option<&T> {
110        self.data.as_deref()?.downcast_ref()
111    }
112
113    /// Sets the text of the drag's ghost ("3 orders"); without one the
114    /// ghost says how many rows ("3 rows").
115    pub fn with_label(mut self, label: impl Into<SharedString>) -> Self {
116        self.label = Some(label.into());
117        self
118    }
119
120    /// The ghost's text, if set.
121    pub fn label(&self) -> Option<&SharedString> {
122        self.label.as_ref()
123    }
124}
125
126impl fmt::Debug for DragPayload {
127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128        f.debug_struct("DragPayload")
129            .field("label", &self.label)
130            .field("has_data", &self.data.is_some())
131            .finish()
132    }
133}
134
135/// What was dropped on a grid.
136#[derive(Clone, Debug)]
137#[non_exhaustive]
138pub enum DropSource<K> {
139    /// Rows of a grid with this key type: this grid or another.
140    Rows(RowDrag<K>),
141    /// A value of a type the grid takes (`with_drop_payload::<T>()`), as its
142    /// data ([`DragPayload::data`]).
143    Payload(DragPayload),
144}
145
146/// Where a drop lands, by identity.
147#[derive(Clone, Debug, PartialEq, Eq)]
148#[non_exhaustive]
149pub enum DropTarget<K> {
150    /// A data row (a tree row too), and where relative to it.
151    Row {
152        /// The row.
153        key: K,
154        /// Before, after or onto it.
155        place: DropPlace,
156    },
157    /// A group caption.
158    Group(GroupPath),
159    /// The empty area below the rows, or an empty grid.
160    Empty,
161}
162
163/// Where a drop lands relative to a row.
164#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
165#[non_exhaustive]
166pub enum DropPlace {
167    /// Above the row.
168    Before,
169    /// Below the row.
170    After,
171    /// Onto the row.
172    Onto,
173}
174
175/// What [`LiveGridDelegate::drag_payload`](super::LiveGridDelegate::drag_payload)
176/// knows: the rows about to be dragged.
177pub struct RowDragContext<'a, R: GridRow> {
178    keys: &'a [R::Key],
179    pressed: &'a R::Key,
180    snapshot: &'a StoreSnapshot<R>,
181    modifiers: Modifiers,
182}
183
184impl<'a, R: GridRow> RowDragContext<'a, R> {
185    /// The rows to drag, in the shown order (the command scope).
186    pub fn keys(&self) -> &'a [R::Key] {
187        self.keys
188    }
189
190    /// The row the press was on.
191    pub fn pressed(&self) -> &'a R::Key {
192        self.pressed
193    }
194
195    /// A row of the snapshot shown when the drag started.
196    pub fn row(&self, key: &R::Key) -> Option<&'a Arc<R>> {
197        self.snapshot.row(self.snapshot.row_id(key)?)
198    }
199
200    /// The modifiers held.
201    pub fn modifiers(&self) -> Modifiers {
202        self.modifiers
203    }
204}
205
206/// Adds the listeners of one of the application's drop types to the rows'
207/// wrapper (`with_drop_payload`).
208type DropRegistrar<D> = Rc<dyn Fn(Stateful<Div>, &mut Context<LiveGridState<D>>) -> Stateful<Div>>;
209
210/// What a grid keeps for row drags: the gesture and the drag armed past its
211/// threshold; the drop policy, the application's drop types, and the drag
212/// over the rows with its target.
213pub(super) struct DragSlot<D: LiveGridDelegate> {
214    gesture: Box<dyn RowDragGesture<D::Row>>,
215    /// Set past the gesture's threshold, until the release: the rows'
216    /// wrapper carries it as `on_drag`.
217    armed: Option<RowDrag<KeyOf<D>>>,
218    drop_policy: Box<dyn RowDropPolicy<D::Row>>,
219    payloads: Vec<DropRegistrar<D>>,
220    /// The drag over the rows, from its first move inside them until it
221    /// leaves, drops or ends.
222    hover: Option<DropHover<KeyOf<D>>>,
223    /// The target of the hovering drag wants placing again from the lines a
224    /// frame paints: the rows scrolled under the pointer.
225    retarget: bool,
226    auto_scroll: AutoScroll,
227}
228
229impl<D: LiveGridDelegate> Default for DragSlot<D> {
230    fn default() -> Self {
231        Self {
232            gesture: Box::new(NoRowDrag),
233            armed: None,
234            drop_policy: Box::new(NoRowDrop),
235            payloads: Vec::new(),
236            hover: None,
237            retarget: false,
238            auto_scroll: AutoScroll::default(),
239        }
240    }
241}
242
243impl<D: LiveGridDelegate> DragSlot<D> {
244    /// Returns true if a press may drag rows: the wrapper then records
245    /// presses.
246    pub(super) fn is_enabled(&self) -> bool {
247        self.gesture.is_enabled()
248    }
249
250    /// Returns true if `press` may become a row drag.
251    pub(super) fn is_drag_press(&self, press: &RowDragPressContext<'_, D::Row>) -> bool {
252        self.gesture.is_enabled() && self.gesture.is_drag_press(press)
253    }
254
255    /// How far the pointer travels from the press before the drag starts.
256    pub(super) fn threshold(&self) -> Pixels {
257        self.gesture.threshold()
258    }
259
260    /// Drops the armed drag: the press ended.
261    pub(super) fn unarm(&mut self) {
262        self.armed = None;
263    }
264
265    /// Returns true while a drag is over the rows (`ReorderContext::
266    /// is_drag_over`).
267    pub(super) fn is_over(&self) -> bool {
268        self.hover.is_some()
269    }
270}
271
272/// What is dragged over the rows: rows of a grid with this key type, or a
273/// value of a registered type, cloned once when it came over the rows.
274#[derive(Clone)]
275enum Dragged<K> {
276    Rows(RowDrag<K>),
277    Value(Rc<dyn Any>),
278}
279
280impl<K> Dragged<K> {
281    fn as_ref(&self) -> DraggedRef<'_, K> {
282        match self {
283            Self::Rows(drag) => DraggedRef::Rows(drag),
284            Self::Value(value) => DraggedRef::Value(value.as_ref()),
285        }
286    }
287}
288
289/// [`Dragged`], borrowed: what a drop hands over.
290#[derive(Clone, Copy)]
291enum DraggedRef<'a, K> {
292    Rows(&'a RowDrag<K>),
293    Value(&'a dyn Any),
294}
295
296/// A drag over the rows: what it carries, where it was last, and where it
297/// would land.
298struct DropHover<K> {
299    dragged: Dragged<K>,
300    own: bool,
301    position: Point<Pixels>,
302    modifiers: Modifiers,
303    target: Option<DropTarget<K>>,
304}
305
306/// Returns true if `modifiers` ask to copy rather than move: Option on
307/// macOS, Ctrl elsewhere, as the platforms' file managers do. Both count,
308/// so the code is the same everywhere.
309/// The ghost of a row drag: a chip with the payload's label, or "3 rows",
310/// right of and below the pointer, in the rows' font. GPUI draws the
311/// ghost's view at the pointer less `offset`, the press's offset in the
312/// rows' wrapper, so the chip moves by it.
313struct RowDragGhost {
314    label: SharedString,
315    height: Pixels,
316    offset: Point<Pixels>,
317    text: GhostTextStyle,
318}
319
320impl Render for RowDragGhost {
321    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
322        let theme = cx.theme();
323        self.text
324            .root()
325            .pl(self.offset.x + px(12.))
326            .pt(self.offset.y + px(12.))
327            .child(
328                div()
329                    .h(self.height)
330                    .max_w(px(320.))
331                    .px(CELL_PADDING)
332                    .flex()
333                    .items_center()
334                    .overflow_hidden()
335                    .bg(theme.table_head)
336                    .text_color(theme.table_head_foreground)
337                    .border_1()
338                    .border_color(theme.border)
339                    .shadow_md()
340                    .opacity(0.9)
341                    .child(div().min_w(px(0.)).truncate().child(self.label.clone())),
342            )
343    }
344}
345
346/// The ghost's text: the payload's label, else how many rows.
347fn ghost_label<K>(drag: &RowDrag<K>) -> SharedString {
348    if let Some(label) = drag.payload().label() {
349        return label.clone();
350    }
351    match drag.keys().len() {
352        1 => t!("live_grid.drag.row").into(),
353        count => t!("live_grid.drag.rows", count = count).into(),
354    }
355}
356
357impl<D: LiveGridDelegate> LiveGridState<D> {
358    /// Sets which presses drag rows (default [`NoRowDrag`]: none;
359    /// [`SelectedRowsDrag`](crate::SelectedRowsDrag) is LiveGrid's gesture).
360    pub fn with_row_drag_gesture(mut self, gesture: impl RowDragGesture<D::Row>) -> Self {
361        self.drag.gesture = Box::new(gesture);
362        self
363    }
364
365    /// Sets where drops on the rows land (default [`NoRowDrop`]: the grid
366    /// takes none; [`DropOnRows`](crate::DropOnRows) and
367    /// [`DropBetweenRows`](crate::DropBetweenRows) are built in).
368    pub fn with_row_drop_policy(mut self, policy: impl RowDropPolicy<D::Row>) -> Self {
369        self.drag.drop_policy = Box::new(policy);
370        self
371    }
372
373    /// Takes drops of `T`, a drag payload of the application's own, besides
374    /// the rows of grids with this key type: an element with
375    /// `on_drag(T)` dropped on the rows arrives as `DropSource::Payload`,
376    /// the value cloned as its data. The drop policy places it, reading the
377    /// value with `RowDropContext::payload`.
378    pub fn with_drop_payload<T: Clone + 'static>(mut self) -> Self {
379        self.drag.payloads.push(Rc::new(|this, cx| {
380            this.on_drag_move(cx.listener(Self::on_payload_drag_move::<T>))
381                .on_drop(cx.listener(Self::on_payload_drop::<T>))
382        }));
383        self
384    }
385
386    /// Returns true while a row drag from this grid is in progress: from the
387    /// gesture's threshold to the release.
388    pub fn is_dragging_rows(&self) -> bool {
389        self.drag.armed.is_some()
390    }
391
392    /// The row drag from this grid in progress, if any. For tests.
393    #[cfg(any(test, feature = "test-support"))]
394    pub fn row_drag(&self) -> Option<&RowDrag<KeyOf<D>>> {
395        self.drag.armed.as_ref()
396    }
397
398    /// Asks the gesture whether the primary press on the data row of `key`,
399    /// at `column`, may drag rows.
400    pub(super) fn is_row_drag_press(
401        &self,
402        key: &KeyOf<D>,
403        column: super::ColumnOf<D>,
404        was_selected: bool,
405        modifiers: Modifiers,
406        click_count: usize,
407    ) -> bool {
408        if !self.drag.is_enabled() {
409            return false;
410        }
411        let Some(id) = self.snapshot.row_id(key) else {
412            return false;
413        };
414        let Some(row) = self.snapshot.row(id) else {
415            return false;
416        };
417        let line = SelectableLine::Row {
418            row: &**row,
419            branch: self.projection.branch(id),
420        };
421        self.drag.is_drag_press(&RowDragPressContext::new(
422            line,
423            column,
424            was_selected,
425            modifiers,
426            self.platform,
427            self.selection.mode(),
428            click_count,
429        ))
430    }
431
432    /// The pointer passed the gesture's threshold from a press on the row
433    /// of `pressed`: the pressed row's command scope and the delegate's
434    /// payload arm the drag for the next frame. Returns false, arming
435    /// nothing, if the row left the store or the delegate refused.
436    pub(super) fn arm_row_drag(
437        &mut self,
438        pressed: &KeyOf<D>,
439        modifiers: Modifiers,
440        cx: &mut Context<Self>,
441    ) -> bool {
442        if self.snapshot.row_id(pressed).is_none() {
443            return false;
444        }
445        let keys = self
446            .command_scope(Some(&LineTarget::Row(pressed.clone())))
447            .shared_keys();
448        let payload = self.delegate.drag_payload(
449            &RowDragContext {
450                keys: &keys,
451                pressed,
452                snapshot: &self.snapshot,
453                modifiers,
454            },
455            cx,
456        );
457        let Some(payload) = payload else {
458            return false;
459        };
460        self.drag.armed = Some(RowDrag {
461            grid: cx.entity_id(),
462            keys,
463            payload,
464        });
465        cx.notify();
466        true
467    }
468
469    /// Drops the armed drag when the press is over.
470    pub(super) fn unarm_row_drag(&mut self) {
471        self.drag.unarm();
472    }
473
474    /// A frame of a grid whose armed drag GPUI no longer carries and whose
475    /// press is over (a release the grid did not see): the drag goes.
476    pub(super) fn settle_row_drag(&mut self, cx: &mut Context<Self>) {
477        if self.drag.armed.is_some() && self.press.is_none() && !cx.has_active_drag() {
478            self.drag.unarm();
479        }
480        if self.drag.hover.is_some() && !cx.has_active_drag() {
481            self.end_drop_hover(cx);
482        }
483    }
484
485    /// The wrapper of the rows (`"live-grid-rows"`) around
486    /// `body`: it takes the body's place in the layout. While the drag
487    /// gesture is enabled it carries an empty `on_click`, so GPUI records
488    /// a press on the rows; armed, its `on_drag` starts the drag on the next
489    /// move, and the ghost draws in `ghost_text`. A div without a role: no
490    /// accessibility node between the grid and its rows. It takes no wheel:
491    /// the body scrolls as before.
492    pub(super) fn render_rows(
493        &self,
494        body: impl IntoElement,
495        ghost_text: GhostTextStyle,
496        cx: &mut Context<Self>,
497    ) -> AnyElement {
498        let row_height = self.row_height;
499        div()
500            .id("live-grid-rows")
501            .flex()
502            .flex_col()
503            .flex_grow(1.)
504            .flex_shrink(1.)
505            .flex_basis(relative(0.))
506            .w_full()
507            .when(self.drag.is_enabled(), |this| this.on_click(|_, _, _| {}))
508            // Every row drag: a target shows where it lands, or that it
509            // does not, and the source its own cursor.
510            .on_drag_move(cx.listener(Self::on_row_drag_move))
511            .when(self.drag.drop_policy.is_enabled(), |this| {
512                this.on_drop(cx.listener(Self::on_rows_drop))
513            })
514            .map(|this| {
515                self.drag
516                    .payloads
517                    .iter()
518                    .fold(this, |this, register| register(this, cx))
519            })
520            // Armed, the drag starts with the closed hand (GPUI takes the
521            // cursor of the element it starts from).
522            .when_some(self.drag.armed.clone(), |this, drag| {
523                this.cursor(CursorStyle::ClosedHand).on_drag(
524                    drag,
525                    move |drag: &RowDrag<KeyOf<D>>, offset, _: &mut Window, cx: &mut App| {
526                        let label = ghost_label(drag);
527                        cx.new(|_| RowDragGhost {
528                            label,
529                            height: row_height,
530                            offset,
531                            text: ghost_text.clone(),
532                        })
533                    },
534                )
535            })
536            .child(body)
537            .into_any_element()
538    }
539
540    /// A row drag moved anywhere in the window.
541    fn on_row_drag_move(
542        &mut self,
543        event: &DragMoveEvent<RowDrag<KeyOf<D>>>,
544        window: &mut Window,
545        cx: &mut Context<Self>,
546    ) {
547        let (position, modifiers) = (event.event.position, event.event.modifiers);
548        let inside = event.bounds.contains(&position);
549        if !inside && self.drag.hover.is_none() {
550            return;
551        }
552        let drag = event.drag(cx).clone();
553        let own = drag.grid() == cx.entity_id();
554        self.follow_drag(
555            Dragged::Rows(drag),
556            own,
557            position,
558            modifiers,
559            inside,
560            window,
561            cx,
562        );
563    }
564
565    /// A drag of the application's type `T` moved anywhere in the window.
566    /// The value is cloned once, when it comes over the rows.
567    fn on_payload_drag_move<T: Clone + 'static>(
568        &mut self,
569        event: &DragMoveEvent<T>,
570        window: &mut Window,
571        cx: &mut Context<Self>,
572    ) {
573        let (position, modifiers) = (event.event.position, event.event.modifiers);
574        let inside = event.bounds.contains(&position);
575        if !inside && self.drag.hover.is_none() {
576            return;
577        }
578        let value = match &self.drag.hover {
579            Some(DropHover {
580                dragged: Dragged::Value(value),
581                ..
582            }) if value.is::<T>() => value.clone(),
583            _ => Rc::new(event.drag(cx).clone()) as Rc<dyn Any>,
584        };
585        self.follow_drag(
586            Dragged::Value(value),
587            false,
588            position,
589            modifiers,
590            inside,
591            window,
592            cx,
593        );
594    }
595
596    /// A drag moved: over the rows its target and the cursor follow, and
597    /// near an edge the rows scroll; off them the target goes.
598    #[allow(clippy::too_many_arguments)]
599    fn follow_drag(
600        &mut self,
601        dragged: Dragged<KeyOf<D>>,
602        own: bool,
603        position: Point<Pixels>,
604        modifiers: Modifiers,
605        inside: bool,
606        window: &mut Window,
607        cx: &mut Context<Self>,
608    ) {
609        if !inside {
610            // Off this grid: the drag shows the closed hand again until
611            // another target says otherwise.
612            self.end_drop_hover(cx);
613            cx.set_active_drag_cursor_style(CursorStyle::ClosedHand, window);
614            return;
615        }
616        let started = profile_start();
617        let target = self.row_drop_target_at(dragged.as_ref(), own, position, modifiers);
618        self.stats.last_drop_target = profile_elapsed(started);
619        let cursor = match &target {
620            Some(_) if self.drag.drop_policy.is_copy(modifiers) => CursorStyle::DragCopy,
621            Some(_) => CursorStyle::ClosedHand,
622            // Over its own rows the source keeps the closed hand.
623            None if own => CursorStyle::ClosedHand,
624            None => CursorStyle::OperationNotAllowed,
625        };
626        // After every grid saw this move: a grid the pointer left resets
627        // the cursor at once, and the grid under it has the last word,
628        // whatever their order.
629        window.defer(cx, move |window, cx| {
630            if cx.active_drag_cursor_style() != Some(cursor) {
631                cx.set_active_drag_cursor_style(cursor, window);
632            }
633        });
634        let changed = self.drag.hover.as_ref().map(|hover| &hover.target) != Some(&target);
635        let entered = self.drag.hover.is_none();
636        self.drag.hover = Some(DropHover {
637            dragged,
638            own,
639            position,
640            modifiers,
641            target,
642        });
643        if self.drag.drop_policy.is_enabled() {
644            let delta = AutoScroll::compute_delta(position.y, self.rows_bounds());
645            self.drag.auto_scroll.last_drag_position = Some(position);
646            self.drag.auto_scroll.set(delta, cx, |delta, state, cx| {
647                state.auto_scroll_drop(delta, cx)
648            });
649        }
650        if changed || entered {
651            cx.notify();
652        }
653    }
654
655    /// One auto-scroll step of a drag over the rows: the next frame places
656    /// the drag again on the lines it paints.
657    fn auto_scroll_drop(&mut self, delta: Pixels, cx: &mut Context<Self>) {
658        if self.drag.hover.is_none() {
659            self.drag.auto_scroll.stop();
660            return;
661        }
662        let before = (self.scroll_row, self.scroll_offset);
663        self.scroll_rows_by(delta);
664        if (self.scroll_row, self.scroll_offset) != before {
665            self.drag.retarget = true;
666            cx.notify();
667        }
668    }
669
670    /// Places the hovering drag again, after the rows scrolled under it:
671    /// called by the frame once its lines are painted.
672    pub(super) fn retarget_drop(&mut self) {
673        if !std::mem::take(&mut self.drag.retarget) {
674            return;
675        }
676        let Some(hover) = &self.drag.hover else {
677            return;
678        };
679        let target = self.row_drop_target_at(
680            hover.dragged.as_ref(),
681            hover.own,
682            hover.position,
683            hover.modifiers,
684        );
685        if let Some(hover) = &mut self.drag.hover {
686            hover.target = target;
687        }
688    }
689
690    /// The drag left the rows, dropped or ended: its target and the
691    /// auto-scroll go, and a held order is asked about again.
692    pub(crate) fn end_drop_hover(&mut self, cx: &mut Context<Self>) {
693        self.drag.auto_scroll.stop();
694        self.drag.retarget = false;
695        if self.drag.hover.take().is_some() {
696            self.reconsider_held(cx);
697            cx.notify();
698        }
699    }
700
701    /// Where a drag at a window position lands, as the drop policy places
702    /// it; `None` refuses it. Pinned bands, group footers and totals refuse
703    /// without asking the policy; a row fading out and the area below the
704    /// rows are `DropLine::Empty`. O(1).
705    fn row_drop_target_at(
706        &self,
707        dragged: DraggedRef<'_, KeyOf<D>>,
708        own: bool,
709        position: Point<Pixels>,
710        modifiers: Modifiers,
711    ) -> Option<DropTarget<KeyOf<D>>> {
712        let policy = &self.drag.drop_policy;
713        if !policy.is_enabled() {
714            return None;
715        }
716        let BodyLine::Data(line) = self.body_line_at(position)? else {
717            return None;
718        };
719        let rows = self.rows_bounds();
720        let y = position.y - rows.origin.y + self.scroll_offset;
721        let offset = ((y - self.row_height * line as f32) / self.row_height).clamp(0., 1.);
722        let (snapshot, projection) = (&self.snapshot, &self.projection);
723        let drop_line = match self.painted.get(line) {
724            Some(PaintedLine::Row(id)) => match snapshot.row(*id) {
725                Some(row) => DropLine::Row {
726                    key: row.key(),
727                    branch: projection.branch(*id),
728                },
729                None => DropLine::Empty,
730            },
731            Some(PaintedLine::Caption(path)) => DropLine::Caption(projection.groups().find(path)?),
732            Some(PaintedLine::Footer(_)) => return None,
733            Some(PaintedLine::Ghost(_)) | None => DropLine::Empty,
734        };
735        // The last data row shown, for a drop below the rows.
736        let last_row = matches!(drop_line, DropLine::Empty)
737            .then(|| {
738                (0..projection.len())
739                    .rev()
740                    .filter_map(|ix| projection.row(ix))
741                    .find_map(|id| snapshot.row(id))
742                    .map(|row| row.key())
743            })
744            .flatten();
745        let (rows_drag, value) = match dragged {
746            DraggedRef::Rows(drag) => (Some(drag), None),
747            DraggedRef::Value(value) => (None, Some(value)),
748        };
749        policy.place(&RowDropContext::new(
750            drop_line,
751            offset,
752            rows_drag,
753            value,
754            own,
755            modifiers,
756            (
757                !self.view.sort().is_empty(),
758                projection.is_grouped(),
759                projection.is_tree(),
760            ),
761            last_row,
762            snapshot,
763        ))
764    }
765
766    /// Rows were dropped on the rows: placed again where they landed, one
767    /// `Drop` if the policy takes them.
768    fn on_rows_drop(
769        &mut self,
770        drag: &RowDrag<KeyOf<D>>,
771        window: &mut Window,
772        cx: &mut Context<Self>,
773    ) {
774        let own = drag.grid() == cx.entity_id();
775        let source = DropSource::Rows(drag.clone());
776        self.drop_on_rows(DraggedRef::Rows(drag), own, source, window, cx);
777    }
778
779    /// A value of the application's type `T` was dropped on the rows.
780    fn on_payload_drop<T: Clone + 'static>(
781        &mut self,
782        value: &T,
783        window: &mut Window,
784        cx: &mut Context<Self>,
785    ) {
786        let source = DropSource::Payload(DragPayload::new().with_data(value.clone()));
787        self.drop_on_rows(DraggedRef::Value(value), false, source, window, cx);
788    }
789
790    fn drop_on_rows(
791        &mut self,
792        dragged: DraggedRef<'_, KeyOf<D>>,
793        own: bool,
794        source: DropSource<KeyOf<D>>,
795        window: &mut Window,
796        cx: &mut Context<Self>,
797    ) {
798        let (position, modifiers) = (window.mouse_position(), window.modifiers());
799        let target = self.row_drop_target_at(dragged, own, position, modifiers);
800        self.end_drop_hover(cx);
801        if let Some(target) = target {
802            cx.emit(LiveGridEvent::Drop {
803                source,
804                target,
805                modifiers,
806            });
807        }
808    }
809
810    /// The indicator of the hovering drag's target, by its key on the lines
811    /// this frame painted: a row or a caption filled and framed, a 2 px line
812    /// between rows, under the last row for the empty area, the rows' frame
813    /// in an empty grid. Across every zone, within `rows`.
814    pub(super) fn drop_indicator(
815        &self,
816        rows: Bounds<Pixels>,
817        fill_color: Hsla,
818        border: Hsla,
819    ) -> Vec<(Bounds<Pixels>, Hsla)> {
820        let Some(target) = self
821            .drag
822            .hover
823            .as_ref()
824            .and_then(|hover| hover.target.as_ref())
825        else {
826            return Vec::new();
827        };
828        let top = |line: usize| rows.origin.y + self.row_height * line as f32 - self.scroll_offset;
829        let line_of =
830            |painted: &dyn Fn(&PaintedLine) -> bool| self.painted.iter().position(painted);
831        let mut quads = Vec::new();
832        let bar = |y: Pixels, quads: &mut Vec<_>| {
833            quads.push((
834                Bounds::new(
835                    point(rows.origin.x, y - px(1.)),
836                    size(rows.size.width, px(2.)),
837                ),
838                border,
839            ));
840        };
841        let frame = |area: Bounds<Pixels>, fill: Option<Hsla>, quads: &mut Vec<_>| {
842            if let Some(color) = fill {
843                quads.push((area, color));
844            }
845            let (w, h, b) = (area.size.width, area.size.height, px(2.));
846            let origin = area.origin;
847            quads.extend([
848                (Bounds::new(origin, size(w, b)), border),
849                (
850                    Bounds::new(point(origin.x, origin.y + h - b), size(w, b)),
851                    border,
852                ),
853                (Bounds::new(origin, size(b, h)), border),
854                (
855                    Bounds::new(point(origin.x + w - b, origin.y), size(b, h)),
856                    border,
857                ),
858            ]);
859        };
860        let line_area = |line: usize| {
861            Bounds::new(
862                point(rows.origin.x, top(line)),
863                size(rows.size.width, self.row_height),
864            )
865        };
866        match target {
867            DropTarget::Row { key, place } => {
868                let Some(id) = self.snapshot.row_id(key) else {
869                    return quads;
870                };
871                let Some(line) = line_of(&|painted| painted.row() == Some(id)) else {
872                    return quads;
873                };
874                match place {
875                    DropPlace::Before => bar(top(line), &mut quads),
876                    DropPlace::After => bar(top(line + 1), &mut quads),
877                    _ => frame(line_area(line), Some(fill_color), &mut quads),
878                }
879            }
880            DropTarget::Group(path) => {
881                if let Some(line) = line_of(&|painted| painted.group() == Some(path)) {
882                    frame(line_area(line), Some(fill_color), &mut quads);
883                }
884            }
885            _ => {
886                let shown = self
887                    .painted
888                    .iter()
889                    .rposition(|painted| !matches!(painted, PaintedLine::Ghost(_)));
890                match shown {
891                    Some(last) => bar(top(last + 1), &mut quads),
892                    None => frame(rows, None, &mut quads),
893                }
894            }
895        }
896        // Within the rows' area: a line scrolled half out is cut.
897        quads
898            .into_iter()
899            .filter_map(|(bounds, color)| {
900                let bounds = bounds.intersect(&rows);
901                (bounds.size.height > px(0.) && bounds.size.width > px(0.))
902                    .then_some((bounds, color))
903            })
904            .collect()
905    }
906
907    /// Escape during a row drag from this grid: GPUI drops it, no `Drop`
908    /// comes, and the selection stays. Returns false without one.
909    pub(super) fn cancel_row_drag(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
910        if self.drag.armed.is_none() {
911            return false;
912        }
913        self.drag.unarm();
914        cx.stop_active_drag(window);
915        cx.notify();
916        true
917    }
918}
919
920#[cfg(test)]
921mod tests {
922    use super::*;
923
924    #[test]
925    fn test_drag_payload() {
926        let payload = DragPayload::new();
927        assert!(payload.label().is_none() && payload.data::<u32>().is_none());
928        let payload = payload.with_data(7u32).with_label("3 orders");
929        assert_eq!(payload.data::<u32>(), Some(&7));
930        assert_eq!(payload.data::<i64>(), None);
931        assert_eq!(payload.label().map(AsRef::as_ref), Some("3 orders"));
932        let debug = format!("{payload:?}");
933        assert!(debug.contains("3 orders") && debug.contains("has_data: true"));
934        assert_ne!(
935            DropTarget::Row {
936                key: 1,
937                place: DropPlace::Before
938            },
939            DropTarget::Empty
940        );
941    }
942}