Skip to main content

xrack_layout/
drag.rs

1use crate::{LayoutNode, Point, Target};
2use crate::{scroll_gesture::SCROLL_FRAME_INTERVAL, table_drag_selection::edge_delta};
3use std::{
4    collections::BTreeSet,
5    rc::Rc,
6    time::{Duration, Instant},
7};
8use xrack_runtime::{
9    Component, DragAction, DragEvent, Length, ListRowRenderer, Node, Orientation, RowKey, Value,
10    is_window_overlay,
11};
12
13const THRESHOLD: f32 = 6.0;
14
15#[derive(Debug)]
16pub struct DragDispatch {
17    pub target: Target,
18    pub event: DragEvent,
19    captured_scene: Option<Rc<Node>>,
20}
21
22impl DragDispatch {
23    pub fn new(target: Target, event: DragEvent) -> Self {
24        Self {
25            target,
26            event,
27            captured_scene: None,
28        }
29    }
30
31    pub fn apply(self, component: &mut impl Component, scene: &Node) -> bool {
32        let scene = self.captured_scene.as_deref().unwrap_or(scene);
33        self.target
34            .node_in(scene)
35            .is_some_and(|node| node.kind == self.event.target_kind())
36            && component.drag_event_at(scene, &self.target.path, &self.event)
37    }
38}
39
40#[derive(Debug, Default)]
41pub struct DragUpdate {
42    /// A captured gesture suppresses the underlying click and pointer actions.
43    pub captured: bool,
44    pub events: Vec<DragDispatch>,
45}
46
47#[derive(Clone, Debug)]
48struct Offer {
49    key: String,
50    data: String,
51    allowed: Vec<DragAction>,
52}
53
54impl Offer {
55    fn actions(node: &Node) -> impl Iterator<Item = DragAction> + '_ {
56        [
57            ("allow-move", DragAction::Move),
58            ("allow-copy", DragAction::Copy),
59            ("allow-link", DragAction::Link),
60        ]
61        .into_iter()
62        .filter_map(|(name, action)| node.boolean(name, false).then_some(action))
63    }
64
65    fn from_node(node: &Node) -> Option<Self> {
66        let allowed: Vec<_> = Self::actions(node).collect();
67        (!allowed.is_empty()).then(|| Self {
68            key: node.text("drag-key").unwrap_or("").into(),
69            data: node.text("data").unwrap_or("").into(),
70            allowed,
71        })
72    }
73
74    fn action_for(&self, node: &Node, requested: Option<DragAction>) -> Option<DragAction> {
75        let keys = node.strings("keys");
76        if !keys.is_empty() && !keys.contains(&self.key) {
77            return None;
78        }
79        let action = match node.properties.get("drop-action") {
80            Some(Value::DragAction(action))
81                if requested.is_none_or(|request| request == *action) =>
82            {
83                *action
84            }
85            Some(Value::DragAction(_)) => return None,
86            _ => requested.unwrap_or(self.allowed[0]),
87        };
88        self.allowed.contains(&action).then_some(action)
89    }
90}
91
92#[derive(Clone, Debug)]
93struct Hover {
94    target: Target,
95    action: DragAction,
96    local: Point,
97    list_row: Option<ListTarget>,
98    captured_scene: Option<Rc<Node>>,
99}
100
101#[derive(Clone, Copy, Debug)]
102struct ListTarget {
103    scope: u64,
104    depth: usize,
105}
106
107impl Hover {
108    fn same_destination(&self, other: &Self) -> bool {
109        self.action == other.action
110            && match (self.list_row, other.list_row) {
111                (Some(left), Some(right)) => {
112                    left.scope == right.scope
113                        && self.target.row_key == other.target.row_key
114                        && self.target.element_id() == other.target.element_id()
115                        && self.target.path[left.depth..] == other.target.path[right.depth..]
116                }
117                (None, None) => self.target == other.target,
118                _ => false,
119            }
120    }
121}
122
123#[derive(Clone, Debug)]
124struct Active {
125    offer: Offer,
126    hover: Option<Hover>,
127    scroll_wake: Instant,
128    rehit_after_scroll: bool,
129}
130
131#[derive(Clone, Debug)]
132struct VirtualSource {
133    viewport: Target,
134    renderer: ListRowRenderer,
135    row: RowKey,
136    index_hint: usize,
137    scene: Rc<Node>,
138}
139
140impl VirtualSource {
141    fn capture(context: &Context<'_>, source: &Target) -> Option<Self> {
142        let (depth, viewport, row) = context.list_row(&source.path)?;
143        let path = &source.path[..depth - 1];
144        if !viewport.boolean("drag-auto-scroll", false) {
145            return None;
146        }
147        let row = row.row_key?;
148        let renderer = viewport.list_row_renderer.clone()?;
149        let index_hint = viewport.list?.first_row + source.path[depth - 1];
150        viewport.displayed_row_for_key(row, index_hint)?;
151        Some(Self {
152            viewport: Target::from_node(
153                path.to_vec(),
154                viewport,
155                false,
156                context.scene.row_key_at(path),
157            ),
158            renderer,
159            row,
160            index_hint,
161            scene: Rc::new(context.scene.clone()),
162        })
163    }
164
165    fn is_current(&self, context: &Context<'_>, source: &Target) -> bool {
166        let depth = self.viewport.path.len();
167        let Some(viewport) = self.viewport.node_in(context.scene) else {
168            return false;
169        };
170        let Some(viewport) = context.node(&self.viewport, viewport.kind) else {
171            return false;
172        };
173        if viewport.list_row_renderer.as_ref() != Some(&self.renderer) {
174            return false;
175        }
176        let Some(index) = viewport.displayed_row_for_key(self.row, self.index_hint) else {
177            return false;
178        };
179        let Some(list) = viewport.list else {
180            return false;
181        };
182        if let Some(slot) = index
183            .checked_sub(list.first_row)
184            .filter(|&slot| slot < viewport.children.len())
185        {
186            let mut target = source.clone();
187            target.path[depth] = slot;
188            return context.node(&target, "DragArea").is_some();
189        }
190
191        // Check only the detached source delegate, including live changes to its enabled state.
192        let rows = self
193            .renderer
194            .render_in_scene(viewport, index..index + 1, &Default::default());
195        rows.first()
196            .filter(|row| row.row_key == Some(self.row))
197            .and_then(|row| {
198                if source.path.get(depth + 1) != Some(&0) {
199                    return None;
200                }
201                row.interactive_at_path(&source.path[depth + 2..])
202            })
203            .is_some_and(|node| node.kind == "DragArea" && source.matches_node(node))
204    }
205}
206
207#[derive(Clone, Debug)]
208pub(crate) struct DragSession {
209    source: Target,
210    origin: Point,
211    pub point: Point,
212    touch_hold: Option<(Instant, Duration)>,
213    virtual_source: Option<VirtualSource>,
214    active: Option<Active>,
215}
216
217pub(crate) struct Context<'a> {
218    pub scene: &'a Node,
219    pub layout: &'a LayoutNode,
220    pub scope: &'a [usize],
221    pub modal: Option<&'a [usize]>,
222    pub transitions: &'a BTreeSet<Vec<usize>>,
223    pub blocked: bool,
224}
225
226impl Context<'_> {
227    fn list_row(&self, path: &[usize]) -> Option<(usize, &Node, &Node)> {
228        (1..=path.len()).rev().find_map(|depth| {
229            let row = self.scene.at_path(&path[..depth])?;
230            if row.kind != "ListRow" {
231                return None;
232            }
233            let viewport = self.scene.at_path(&path[..depth - 1])?;
234            Some((depth, viewport, row))
235        })
236    }
237
238    fn node(&self, target: &Target, kind: &str) -> Option<&Node> {
239        if self.blocked
240            || self
241                .modal
242                .is_some_and(|modal| !target.path.starts_with(modal))
243            || self
244                .transitions
245                .iter()
246                .any(|path| target.path.starts_with(path))
247        {
248            return None;
249        }
250        let node = target.node_in(self.scene)?;
251        let item = self.layout.at_path(&target.path)?;
252        (node.kind == kind && item.visible && item.enabled && node.boolean("enabled", true))
253            .then_some(node)
254    }
255
256    pub(crate) fn find<T>(
257        &self,
258        point: Point,
259        accept: &impl Fn(&Node, &LayoutNode) -> Option<T>,
260    ) -> Option<(Target, T)> {
261        fn pick<T>(
262            node: &Node,
263            layout: &LayoutNode,
264            point: Point,
265            path: &mut Vec<usize>,
266            transitions: &BTreeSet<Vec<usize>>,
267            accept: &impl Fn(&Node, &LayoutNode) -> Option<T>,
268        ) -> Option<(Vec<usize>, T)> {
269            if !layout.enabled
270                || transitions.contains(path)
271                || !layout.contains_subtree_point(point)
272            {
273                return None;
274            }
275            for (index, child, item) in layout.children_in_paint_order(node).rev() {
276                if is_window_overlay(child.kind) {
277                    continue;
278                }
279                path.push(index);
280                let found = pick(child, item, point, path, transitions, accept);
281                path.pop();
282                if found.is_some() {
283                    return found;
284                }
285            }
286            (node.boolean("enabled", true)
287                && layout
288                    .map_from_window(point)
289                    .is_some_and(|point| layout.bounds.contains(point)))
290            .then(|| accept(node, layout))
291            .flatten()
292            .map(|value| (path.clone(), value))
293        }
294        if self.blocked {
295            return None;
296        }
297        let (path, result) = pick(
298            self.scene.at_path(self.scope)?,
299            self.layout.at_path(self.scope)?,
300            point,
301            &mut self.scope.to_vec(),
302            self.transitions,
303            accept,
304        )?;
305        let node = self.scene.at_path(&path)?;
306        let row_key = self.scene.row_key_at(&path);
307        Some((Target::from_node(path, node, false, row_key), result))
308    }
309
310    fn hover(&self, offer: &Offer, point: Point, requested: Option<DragAction>) -> Option<Hover> {
311        let (target, (action, local)) = self.find(point, &|node, layout| {
312            (node.kind == "DropArea")
313                .then(|| {
314                    let action = offer.action_for(node, requested)?;
315                    let point = layout.map_from_window(point)?;
316                    Some((
317                        action,
318                        Point {
319                            x: point.x - layout.bounds.x,
320                            y: point.y - layout.bounds.y,
321                        },
322                    ))
323                })
324                .flatten()
325        })?;
326        let list_row = self
327            .list_row(&target.path)
328            .and_then(|(depth, viewport, row)| {
329                row.row_key?;
330                Some(ListTarget {
331                    scope: viewport.list_row_renderer.as_ref()?.scope(),
332                    depth,
333                })
334            });
335        Some(Hover {
336            target,
337            action,
338            local,
339            list_row,
340            captured_scene: None,
341        })
342    }
343}
344
345pub(crate) fn send(update: &mut DragUpdate, target: &Target, event: DragEvent) {
346    update.events.push(DragDispatch::new(target.clone(), event));
347}
348
349impl DragSession {
350    pub fn arm(context: Context<'_>, point: Point, touch_started: Option<Instant>) -> Option<Self> {
351        let (source, delay) = context.find(point, &|node, _| {
352            (node.kind == "DragArea" && Offer::actions(node).next().is_some())
353                .then(|| node.int("touch-drag-delay").unwrap_or_default().max(0) as u64)
354        })?;
355        Some(Self {
356            source,
357            origin: point,
358            point,
359            touch_hold: touch_started.map(|started| (started, Duration::from_millis(delay))),
360            virtual_source: None,
361            active: None,
362        })
363    }
364
365    pub fn active(&self) -> bool {
366        self.active.is_some()
367    }
368
369    pub fn action(&self) -> Option<DragAction> {
370        self.active.as_ref().map(|active| {
371            active
372                .hover
373                .as_ref()
374                .map_or(DragAction::None, |over| over.action)
375        })
376    }
377
378    pub fn over(&self, node: &Node, path: &[usize]) -> bool {
379        self.active
380            .as_ref()
381            .and_then(|active| active.hover.as_ref())
382            .is_some_and(|over| over.target.path == path && over.target.matches_node(node))
383    }
384
385    pub fn motion(
386        &mut self,
387        context: Context<'_>,
388        point: Point,
389        requested: Option<DragAction>,
390        now: Instant,
391    ) -> (DragUpdate, bool) {
392        self.point = point;
393        let mut update = DragUpdate::default();
394        if self.active.is_none() {
395            let Some(source) = context.node(&self.source, "DragArea") else {
396                return (update, false);
397            };
398            if (point.x - self.origin.x).hypot(point.y - self.origin.y) < THRESHOLD {
399                return (update, true);
400            }
401            if self
402                .touch_hold
403                .is_some_and(|(started, delay)| now.saturating_duration_since(started) < delay)
404            {
405                return (update, false);
406            }
407            let Some(offer) = Offer::from_node(source) else {
408                return (update, false);
409            };
410            self.virtual_source = VirtualSource::capture(&context, &self.source);
411            self.active = Some(Active {
412                offer,
413                hover: None,
414                scroll_wake: now + SCROLL_FRAME_INTERVAL,
415                rehit_after_scroll: false,
416            });
417            send(&mut update, &self.source, DragEvent::Started);
418        } else if !self.source_is_current(&context) {
419            return (self.cancel(), false);
420        }
421        update.captured = true;
422        let Some(active) = &mut self.active else {
423            return (update, false);
424        };
425        let next = context.hover(&active.offer, point, requested);
426        active.update_hover(next, context.scene, &mut update);
427        (update, true)
428    }
429
430    pub fn reconcile(
431        &mut self,
432        context: Context<'_>,
433        point: Point,
434        requested: Option<DragAction>,
435    ) -> (DragUpdate, bool) {
436        if !self.source_is_current(&context) {
437            return (self.cancel(), false);
438        }
439        let mut update = DragUpdate::default();
440        if let Some(active) = &mut self.active
441            && (active.rehit_after_scroll || active.hover.is_some())
442        {
443            let next = context.hover(&active.offer, point, requested);
444            let same_destination = active
445                .hover
446                .as_ref()
447                .zip(next.as_ref())
448                .filter(|(old, next)| old.same_destination(next));
449            let relocated = same_destination.is_some_and(|(old, next)| old.target != next.target);
450            if std::mem::take(&mut active.rehit_after_scroll) || relocated {
451                active.update_hover(next, context.scene, &mut update);
452            } else if same_destination.is_none() {
453                active.leave_hover(&mut update);
454            }
455        }
456        (update, true)
457    }
458
459    pub fn finish(
460        mut self,
461        context: Context<'_>,
462        point: Point,
463        requested: Option<DragAction>,
464    ) -> DragUpdate {
465        if !self.active() {
466            return DragUpdate::default();
467        }
468        let (mut update, valid) = self.motion(context, point, requested, Instant::now());
469        if !valid {
470            return update;
471        }
472        let Some(active) = self.active.take() else {
473            return update;
474        };
475        let action = active.hover.map_or(DragAction::None, |over| {
476            send(
477                &mut update,
478                &over.target,
479                DragEvent::Dropped {
480                    data: active.offer.data,
481                    action: over.action,
482                },
483            );
484            over.action
485        });
486        self.send_finished(&mut update, action);
487        update
488    }
489
490    pub fn cancel(&mut self) -> DragUpdate {
491        let Some(mut active) = self.active.take() else {
492            return DragUpdate::default();
493        };
494        let mut update = DragUpdate {
495            captured: true,
496            events: Vec::new(),
497        };
498        active.leave_hover(&mut update);
499        self.send_finished(&mut update, DragAction::None);
500        update
501    }
502
503    fn source_is_current(&self, context: &Context<'_>) -> bool {
504        if let Some(source) = &self.virtual_source {
505            return source.is_current(context, &self.source);
506        }
507        context.node(&self.source, "DragArea").is_some()
508    }
509
510    fn send_finished(&self, update: &mut DragUpdate, action: DragAction) {
511        // Cleanup events resolve the captured row even after its display slot has been recycled.
512        let captured_scene = self
513            .virtual_source
514            .as_ref()
515            .map(|source| source.scene.clone());
516        update.events.push(DragDispatch {
517            target: self.source.clone(),
518            event: DragEvent::Finished(action),
519            captured_scene,
520        });
521    }
522
523    pub fn auto_scroll_offset(&self, context: Context<'_>) -> Option<(&[usize], f32)> {
524        let target = &self.active.as_ref()?.hover.as_ref()?.target;
525        if !target.path.starts_with(context.scope) {
526            return None;
527        }
528        context.node(target, "DropArea")?;
529        (context.scope.len()..target.path.len())
530            .rev()
531            .find_map(|depth| {
532                let path = &target.path[..depth];
533                let node = context.scene.at_path(path)?;
534                if !node.boolean("drag-auto-scroll", false) {
535                    return None;
536                }
537                let layout = context.layout.at_path(path)?;
538                let point = layout.map_from_window(self.point)?;
539                let rect = layout.clip_rect(layout.scroll_viewport(Orientation::Vertical));
540                if !rect.contains(point) {
541                    return None;
542                }
543                let scroll = layout.scroll?;
544                let offset = (scroll.offset + edge_delta(point.y, rect.y, rect.height))
545                    .clamp(0.0, scroll.max_offset);
546                (offset != scroll.offset).then_some((path, offset))
547            })
548    }
549
550    pub fn scroll_deadline(&self) -> Option<Instant> {
551        self.active.as_ref().map(|active| active.scroll_wake)
552    }
553
554    pub fn advance_scroll_deadline(&mut self, now: Instant, scrolled: bool) {
555        if let Some(active) = &mut self.active {
556            active.scroll_wake = now + SCROLL_FRAME_INTERVAL;
557            active.rehit_after_scroll |= scrolled;
558        }
559    }
560}
561
562impl Active {
563    fn leave_hover(&mut self, update: &mut DragUpdate) {
564        if let Some(old) = self.hover.take() {
565            update.events.push(DragDispatch {
566                target: old.target,
567                event: DragEvent::Exited,
568                captured_scene: old.captured_scene,
569            });
570        }
571    }
572
573    fn update_hover(&mut self, mut next: Option<Hover>, scene: &Node, update: &mut DragUpdate) {
574        let same_target = self
575            .hover
576            .as_ref()
577            .zip(next.as_ref())
578            .is_some_and(|(last, next)| last.same_destination(next));
579        if !same_target {
580            self.leave_hover(update);
581            if let Some(next) = &next {
582                send(
583                    update,
584                    &next.target,
585                    DragEvent::Entered {
586                        data: self.offer.data.clone(),
587                        action: next.action,
588                    },
589                );
590            }
591        }
592        if let Some(next) = &mut next {
593            if next.target.row_key.is_some() {
594                next.captured_scene = self
595                    .hover
596                    .as_ref()
597                    .filter(|old| old.target == next.target)
598                    .and_then(|old| old.captured_scene.clone())
599                    .or_else(|| Some(Rc::new(scene.clone())));
600            }
601            if self
602                .hover
603                .as_ref()
604                .is_none_or(|old| old.local != next.local)
605            {
606                send(
607                    update,
608                    &next.target,
609                    DragEvent::Moved {
610                        x: Length(next.local.x.into()),
611                        y: Length(next.local.y.into()),
612                    },
613                );
614            }
615        }
616        self.hover = next;
617    }
618}