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};
pub const MAX_DROPPED_FILES: usize = MAX_DRAG_FILES;
pub const NV_INTERNAL_DRAG_MIME: &str = "application/x-nv-drag";
#[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",
}
}
#[inline]
pub const fn effect_allowed_web_str(_effect: DropEffect) -> &'static str {
"all"
}
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,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DragHoverTransition {
pub resolved_effect: DropEffect,
pub exited: Vec<NodeId>,
pub entered: Vec<NodeId>,
pub clear_external_session: bool,
}
#[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,
}
}
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,
}
}
#[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)
}
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(),
}
}
#[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);
#[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(),
}
}
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
}
#[inline]
pub fn peek(&self, id: u64) -> Option<&T> {
self.entries.iter().find_map(|(k, v)| (*k == id).then_some(v))
}
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();
}
}
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
}
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)
}
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
}
#[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
}
#[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
);
}
}