use crate::{GuiError, GuiResult};
pub const MAX_DRAG_PAYLOAD_BYTES: usize = 8 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum DragPayloadKind {
Text,
Custom { mime: String },
}
impl DragPayloadKind {
pub fn mime_type(&self) -> &str {
match self {
Self::Text => "text/plain",
Self::Custom { mime } => mime,
}
}
pub fn normalized(self) -> GuiResult<Self> {
match self {
Self::Text => Ok(Self::Text),
Self::Custom { mime } => Ok(Self::Custom {
mime: normalize_mime(&mime)?,
}),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DragPayload {
Rows { indices: Vec<usize> },
Files { paths: Vec<String> },
Text { text: String },
Custom { mime: String, bytes: Vec<u8> },
}
impl DragPayload {
pub fn normalized(self) -> GuiResult<Self> {
match self {
Self::Text { text } => {
check_payload_size(text.len())?;
Ok(Self::Text { text })
}
Self::Custom { mime, bytes } => {
check_payload_size(bytes.len())?;
Ok(Self::Custom {
mime: normalize_mime(&mime)?,
bytes,
})
}
payload @ (Self::Rows { .. } | Self::Files { .. }) => Ok(payload),
}
}
pub fn kind(&self) -> Option<DragPayloadKind> {
match self {
Self::Text { .. } => Some(DragPayloadKind::Text),
Self::Custom { mime, .. } => Some(DragPayloadKind::Custom { mime: mime.clone() }),
Self::Rows { .. } | Self::Files { .. } => None,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DragCapabilities {
pub text: bool,
pub custom_mime: bool,
pub drop_feedback: bool,
pub preview: bool,
}
impl DragCapabilities {
pub const fn none() -> Self {
Self {
text: false,
custom_mime: false,
drop_feedback: false,
preview: false,
}
}
pub(crate) fn supports_kind(self, kind: &DragPayloadKind) -> bool {
match kind {
DragPayloadKind::Text => self.text,
DragPayloadKind::Custom { .. } => self.custom_mime,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DragSourceOptions {
pub kinds: Vec<DragPayloadKind>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DragTargetOptions {
pub kinds: Vec<DragPayloadKind>,
pub effect: DropEffect,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DragSessionId(pub u64);
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum DropEffect {
#[default]
None,
Copy,
Move,
Link,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DropCancelReason {
Escape,
FocusLost,
SourceRemoved,
OwnerClosed,
BackendFailed,
}
pub(crate) fn normalize_kinds(kinds: Vec<DragPayloadKind>) -> GuiResult<Vec<DragPayloadKind>> {
let mut normalized = Vec::with_capacity(kinds.len());
for kind in kinds {
let kind = kind.normalized()?;
if !normalized.contains(&kind) {
normalized.push(kind);
}
}
Ok(normalized)
}
fn normalize_mime(mime: &str) -> GuiResult<String> {
let mime = mime.trim().to_ascii_lowercase();
let mut parts = mime.split('/');
let top_level = parts.next().unwrap_or_default();
let subtype = parts.next().unwrap_or_default();
let valid_token = |token: &str| {
!token.is_empty()
&& token.bytes().all(|byte| {
byte.is_ascii_alphanumeric()
|| matches!(
byte,
b'!' | b'#' | b'$' | b'&' | b'^' | b'_' | b'.' | b'+' | b'-'
)
})
};
if !valid_token(top_level) || !valid_token(subtype) || parts.next().is_some() {
return Err(GuiError::Backend(format!("Invalid drag MIME type: {mime}")));
}
Ok(mime)
}
fn check_payload_size(size: usize) -> GuiResult<()> {
if size > MAX_DRAG_PAYLOAD_BYTES {
return Err(GuiError::Backend(format!(
"Drag payload exceeds the {MAX_DRAG_PAYLOAD_BYTES}-byte limit"
)));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::MockBackend;
use crate::{Ui, UiEvent, WidgetId, WidgetKind};
fn full_capabilities() -> DragCapabilities {
DragCapabilities {
text: true,
custom_mime: true,
drop_feedback: true,
preview: false,
}
}
fn custom(mime: &str) -> DragPayloadKind {
DragPayloadKind::Custom {
mime: mime.to_owned(),
}
}
fn configured_ui() -> (Ui<MockBackend>, WidgetId, WidgetId) {
let mut ui = Ui::new(MockBackend::default());
let source = ui.create(WidgetKind::ListView, Some("source")).unwrap();
let target = ui.create(WidgetKind::ListView, Some("target")).unwrap();
(ui, source, target)
}
fn configure_source_target(ui: &mut Ui<MockBackend>, source: WidgetId, target: WidgetId) {
ui.set_drag_source(
source,
DragSourceOptions {
kinds: vec![
DragPayloadKind::Text,
custom("application/x-nativegui-test"),
],
},
)
.unwrap();
ui.set_drag_target_options(
target,
DragTargetOptions {
kinds: vec![custom("application/x-nativegui-test")],
effect: DropEffect::Move,
},
)
.unwrap();
}
#[test]
fn source_and_target_options_normalize_mime_without_changing_row_drag_state() {
let (mut ui, source, target) = configured_ui();
ui.set_row_drag(source, true, true).unwrap();
ui.set_drag_source(
source,
DragSourceOptions {
kinds: vec![
custom(" Application/Vnd.Nativegui-Test+Json "),
DragPayloadKind::Text,
custom("application/vnd.nativegui-test+json"),
],
},
)
.unwrap();
ui.set_drag_target_options(
target,
DragTargetOptions {
kinds: vec![custom("APPLICATION/VND.NATIVEGUI-TEST+JSON")],
effect: DropEffect::Copy,
},
)
.unwrap();
assert_eq!(
ui.backend().drag_source_options[&source].kinds,
vec![
custom("application/vnd.nativegui-test+json"),
DragPayloadKind::Text
]
);
assert!(ui.backend().created[&source].row_drag_source);
assert!(ui.backend().created[&source].row_drop_target);
assert_eq!(
ui.backend().drag_target_options[&target].effect,
DropEffect::Copy
);
}
#[test]
fn mock_drag_session_filters_kinds_orders_phases_and_ends_once() {
let (mut ui, source, target) = configured_ui();
configure_source_target(&mut ui, source, target);
let session = ui.backend_mut().mock_start_drag(source).unwrap();
assert_eq!(session, DragSessionId(1));
assert_eq!(
ui.backend_mut().mock_start_drag(source).unwrap_err(),
GuiError::UnsupportedCapability("drag_busy".to_owned())
);
assert!(ui
.backend_mut()
.mock_drag_enter(session, target, (12, 28))
.unwrap());
assert!(ui.backend_mut().mock_drag_move(session, target, (14, 31)));
assert!(ui
.backend_mut()
.mock_drag_drop(
session,
target,
(16, 32),
DragPayload::Custom {
mime: "APPLICATION/X-NATIVEGUI-TEST".to_owned(),
bytes: vec![1, 2, 3],
},
)
.unwrap());
assert!(!ui
.backend_mut()
.mock_cancel_drag(session, DropCancelReason::Escape));
assert_eq!(
ui.poll_event().unwrap(),
Some(UiEvent::DragSessionStarted {
widget_id: source,
session,
kinds: vec![
DragPayloadKind::Text,
custom("application/x-nativegui-test")
],
})
);
assert_eq!(
ui.poll_event().unwrap(),
Some(UiEvent::DragEntered {
target,
session,
position: (12, 28),
offered: vec!["application/x-nativegui-test".to_owned()],
})
);
assert_eq!(
ui.poll_event().unwrap(),
Some(UiEvent::DragMoved {
target,
session,
position: (14, 31),
})
);
assert_eq!(
ui.poll_event().unwrap(),
Some(UiEvent::DragExited { target, session })
);
assert_eq!(
ui.poll_event().unwrap(),
Some(UiEvent::DragDropped {
target,
session,
position: (16, 32),
payload: DragPayload::Custom {
mime: "application/x-nativegui-test".to_owned(),
bytes: vec![1, 2, 3],
},
effect: DropEffect::Move,
})
);
assert_eq!(ui.poll_event().unwrap(), None);
}
#[test]
fn mock_text_drop_preserves_utf8_payload_and_copy_effect() {
let (mut ui, source, target) = configured_ui();
ui.set_drag_source(
source,
DragSourceOptions {
kinds: vec![DragPayloadKind::Text],
},
)
.unwrap();
ui.set_drag_target_options(
target,
DragTargetOptions {
kinds: vec![DragPayloadKind::Text],
effect: DropEffect::Copy,
},
)
.unwrap();
let session = ui.backend_mut().mock_start_drag(source).unwrap();
assert!(ui
.backend_mut()
.mock_drag_enter(session, target, (3, 7))
.unwrap());
assert!(ui
.backend_mut()
.mock_drag_drop(
session,
target,
(4, 9),
DragPayload::Text {
text: "Grüße".to_owned(),
},
)
.unwrap());
let mut dropped = 0;
while let Some(event) = ui.poll_event().unwrap() {
if let UiEvent::DragDropped {
payload, effect, ..
} = event
{
assert_eq!(
payload,
DragPayload::Text {
text: "Grüße".to_owned()
}
);
assert_eq!(effect, DropEffect::Copy);
dropped += 1;
}
}
assert_eq!(dropped, 1, "the session has exactly one terminal event");
}
#[test]
fn cancel_reasons_and_source_removal_terminate_exactly_once() {
for reason in [
DropCancelReason::Escape,
DropCancelReason::FocusLost,
DropCancelReason::BackendFailed,
] {
let (mut ui, source, target) = configured_ui();
configure_source_target(&mut ui, source, target);
let session = ui.backend_mut().mock_start_drag(source).unwrap();
ui.backend_mut()
.mock_drag_enter(session, target, (0, 0))
.unwrap();
assert!(ui.backend_mut().mock_cancel_drag(session, reason));
assert!(!ui.backend_mut().mock_cancel_drag(session, reason));
assert_eq!(
ui.poll_event().unwrap(),
Some(UiEvent::DragSessionStarted {
widget_id: source,
session,
kinds: vec![
DragPayloadKind::Text,
custom("application/x-nativegui-test")
],
})
);
assert!(matches!(
ui.poll_event().unwrap(),
Some(UiEvent::DragEntered { .. })
));
assert_eq!(
ui.poll_event().unwrap(),
Some(UiEvent::DragExited { target, session })
);
assert_eq!(
ui.poll_event().unwrap(),
Some(UiEvent::DragCancelled { session, reason })
);
assert_eq!(ui.poll_event().unwrap(), None);
}
let mut ui = Ui::new(MockBackend::default());
let owner = ui.create(WidgetKind::Window, Some("owner")).unwrap();
let source = ui.create(WidgetKind::ListView, Some("source")).unwrap();
let target = ui.create(WidgetKind::ListView, Some("target")).unwrap();
ui.attach(owner, source).unwrap();
configure_source_target(&mut ui, source, target);
let session = ui.backend_mut().mock_start_drag(source).unwrap();
ui.backend_mut()
.mock_drag_enter(session, target, (0, 0))
.unwrap();
ui.remove(source).unwrap();
assert_eq!(
ui.poll_event().unwrap(),
Some(UiEvent::DragSessionStarted {
widget_id: source,
session,
kinds: vec![
DragPayloadKind::Text,
custom("application/x-nativegui-test")
],
})
);
assert!(matches!(
ui.poll_event().unwrap(),
Some(UiEvent::DragEntered { .. })
));
assert_eq!(
ui.poll_event().unwrap(),
Some(UiEvent::DragExited { target, session })
);
assert_eq!(
ui.poll_event().unwrap(),
Some(UiEvent::DragCancelled {
session,
reason: DropCancelReason::SourceRemoved,
})
);
assert_eq!(ui.poll_event().unwrap(), None);
}
#[test]
fn owner_close_cancels_drag_before_window_closed() {
let mut ui = Ui::new(MockBackend::default());
let owner = ui.create(WidgetKind::Window, Some("owner")).unwrap();
let source = ui.create(WidgetKind::ListView, Some("source")).unwrap();
ui.attach(owner, source).unwrap();
ui.set_drag_source(
source,
DragSourceOptions {
kinds: vec![DragPayloadKind::Text],
},
)
.unwrap();
let session = ui.backend_mut().mock_start_drag(source).unwrap();
ui.backend_mut().inject_window_closed(owner);
assert_eq!(
ui.poll_event().unwrap(),
Some(UiEvent::DragSessionStarted {
widget_id: source,
session,
kinds: vec![DragPayloadKind::Text],
})
);
assert_eq!(
ui.poll_event().unwrap(),
Some(UiEvent::DragCancelled {
session,
reason: DropCancelReason::OwnerClosed,
})
);
assert_eq!(
ui.poll_event().unwrap(),
Some(UiEvent::WindowClosed { widget_id: owner })
);
}
#[test]
fn drag_session_events_run_inside_a_scripted_modal_pump() {
let (mut ui, source, _target) = configured_ui();
ui.set_drag_source(
source,
DragSourceOptions {
kinds: vec![DragPayloadKind::Text],
},
)
.unwrap();
ui.backend_mut().begin_modal_loop();
let session = ui.backend_mut().mock_start_drag(source).unwrap();
ui.backend_mut()
.mock_cancel_drag(session, DropCancelReason::Escape);
assert_eq!(
ui.poll_event().unwrap(),
Some(UiEvent::DragSessionStarted {
widget_id: source,
session,
kinds: vec![DragPayloadKind::Text],
})
);
assert_eq!(
ui.poll_event().unwrap(),
Some(UiEvent::DragCancelled {
session,
reason: DropCancelReason::Escape,
})
);
assert_eq!(ui.backend().modal_loops[0].delivered, 2);
assert!(ui.backend_mut().end_modal_loop().is_empty());
}
#[test]
fn unsupported_payloads_feedback_and_oversize_values_fail_explicitly() {
let (mut ui, source, target) = configured_ui();
let mut capabilities = full_capabilities();
capabilities.text = false;
ui.backend_mut().set_drag_capabilities(capabilities);
assert_eq!(
ui.set_drag_source(
source,
DragSourceOptions {
kinds: vec![DragPayloadKind::Text],
}
)
.unwrap_err(),
GuiError::UnsupportedCapability("drag_text".to_owned())
);
capabilities.text = true;
capabilities.custom_mime = false;
ui.backend_mut().set_drag_capabilities(capabilities);
assert_eq!(
ui.set_drag_source(
source,
DragSourceOptions {
kinds: vec![custom("application/x-test")],
}
)
.unwrap_err(),
GuiError::UnsupportedCapability("drag_custom_mime".to_owned())
);
capabilities.custom_mime = true;
capabilities.drop_feedback = false;
ui.backend_mut().set_drag_capabilities(capabilities);
assert_eq!(
ui.set_drag_target_options(
target,
DragTargetOptions {
kinds: vec![DragPayloadKind::Text],
effect: DropEffect::Copy,
}
)
.unwrap_err(),
GuiError::UnsupportedCapability("drop_feedback".to_owned())
);
assert!(!ui.drag_capabilities().preview);
ui.set_drag_source(
source,
DragSourceOptions {
kinds: vec![DragPayloadKind::Text],
},
)
.unwrap();
ui.set_drag_target_options(
target,
DragTargetOptions {
kinds: vec![DragPayloadKind::Text],
effect: DropEffect::None,
},
)
.unwrap();
let session = ui.backend_mut().mock_start_drag(source).unwrap();
ui.backend_mut()
.mock_drag_enter(session, target, (0, 0))
.unwrap();
assert!(ui
.backend_mut()
.mock_drag_drop(
session,
target,
(1, 1),
DragPayload::Text {
text: "still delivered".to_owned(),
},
)
.unwrap());
let mut dropped = false;
while let Some(event) = ui.poll_event().unwrap() {
if let UiEvent::DragDropped { effect, .. } = event {
assert_eq!(effect, DropEffect::None);
dropped = true;
}
}
assert!(dropped, "events still flow without OS feedback support");
assert!(DragPayload::Text {
text: "x".repeat(MAX_DRAG_PAYLOAD_BYTES),
}
.normalized()
.is_ok());
assert!(matches!(
DragPayload::Text {
text: "x".repeat(MAX_DRAG_PAYLOAD_BYTES + 1),
}
.normalized(),
Err(GuiError::Backend(_))
));
assert!(matches!(
DragPayload::Custom {
mime: "application/x-test".to_owned(),
bytes: vec![0; MAX_DRAG_PAYLOAD_BYTES + 1],
}
.normalized(),
Err(GuiError::Backend(_))
));
assert!(matches!(
custom("not-a-mime").normalized(),
Err(GuiError::Backend(_))
));
}
#[test]
fn drag_source_and_target_reject_missing_widgets() {
let mut ui = Ui::new(MockBackend::default());
assert_eq!(
ui.set_drag_source(
WidgetId(u64::MAX),
DragSourceOptions {
kinds: vec![DragPayloadKind::Text],
}
)
.unwrap_err(),
GuiError::WidgetNotFound(u64::MAX)
);
assert_eq!(
ui.set_drag_target_options(WidgetId(u64::MAX), DragTargetOptions::default())
.unwrap_err(),
GuiError::WidgetNotFound(u64::MAX)
);
}
}