Skip to main content

nativeview_engine/drag/
mod.rs

1//! Platform-agnostic drag-and-drop state, accept-mask matching, bounded LRU dropped-file
2//! handle registry (`max 256`), and non-flickering ancestor enter/leave diffing.
3
4mod contributor;
5
6pub use contributor::{DragPayloadContributor, DragPayloadRegistry};
7
8use std::collections::VecDeque;
9
10use nativeview_abi::{
11    DragEventMeta, DragOutcomeFlags, DragPayload, DragSessionId, DragSourceKind, NodeId,
12    starts_with_ignore_ascii_case, MAX_DRAG_FILES,
13};
14use nativeview_tables::tables::{DragAcceptMask, DropEffect};
15
16/// Hard cap on live sandboxed browser `File` handles retained in [`DroppedFileLru`].
17pub const MAX_DROPPED_FILES: usize = MAX_DRAG_FILES;
18
19/// Internal MIME token stamped onto `DataTransfer` during in-app HTML5 drags.
20pub const NV_INTERNAL_DRAG_MIME: &str = "application/x-nv-drag";
21
22/// Canonical W3C `DataTransfer.dropEffect` keyword.
23#[inline]
24pub const fn drop_effect_web_str(effect: DropEffect) -> &'static str {
25    match effect {
26        DropEffect::None => "none",
27        DropEffect::Copy => "copy",
28        DropEffect::Move => "move",
29        DropEffect::Link => "link",
30    }
31}
32
33/// Canonical W3C `DataTransfer.effectAllowed` keyword for internal drags.
34///
35/// Emits `"all"` (matching `allowed_effects: 0x07` in `DragEventMeta`) so internal `<Draggable>`
36/// sources (default `Move`) can drop cleanly onto `<DropZone>` targets (default `Copy`) without
37/// browsers rejecting the gesture on `effectAllowed`/`dropEffect` mismatch.
38#[inline]
39pub const fn effect_allowed_web_str(_effect: DropEffect) -> &'static str {
40    "all"
41}
42
43/// Aligns a drop zone's preferred `requested` [`DropEffect`] against the browser's active
44/// `DataTransfer.effectAllowed` keyword so `dt.dropEffect` is always permitted by the source.
45///
46/// On synthetic (untrusted) `new DataTransfer()` events, Chromium/WebKit lock `effectAllowed` to
47/// `"none"` and ignore writes to it; when `is_trusted == false` and `effect_allowed == "none"`,
48/// fall back to `requested` while still honoring `"none"` on real trusted browser drags and
49/// constraining any explicit `"copy"`/`"move"`/`"link"` combinations in both modes.
50pub fn resolve_allowed_drop_effect(
51    requested: DropEffect,
52    effect_allowed: &str,
53    is_trusted: bool,
54) -> DropEffect {
55    let want = match requested {
56        DropEffect::None => DropEffect::Copy,
57        other => other,
58    };
59    let s = effect_allowed.trim();
60    if s.is_empty() || s.eq_ignore_ascii_case("all") || s.eq_ignore_ascii_case("uninitialized") {
61        return want;
62    }
63    if s.eq_ignore_ascii_case("none") {
64        return if is_trusted { DropEffect::None } else { want };
65    }
66    let allow_copy = s.eq_ignore_ascii_case("copy")
67        || s.eq_ignore_ascii_case("copyMove")
68        || s.eq_ignore_ascii_case("copyLink");
69    let allow_move = s.eq_ignore_ascii_case("move")
70        || s.eq_ignore_ascii_case("copyMove")
71        || s.eq_ignore_ascii_case("linkMove");
72    let allow_link = s.eq_ignore_ascii_case("link")
73        || s.eq_ignore_ascii_case("copyLink")
74        || s.eq_ignore_ascii_case("linkMove");
75    match want {
76        DropEffect::Copy if allow_copy => DropEffect::Copy,
77        DropEffect::Move if allow_move => DropEffect::Move,
78        DropEffect::Link if allow_link => DropEffect::Link,
79        _ if allow_copy => DropEffect::Copy,
80        _ if allow_move => DropEffect::Move,
81        _ if allow_link => DropEffect::Link,
82        _ => DropEffect::None,
83    }
84}
85
86/// Pure enter/leave reconciliation plan for one Web `dragenter` / `dragover` step.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct DragHoverTransition {
89    /// Resolved [`DropEffect`] (`DropEffect::None` when rejected or no matching drop targets).
90    pub resolved_effect: DropEffect,
91    /// Previously entered nodes that are now exited (always emitted with `DropEffect::None`).
92    pub exited: Vec<NodeId>,
93    /// Newly entered nodes (always emitted with `resolved_effect`; empty when rejected).
94    pub entered: Vec<NodeId>,
95    /// Whether an active external OS drag session should be cleared after reconciliation.
96    pub clear_external_session: bool,
97}
98
99/// Resolves the effective [`DropEffect`] for the innermost matched drop target (or
100/// `DropEffect::None` when no drop target matched or the drag source disallowed all effects).
101#[inline]
102pub fn resolve_matched_drop_effect(
103    first_requested: Option<DropEffect>,
104    effect_allowed: Option<&str>,
105    is_trusted: bool,
106) -> DropEffect {
107    match first_requested {
108        Some(req) => match effect_allowed {
109            Some(allowed) => resolve_allowed_drop_effect(req, allowed, is_trusted),
110            None => match req {
111                DropEffect::None => DropEffect::Copy,
112                other => other,
113            },
114        },
115        None => DropEffect::None,
116    }
117}
118
119/// Resolves the effective drop effect and enter/leave diff for a `dragenter`/`dragover` event.
120///
121/// Guarantees:
122/// - Rejected targets (`resolved_effect == DropEffect::None`, e.g. trusted `effectAllowed == "none"`)
123///   produce zero entered targets (preventing `[data-nv-drag-over]` flicker and spurious `DragEnter`)
124///   while cleanly exiting any previously entered targets.
125/// - External OS sessions are cleared whenever the resulting entered chain is empty.
126pub fn plan_drag_hover_transition(
127    prev_entered: &[NodeId],
128    matched_ids: &[NodeId],
129    first_requested: Option<DropEffect>,
130    effect_allowed: Option<&str>,
131    is_trusted: bool,
132    source_kind: DragSourceKind,
133) -> DragHoverTransition {
134    let resolved_effect = resolve_matched_drop_effect(first_requested, effect_allowed, is_trusted);
135    let effective_next: &[NodeId] = if resolved_effect == DropEffect::None {
136        &[]
137    } else {
138        matched_ids
139    };
140    let (exited, entered) = diff_drag_enter_leave(prev_entered, effective_next);
141    let clear_external_session =
142        source_kind == DragSourceKind::ExternalOs && effective_next.is_empty();
143    DragHoverTransition {
144        resolved_effect,
145        exited,
146        entered,
147        clear_external_session,
148    }
149}
150
151/// Builds separate `(leave_meta, enter_meta)` headers for enter/leave reconciliation:
152/// `DragLeave` always carries `DropEffect::None`, while `DragEnter` carries `resolved_effect`.
153#[inline]
154pub const fn drag_enter_leave_metas(
155    session_id: DragSessionId,
156    source_kind: DragSourceKind,
157    source_node: NodeId,
158    item_count: u32,
159    resolved_effect: DropEffect,
160) -> (DragEventMeta, DragEventMeta) {
161    let leave_meta = DragEventMeta {
162        session_id,
163        source_kind,
164        drop_effect: DropEffect::None.as_u8(),
165        allowed_effects: 0x07,
166        outcome_flags: DragOutcomeFlags::EMPTY,
167        source_node,
168        item_count,
169    };
170    let enter_meta = DragEventMeta {
171        drop_effect: resolved_effect.as_u8(),
172        ..leave_meta
173    };
174    (leave_meta, enter_meta)
175}
176
177/// Builds a canonical [`DragPayload`] from an internal draggable node's `(mime, data)` pair,
178/// matching `skia-shell` (`text/uri-list` -> `uris` + `text`, `text/*` -> `text`, custom MIME ->
179/// `custom` bytes) uniformly across `DragStart`, `DragEnter`, and `Drop`.
180pub fn build_internal_drag_payload(mime: &str, data: &str) -> DragPayload {
181    let effective_mime = if mime.is_empty() { "text/plain" } else { mime };
182    let is_uri_list = effective_mime.eq_ignore_ascii_case("text/uri-list");
183    let is_text = starts_with_ignore_ascii_case(effective_mime, "text/");
184    let uris = if is_uri_list && !data.is_empty() {
185        parse_uri_list(data, MAX_DRAG_FILES)
186    } else {
187        Vec::new()
188    };
189    let text = if is_text && !data.is_empty() {
190        Some(data.to_owned())
191    } else {
192        None
193    };
194    let custom = if !is_text && !data.is_empty() {
195        data.as_bytes().to_vec()
196    } else {
197        Vec::new()
198    };
199    DragPayload {
200        mime: effective_mime.to_owned(),
201        text,
202        uris,
203        custom,
204        files: Vec::new(),
205    }
206}
207
208/// Compact 1-byte mirrored per-node drag metadata stored in `WebEventState`:
209/// - bit 0: `draggable`
210/// - bits 1..=5: `DragAcceptMask` (5 bits)
211/// - bits 6..=7: `DropEffect` (2 bits)
212#[repr(transparent)]
213#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
214pub struct DragNodeMeta(u8);
215
216impl DragNodeMeta {
217    pub const EMPTY: Self = Self(0);
218
219    #[inline(always)]
220    pub const fn from_parts(
221        draggable: bool,
222        accept: DragAcceptMask,
223        drop_effect: DropEffect,
224    ) -> Self {
225        let b0 = if draggable { 1u8 } else { 0u8 };
226        let b1_5 = (accept.bits() & 0x1F) << 1;
227        let b6_7 = (drop_effect.as_u8() & 0x03) << 6;
228        Self(b0 | b1_5 | b6_7)
229    }
230
231    #[inline(always)]
232    pub const fn is_empty(self) -> bool {
233        self.0 == 0
234    }
235
236    #[inline(always)]
237    pub const fn is_draggable(self) -> bool {
238        (self.0 & 1) != 0
239    }
240
241    #[inline(always)]
242    pub const fn accept(self) -> DragAcceptMask {
243        DragAcceptMask::from_bits_truncate((self.0 >> 1) & 0x1F)
244    }
245
246    #[inline(always)]
247    pub const fn drop_effect(self) -> DropEffect {
248        match DropEffect::try_from_word(((self.0 >> 6) & 0x03) as u32) {
249            Some(v) => v,
250            None => DropEffect::None,
251        }
252    }
253
254    #[inline(always)]
255    pub const fn is_drop_target(self) -> bool {
256        !self.accept().is_empty()
257    }
258}
259
260#[repr(transparent)]
261#[derive(Debug, Clone, Copy, PartialEq, Eq)]
262struct DroppedFileSeq(u64);
263
264/// Bounded monotonic-ID LRU registry (`max 256`) holding sandboxed dropped file handles.
265#[derive(Debug, Clone)]
266pub struct DroppedFileLru<T> {
267    next_id: DroppedFileSeq,
268    cap: usize,
269    entries: VecDeque<(u64, T)>,
270}
271
272impl<T> Default for DroppedFileLru<T> {
273    fn default() -> Self {
274        Self::new()
275    }
276}
277
278impl<T> DroppedFileLru<T> {
279    pub fn new() -> Self {
280        Self::with_capacity(MAX_DROPPED_FILES)
281    }
282
283    pub fn with_capacity(cap: usize) -> Self {
284        let cap = cap.max(1);
285        Self {
286            next_id: DroppedFileSeq(1),
287            cap,
288            entries: VecDeque::new(),
289        }
290    }
291
292    /// Inserts `item` under a fresh monotonic handle ID, evicting the least-recently-used entry
293    /// when at capacity.
294    pub fn insert(&mut self, item: T) -> u64 {
295        let id = self.next_id.0;
296        self.next_id.0 = self.next_id.0.wrapping_add(1).max(1);
297        if self.entries.len() >= self.cap {
298            self.entries.pop_front();
299        }
300        self.entries.push_back((id, item));
301        id
302    }
303
304    /// Looks up `id` without modifying LRU order.
305    #[inline]
306    pub fn peek(&self, id: u64) -> Option<&T> {
307        self.entries.iter().find_map(|(k, v)| (*k == id).then_some(v))
308    }
309
310    /// Looks up `id` and promotes it to most-recently-used.
311    pub fn get(&mut self, id: u64) -> Option<&T> {
312        let pos = self.entries.iter().position(|(k, _)| *k == id)?;
313        if pos + 1 < self.entries.len()
314            && let Some(entry) = self.entries.remove(pos)
315        {
316            self.entries.push_back(entry);
317        }
318        self.entries.back().map(|(_, v)| v)
319    }
320
321    pub fn remove(&mut self, id: u64) -> Option<T> {
322        let pos = self.entries.iter().position(|(k, _)| *k == id)?;
323        self.entries.remove(pos).map(|(_, v)| v)
324    }
325
326    #[inline]
327    pub fn len(&self) -> usize {
328        self.entries.len()
329    }
330
331    #[inline]
332    pub fn is_empty(&self) -> bool {
333        self.entries.is_empty()
334    }
335
336    #[inline]
337    pub fn clear(&mut self) {
338        self.entries.clear();
339    }
340}
341
342/// Synchronous `dragover`/`dragenter`/`drop` accept check against mirrored [`DragAcceptMask`].
343pub fn data_transfer_matches_accept(
344    accept: DragAcceptMask,
345    is_internal: bool,
346    has_files: bool,
347    dt_types: &[&str],
348) -> bool {
349    if accept.is_empty() {
350        return false;
351    }
352    if is_internal && accept.contains(DragAcceptMask::INTERNAL) {
353        return true;
354    }
355    if has_files && accept.contains(DragAcceptMask::FILES) {
356        return true;
357    }
358    for &ty in dt_types {
359        if ty.eq_ignore_ascii_case("Files") {
360            if accept.contains(DragAcceptMask::FILES) {
361                return true;
362            }
363        } else if ty.eq_ignore_ascii_case("text/plain") {
364            if accept.contains(DragAcceptMask::TEXT) {
365                return true;
366            }
367        } else if ty.eq_ignore_ascii_case("text/uri-list") {
368            if accept.contains(DragAcceptMask::URI_LIST) {
369                return true;
370            }
371        } else if ty.eq_ignore_ascii_case(NV_INTERNAL_DRAG_MIME) {
372            if accept.contains(DragAcceptMask::INTERNAL) {
373                return true;
374            }
375        } else if !ty.is_empty() && accept.contains(DragAcceptMask::CUSTOM) {
376            return true;
377        }
378    }
379    false
380}
381
382/// Computes `(exited_bottom_up, entered_top_down)` between previous and next drop-zone chains.
383/// Crossing into a child element inside the same drop zone leaves both slices empty (0 flicker).
384pub fn diff_drag_enter_leave(prev: &[NodeId], next: &[NodeId]) -> (Vec<NodeId>, Vec<NodeId>) {
385    let mut exited = Vec::new();
386    for &id in prev {
387        if !next.contains(&id) {
388            exited.push(id);
389        }
390    }
391    let mut entered = Vec::new();
392    for &id in next.iter().rev() {
393        if !prev.contains(&id) {
394            entered.push(id);
395        }
396    }
397    (exited, entered)
398}
399
400/// Parses an RFC 2483 `text/uri-list` payload, skipping `#` comments and blank lines, capped at `max`.
401pub fn parse_uri_list(raw: &str, max: usize) -> Vec<String> {
402    let mut out = Vec::new();
403    for line in raw.lines() {
404        let trimmed = line.trim();
405        if trimmed.is_empty() || trimmed.starts_with('#') {
406            continue;
407        }
408        if out.len() >= max {
409            break;
410        }
411        out.push(trimmed.to_owned());
412    }
413    out
414}
415
416/// Returns whether a [`DragPayload`] satisfies a drop target's `DragAcceptMask`.
417#[inline]
418pub fn payload_matches_accept(mask: DragAcceptMask, payload: &DragPayload) -> bool {
419    if mask.is_empty() {
420        return false;
421    }
422    if mask.contains(DragAcceptMask::INTERNAL) && !payload.mime.is_empty() {
423        return true;
424    }
425    if mask.contains(DragAcceptMask::TEXT) && payload.text.as_deref().is_some_and(|s| !s.is_empty()) {
426        return true;
427    }
428    if mask.contains(DragAcceptMask::URI_LIST) && !payload.uris.is_empty() {
429        return true;
430    }
431    if mask.contains(DragAcceptMask::FILES) && !payload.files.is_empty() {
432        return true;
433    }
434    if mask.contains(DragAcceptMask::CUSTOM) && !payload.custom.is_empty() {
435        return true;
436    }
437    false
438}
439
440/// Resolves the effective drop effect from the source's allowed mask and the target's preferred
441/// effect (falling back to `Copy`).
442#[inline]
443pub fn effective_drop_effect(allowed_mask: u8, preferred: DropEffect) -> DropEffect {
444    let bit = |e: DropEffect| 1u8 << e.as_u8();
445    if preferred != DropEffect::None && (allowed_mask & bit(preferred)) != 0 {
446        preferred
447    } else if (allowed_mask & bit(DropEffect::Copy)) != 0 {
448        DropEffect::Copy
449    } else if (allowed_mask & bit(DropEffect::Move)) != 0 {
450        DropEffect::Move
451    } else if (allowed_mask & bit(DropEffect::Link)) != 0 {
452        DropEffect::Link
453    } else {
454        DropEffect::Copy
455    }
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461
462    #[test]
463    fn drag_hover_transition_diff_and_payload() {
464        let a = NodeId::new(1, 1);
465        let b = NodeId::new(2, 1);
466        let tr = plan_drag_hover_transition(
467            &[a],
468            &[a, b],
469            Some(DropEffect::Copy),
470            Some("copyMove"),
471            true,
472            DragSourceKind::Internal,
473        );
474        assert_eq!(tr.resolved_effect, DropEffect::Copy);
475        assert!(tr.exited.is_empty());
476        assert_eq!(tr.entered, vec![b]);
477
478        let p = build_internal_drag_payload("text/uri-list", "# comment\nhttps://a.test\nhttps://b.test");
479        assert_eq!(p.uris, vec!["https://a.test", "https://b.test"]);
480        assert!(data_transfer_matches_accept(DragAcceptMask::FILES, false, true, &[]));
481    }
482
483    #[test]
484    fn drag_node_meta_bit_packing_roundtrip() {
485        let m = DragNodeMeta::from_parts(
486            true,
487            DragAcceptMask::TEXT | DragAcceptMask::FILES,
488            DropEffect::Move,
489        );
490        assert!(m.is_draggable());
491        assert!(m.is_drop_target());
492        assert_eq!(m.accept(), DragAcceptMask::TEXT | DragAcceptMask::FILES);
493        assert_eq!(m.drop_effect(), DropEffect::Move);
494        assert!(!DragNodeMeta::EMPTY.is_draggable());
495        assert!(!DragNodeMeta::EMPTY.is_drop_target());
496    }
497
498    #[test]
499    fn dropped_file_lru_evicts_oldest_beyond_256_and_get_refreshes_unlike_peek() {
500        let mut lru: DroppedFileLru<u32> = DroppedFileLru::new();
501        let mut keys = Vec::with_capacity(256);
502        for i in 0..256u32 {
503            keys.push(lru.insert(i));
504        }
505        assert_eq!(lru.len(), 256);
506        assert_eq!(lru.peek(keys[0]), Some(&0));
507        assert_eq!(lru.get(keys[0]), Some(&0));
508        let _ = lru.insert(256);
509        assert_eq!(lru.len(), 256);
510        assert_eq!(lru.peek(keys[0]), Some(&0), "get() refreshed oldest key");
511        assert_eq!(lru.peek(keys[1]), None, "second key became oldest and evicted");
512    }
513
514    #[test]
515    fn payload_matches_accept_and_effective_drop_effect() {
516        let text = build_internal_drag_payload("text/plain", "hello");
517        assert!(payload_matches_accept(DragAcceptMask::TEXT, &text));
518        assert!(!payload_matches_accept(DragAcceptMask::FILES, &text));
519        assert!(!payload_matches_accept(DragAcceptMask::NONE, &text));
520
521        let allowed = (1u8 << DropEffect::Copy.as_u8()) | (1u8 << DropEffect::Move.as_u8());
522        assert_eq!(effective_drop_effect(allowed, DropEffect::Move), DropEffect::Move);
523        assert_eq!(effective_drop_effect(allowed, DropEffect::Link), DropEffect::Copy);
524        assert_eq!(
525            effective_drop_effect(1u8 << DropEffect::Move.as_u8(), DropEffect::Link),
526            DropEffect::Move
527        );
528    }
529}
530