nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! Platform-agnostic drag-and-drop state, accept-mask matching, bounded LRU dropped-file
//! handle registry (`max 256`), and non-flickering ancestor enter/leave diffing.

mod contributor;

pub use contributor::{DragPayloadContributor, DragPayloadRegistry};

use std::collections::VecDeque;

use nativeview_abi::{
    DragEventMeta, DragOutcomeFlags, DragPayload, DragSessionId, DragSourceKind, NodeId,
    starts_with_ignore_ascii_case, MAX_DRAG_FILES,
};
use nativeview_tables::tables::{DragAcceptMask, DropEffect};

/// Hard cap on live sandboxed browser `File` handles retained in [`DroppedFileLru`].
pub const MAX_DROPPED_FILES: usize = MAX_DRAG_FILES;

/// Internal MIME token stamped onto `DataTransfer` during in-app HTML5 drags.
pub const NV_INTERNAL_DRAG_MIME: &str = "application/x-nv-drag";

/// Canonical W3C `DataTransfer.dropEffect` keyword.
#[inline]
pub const fn drop_effect_web_str(effect: DropEffect) -> &'static str {
    match effect {
        DropEffect::None => "none",
        DropEffect::Copy => "copy",
        DropEffect::Move => "move",
        DropEffect::Link => "link",
    }
}

/// Canonical W3C `DataTransfer.effectAllowed` keyword for internal drags.
///
/// Emits `"all"` (matching `allowed_effects: 0x07` in `DragEventMeta`) so internal `<Draggable>`
/// sources (default `Move`) can drop cleanly onto `<DropZone>` targets (default `Copy`) without
/// browsers rejecting the gesture on `effectAllowed`/`dropEffect` mismatch.
#[inline]
pub const fn effect_allowed_web_str(_effect: DropEffect) -> &'static str {
    "all"
}

/// Aligns a drop zone's preferred `requested` [`DropEffect`] against the browser's active
/// `DataTransfer.effectAllowed` keyword so `dt.dropEffect` is always permitted by the source.
///
/// On synthetic (untrusted) `new DataTransfer()` events, Chromium/WebKit lock `effectAllowed` to
/// `"none"` and ignore writes to it; when `is_trusted == false` and `effect_allowed == "none"`,
/// fall back to `requested` while still honoring `"none"` on real trusted browser drags and
/// constraining any explicit `"copy"`/`"move"`/`"link"` combinations in both modes.
pub fn resolve_allowed_drop_effect(
    requested: DropEffect,
    effect_allowed: &str,
    is_trusted: bool,
) -> DropEffect {
    let want = match requested {
        DropEffect::None => DropEffect::Copy,
        other => other,
    };
    let s = effect_allowed.trim();
    if s.is_empty() || s.eq_ignore_ascii_case("all") || s.eq_ignore_ascii_case("uninitialized") {
        return want;
    }
    if s.eq_ignore_ascii_case("none") {
        return if is_trusted { DropEffect::None } else { want };
    }
    let allow_copy = s.eq_ignore_ascii_case("copy")
        || s.eq_ignore_ascii_case("copyMove")
        || s.eq_ignore_ascii_case("copyLink");
    let allow_move = s.eq_ignore_ascii_case("move")
        || s.eq_ignore_ascii_case("copyMove")
        || s.eq_ignore_ascii_case("linkMove");
    let allow_link = s.eq_ignore_ascii_case("link")
        || s.eq_ignore_ascii_case("copyLink")
        || s.eq_ignore_ascii_case("linkMove");
    match want {
        DropEffect::Copy if allow_copy => DropEffect::Copy,
        DropEffect::Move if allow_move => DropEffect::Move,
        DropEffect::Link if allow_link => DropEffect::Link,
        _ if allow_copy => DropEffect::Copy,
        _ if allow_move => DropEffect::Move,
        _ if allow_link => DropEffect::Link,
        _ => DropEffect::None,
    }
}

/// Pure enter/leave reconciliation plan for one Web `dragenter` / `dragover` step.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DragHoverTransition {
    /// Resolved [`DropEffect`] (`DropEffect::None` when rejected or no matching drop targets).
    pub resolved_effect: DropEffect,
    /// Previously entered nodes that are now exited (always emitted with `DropEffect::None`).
    pub exited: Vec<NodeId>,
    /// Newly entered nodes (always emitted with `resolved_effect`; empty when rejected).
    pub entered: Vec<NodeId>,
    /// Whether an active external OS drag session should be cleared after reconciliation.
    pub clear_external_session: bool,
}

/// Resolves the effective [`DropEffect`] for the innermost matched drop target (or
/// `DropEffect::None` when no drop target matched or the drag source disallowed all effects).
#[inline]
pub fn resolve_matched_drop_effect(
    first_requested: Option<DropEffect>,
    effect_allowed: Option<&str>,
    is_trusted: bool,
) -> DropEffect {
    match first_requested {
        Some(req) => match effect_allowed {
            Some(allowed) => resolve_allowed_drop_effect(req, allowed, is_trusted),
            None => match req {
                DropEffect::None => DropEffect::Copy,
                other => other,
            },
        },
        None => DropEffect::None,
    }
}

/// Resolves the effective drop effect and enter/leave diff for a `dragenter`/`dragover` event.
///
/// Guarantees:
/// - Rejected targets (`resolved_effect == DropEffect::None`, e.g. trusted `effectAllowed == "none"`)
///   produce zero entered targets (preventing `[data-nv-drag-over]` flicker and spurious `DragEnter`)
///   while cleanly exiting any previously entered targets.
/// - External OS sessions are cleared whenever the resulting entered chain is empty.
pub fn plan_drag_hover_transition(
    prev_entered: &[NodeId],
    matched_ids: &[NodeId],
    first_requested: Option<DropEffect>,
    effect_allowed: Option<&str>,
    is_trusted: bool,
    source_kind: DragSourceKind,
) -> DragHoverTransition {
    let resolved_effect = resolve_matched_drop_effect(first_requested, effect_allowed, is_trusted);
    let effective_next: &[NodeId] = if resolved_effect == DropEffect::None {
        &[]
    } else {
        matched_ids
    };
    let (exited, entered) = diff_drag_enter_leave(prev_entered, effective_next);
    let clear_external_session =
        source_kind == DragSourceKind::ExternalOs && effective_next.is_empty();
    DragHoverTransition {
        resolved_effect,
        exited,
        entered,
        clear_external_session,
    }
}

/// Builds separate `(leave_meta, enter_meta)` headers for enter/leave reconciliation:
/// `DragLeave` always carries `DropEffect::None`, while `DragEnter` carries `resolved_effect`.
#[inline]
pub const fn drag_enter_leave_metas(
    session_id: DragSessionId,
    source_kind: DragSourceKind,
    source_node: NodeId,
    item_count: u32,
    resolved_effect: DropEffect,
) -> (DragEventMeta, DragEventMeta) {
    let leave_meta = DragEventMeta {
        session_id,
        source_kind,
        drop_effect: DropEffect::None.as_u8(),
        allowed_effects: 0x07,
        outcome_flags: DragOutcomeFlags::EMPTY,
        source_node,
        item_count,
    };
    let enter_meta = DragEventMeta {
        drop_effect: resolved_effect.as_u8(),
        ..leave_meta
    };
    (leave_meta, enter_meta)
}

/// Builds a canonical [`DragPayload`] from an internal draggable node's `(mime, data)` pair,
/// matching `skia-shell` (`text/uri-list` -> `uris` + `text`, `text/*` -> `text`, custom MIME ->
/// `custom` bytes) uniformly across `DragStart`, `DragEnter`, and `Drop`.
pub fn build_internal_drag_payload(mime: &str, data: &str) -> DragPayload {
    let effective_mime = if mime.is_empty() { "text/plain" } else { mime };
    let is_uri_list = effective_mime.eq_ignore_ascii_case("text/uri-list");
    let is_text = starts_with_ignore_ascii_case(effective_mime, "text/");
    let uris = if is_uri_list && !data.is_empty() {
        parse_uri_list(data, MAX_DRAG_FILES)
    } else {
        Vec::new()
    };
    let text = if is_text && !data.is_empty() {
        Some(data.to_owned())
    } else {
        None
    };
    let custom = if !is_text && !data.is_empty() {
        data.as_bytes().to_vec()
    } else {
        Vec::new()
    };
    DragPayload {
        mime: effective_mime.to_owned(),
        text,
        uris,
        custom,
        files: Vec::new(),
    }
}

/// Compact 1-byte mirrored per-node drag metadata stored in `WebEventState`:
/// - bit 0: `draggable`
/// - bits 1..=5: `DragAcceptMask` (5 bits)
/// - bits 6..=7: `DropEffect` (2 bits)
#[repr(transparent)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct DragNodeMeta(u8);

impl DragNodeMeta {
    pub const EMPTY: Self = Self(0);

    #[inline(always)]
    pub const fn from_parts(
        draggable: bool,
        accept: DragAcceptMask,
        drop_effect: DropEffect,
    ) -> Self {
        let b0 = if draggable { 1u8 } else { 0u8 };
        let b1_5 = (accept.bits() & 0x1F) << 1;
        let b6_7 = (drop_effect.as_u8() & 0x03) << 6;
        Self(b0 | b1_5 | b6_7)
    }

    #[inline(always)]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    #[inline(always)]
    pub const fn is_draggable(self) -> bool {
        (self.0 & 1) != 0
    }

    #[inline(always)]
    pub const fn accept(self) -> DragAcceptMask {
        DragAcceptMask::from_bits_truncate((self.0 >> 1) & 0x1F)
    }

    #[inline(always)]
    pub const fn drop_effect(self) -> DropEffect {
        match DropEffect::try_from_word(((self.0 >> 6) & 0x03) as u32) {
            Some(v) => v,
            None => DropEffect::None,
        }
    }

    #[inline(always)]
    pub const fn is_drop_target(self) -> bool {
        !self.accept().is_empty()
    }
}

#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct DroppedFileSeq(u64);

/// Bounded monotonic-ID LRU registry (`max 256`) holding sandboxed dropped file handles.
#[derive(Debug, Clone)]
pub struct DroppedFileLru<T> {
    next_id: DroppedFileSeq,
    cap: usize,
    entries: VecDeque<(u64, T)>,
}

impl<T> Default for DroppedFileLru<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> DroppedFileLru<T> {
    pub fn new() -> Self {
        Self::with_capacity(MAX_DROPPED_FILES)
    }

    pub fn with_capacity(cap: usize) -> Self {
        let cap = cap.max(1);
        Self {
            next_id: DroppedFileSeq(1),
            cap,
            entries: VecDeque::new(),
        }
    }

    /// Inserts `item` under a fresh monotonic handle ID, evicting the least-recently-used entry
    /// when at capacity.
    pub fn insert(&mut self, item: T) -> u64 {
        let id = self.next_id.0;
        self.next_id.0 = self.next_id.0.wrapping_add(1).max(1);
        if self.entries.len() >= self.cap {
            self.entries.pop_front();
        }
        self.entries.push_back((id, item));
        id
    }

    /// Looks up `id` without modifying LRU order.
    #[inline]
    pub fn peek(&self, id: u64) -> Option<&T> {
        self.entries.iter().find_map(|(k, v)| (*k == id).then_some(v))
    }

    /// Looks up `id` and promotes it to most-recently-used.
    pub fn get(&mut self, id: u64) -> Option<&T> {
        let pos = self.entries.iter().position(|(k, _)| *k == id)?;
        if pos + 1 < self.entries.len()
            && let Some(entry) = self.entries.remove(pos)
        {
            self.entries.push_back(entry);
        }
        self.entries.back().map(|(_, v)| v)
    }

    pub fn remove(&mut self, id: u64) -> Option<T> {
        let pos = self.entries.iter().position(|(k, _)| *k == id)?;
        self.entries.remove(pos).map(|(_, v)| v)
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    #[inline]
    pub fn clear(&mut self) {
        self.entries.clear();
    }
}

/// Synchronous `dragover`/`dragenter`/`drop` accept check against mirrored [`DragAcceptMask`].
pub fn data_transfer_matches_accept(
    accept: DragAcceptMask,
    is_internal: bool,
    has_files: bool,
    dt_types: &[&str],
) -> bool {
    if accept.is_empty() {
        return false;
    }
    if is_internal && accept.contains(DragAcceptMask::INTERNAL) {
        return true;
    }
    if has_files && accept.contains(DragAcceptMask::FILES) {
        return true;
    }
    for &ty in dt_types {
        if ty.eq_ignore_ascii_case("Files") {
            if accept.contains(DragAcceptMask::FILES) {
                return true;
            }
        } else if ty.eq_ignore_ascii_case("text/plain") {
            if accept.contains(DragAcceptMask::TEXT) {
                return true;
            }
        } else if ty.eq_ignore_ascii_case("text/uri-list") {
            if accept.contains(DragAcceptMask::URI_LIST) {
                return true;
            }
        } else if ty.eq_ignore_ascii_case(NV_INTERNAL_DRAG_MIME) {
            if accept.contains(DragAcceptMask::INTERNAL) {
                return true;
            }
        } else if !ty.is_empty() && accept.contains(DragAcceptMask::CUSTOM) {
            return true;
        }
    }
    false
}

/// Computes `(exited_bottom_up, entered_top_down)` between previous and next drop-zone chains.
/// Crossing into a child element inside the same drop zone leaves both slices empty (0 flicker).
pub fn diff_drag_enter_leave(prev: &[NodeId], next: &[NodeId]) -> (Vec<NodeId>, Vec<NodeId>) {
    let mut exited = Vec::new();
    for &id in prev {
        if !next.contains(&id) {
            exited.push(id);
        }
    }
    let mut entered = Vec::new();
    for &id in next.iter().rev() {
        if !prev.contains(&id) {
            entered.push(id);
        }
    }
    (exited, entered)
}

/// Parses an RFC 2483 `text/uri-list` payload, skipping `#` comments and blank lines, capped at `max`.
pub fn parse_uri_list(raw: &str, max: usize) -> Vec<String> {
    let mut out = Vec::new();
    for line in raw.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        if out.len() >= max {
            break;
        }
        out.push(trimmed.to_owned());
    }
    out
}

/// Returns whether a [`DragPayload`] satisfies a drop target's `DragAcceptMask`.
#[inline]
pub fn payload_matches_accept(mask: DragAcceptMask, payload: &DragPayload) -> bool {
    if mask.is_empty() {
        return false;
    }
    if mask.contains(DragAcceptMask::INTERNAL) && !payload.mime.is_empty() {
        return true;
    }
    if mask.contains(DragAcceptMask::TEXT) && payload.text.as_deref().is_some_and(|s| !s.is_empty()) {
        return true;
    }
    if mask.contains(DragAcceptMask::URI_LIST) && !payload.uris.is_empty() {
        return true;
    }
    if mask.contains(DragAcceptMask::FILES) && !payload.files.is_empty() {
        return true;
    }
    if mask.contains(DragAcceptMask::CUSTOM) && !payload.custom.is_empty() {
        return true;
    }
    false
}

/// Resolves the effective drop effect from the source's allowed mask and the target's preferred
/// effect (falling back to `Copy`).
#[inline]
pub fn effective_drop_effect(allowed_mask: u8, preferred: DropEffect) -> DropEffect {
    let bit = |e: DropEffect| 1u8 << e.as_u8();
    if preferred != DropEffect::None && (allowed_mask & bit(preferred)) != 0 {
        preferred
    } else if (allowed_mask & bit(DropEffect::Copy)) != 0 {
        DropEffect::Copy
    } else if (allowed_mask & bit(DropEffect::Move)) != 0 {
        DropEffect::Move
    } else if (allowed_mask & bit(DropEffect::Link)) != 0 {
        DropEffect::Link
    } else {
        DropEffect::Copy
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn drag_hover_transition_diff_and_payload() {
        let a = NodeId::new(1, 1);
        let b = NodeId::new(2, 1);
        let tr = plan_drag_hover_transition(
            &[a],
            &[a, b],
            Some(DropEffect::Copy),
            Some("copyMove"),
            true,
            DragSourceKind::Internal,
        );
        assert_eq!(tr.resolved_effect, DropEffect::Copy);
        assert!(tr.exited.is_empty());
        assert_eq!(tr.entered, vec![b]);

        let p = build_internal_drag_payload("text/uri-list", "# comment\nhttps://a.test\nhttps://b.test");
        assert_eq!(p.uris, vec!["https://a.test", "https://b.test"]);
        assert!(data_transfer_matches_accept(DragAcceptMask::FILES, false, true, &[]));
    }

    #[test]
    fn drag_node_meta_bit_packing_roundtrip() {
        let m = DragNodeMeta::from_parts(
            true,
            DragAcceptMask::TEXT | DragAcceptMask::FILES,
            DropEffect::Move,
        );
        assert!(m.is_draggable());
        assert!(m.is_drop_target());
        assert_eq!(m.accept(), DragAcceptMask::TEXT | DragAcceptMask::FILES);
        assert_eq!(m.drop_effect(), DropEffect::Move);
        assert!(!DragNodeMeta::EMPTY.is_draggable());
        assert!(!DragNodeMeta::EMPTY.is_drop_target());
    }

    #[test]
    fn dropped_file_lru_evicts_oldest_beyond_256_and_get_refreshes_unlike_peek() {
        let mut lru: DroppedFileLru<u32> = DroppedFileLru::new();
        let mut keys = Vec::with_capacity(256);
        for i in 0..256u32 {
            keys.push(lru.insert(i));
        }
        assert_eq!(lru.len(), 256);
        assert_eq!(lru.peek(keys[0]), Some(&0));
        assert_eq!(lru.get(keys[0]), Some(&0));
        let _ = lru.insert(256);
        assert_eq!(lru.len(), 256);
        assert_eq!(lru.peek(keys[0]), Some(&0), "get() refreshed oldest key");
        assert_eq!(lru.peek(keys[1]), None, "second key became oldest and evicted");
    }

    #[test]
    fn payload_matches_accept_and_effective_drop_effect() {
        let text = build_internal_drag_payload("text/plain", "hello");
        assert!(payload_matches_accept(DragAcceptMask::TEXT, &text));
        assert!(!payload_matches_accept(DragAcceptMask::FILES, &text));
        assert!(!payload_matches_accept(DragAcceptMask::NONE, &text));

        let allowed = (1u8 << DropEffect::Copy.as_u8()) | (1u8 << DropEffect::Move.as_u8());
        assert_eq!(effective_drop_effect(allowed, DropEffect::Move), DropEffect::Move);
        assert_eq!(effective_drop_effect(allowed, DropEffect::Link), DropEffect::Copy);
        assert_eq!(
            effective_drop_effect(1u8 << DropEffect::Move.as_u8(), DropEffect::Link),
            DropEffect::Move
        );
    }
}