Skip to main content

native_gui_core/
drag.rs

1use crate::{GuiError, GuiResult};
2
3/// Maximum UTF-8 text or custom-MIME payload size accepted by a drag session.
4pub const MAX_DRAG_PAYLOAD_BYTES: usize = 8 * 1024 * 1024;
5
6/// Payload formats a drag source can offer.
7#[derive(Debug, Clone, PartialEq, Eq, Hash)]
8pub enum DragPayloadKind {
9    Text,
10    Custom { mime: String },
11}
12
13impl DragPayloadKind {
14    /// The normalized MIME type advertised for this payload kind.
15    pub fn mime_type(&self) -> &str {
16        match self {
17            Self::Text => "text/plain",
18            Self::Custom { mime } => mime,
19        }
20    }
21
22    pub fn normalized(self) -> GuiResult<Self> {
23        match self {
24            Self::Text => Ok(Self::Text),
25            Self::Custom { mime } => Ok(Self::Custom {
26                mime: normalize_mime(&mime)?,
27            }),
28        }
29    }
30}
31
32/// Payload delivered by a drag-and-drop session.
33///
34/// Row and file values preserve their existing event shape and are not
35/// accepted by the text/custom-MIME session setters.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum DragPayload {
38    Rows { indices: Vec<usize> },
39    Files { paths: Vec<String> },
40    Text { text: String },
41    Custom { mime: String, bytes: Vec<u8> },
42}
43
44impl DragPayload {
45    pub fn normalized(self) -> GuiResult<Self> {
46        match self {
47            Self::Text { text } => {
48                check_payload_size(text.len())?;
49                Ok(Self::Text { text })
50            }
51            Self::Custom { mime, bytes } => {
52                check_payload_size(bytes.len())?;
53                Ok(Self::Custom {
54                    mime: normalize_mime(&mime)?,
55                    bytes,
56                })
57            }
58            payload @ (Self::Rows { .. } | Self::Files { .. }) => Ok(payload),
59        }
60    }
61
62    pub fn kind(&self) -> Option<DragPayloadKind> {
63        match self {
64            Self::Text { .. } => Some(DragPayloadKind::Text),
65            Self::Custom { mime, .. } => Some(DragPayloadKind::Custom { mime: mime.clone() }),
66            Self::Rows { .. } | Self::Files { .. } => None,
67        }
68    }
69}
70
71/// Capability report for the additive text/custom-MIME drag surface.
72#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
73pub struct DragCapabilities {
74    pub text: bool,
75    pub custom_mime: bool,
76    pub drop_feedback: bool,
77    pub preview: bool,
78}
79
80impl DragCapabilities {
81    /// Returns a capability set with every flag disabled.
82    pub const fn none() -> Self {
83        Self {
84            text: false,
85            custom_mime: false,
86            drop_feedback: false,
87            preview: false,
88        }
89    }
90
91    pub(crate) fn supports_kind(self, kind: &DragPayloadKind) -> bool {
92        match kind {
93            DragPayloadKind::Text => self.text,
94            DragPayloadKind::Custom { .. } => self.custom_mime,
95        }
96    }
97}
98
99/// Source payload formats, in preference order.
100#[derive(Debug, Clone, Default, PartialEq, Eq)]
101pub struct DragSourceOptions {
102    pub kinds: Vec<DragPayloadKind>,
103}
104
105/// Payload formats accepted by a target and its requested drop effect.
106#[derive(Debug, Clone, Default, PartialEq, Eq)]
107pub struct DragTargetOptions {
108    pub kinds: Vec<DragPayloadKind>,
109    pub effect: DropEffect,
110}
111
112/// Stable identifier for one drag session.
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
114pub struct DragSessionId(pub u64);
115
116/// The operation a target accepts for a payload.
117#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
118pub enum DropEffect {
119    #[default]
120    None,
121    Copy,
122    Move,
123    Link,
124}
125
126/// Why an in-progress drag did not end in a drop.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum DropCancelReason {
129    Escape,
130    FocusLost,
131    SourceRemoved,
132    OwnerClosed,
133    BackendFailed,
134}
135
136pub(crate) fn normalize_kinds(kinds: Vec<DragPayloadKind>) -> GuiResult<Vec<DragPayloadKind>> {
137    let mut normalized = Vec::with_capacity(kinds.len());
138    for kind in kinds {
139        let kind = kind.normalized()?;
140        if !normalized.contains(&kind) {
141            normalized.push(kind);
142        }
143    }
144    Ok(normalized)
145}
146
147fn normalize_mime(mime: &str) -> GuiResult<String> {
148    let mime = mime.trim().to_ascii_lowercase();
149    let mut parts = mime.split('/');
150    let top_level = parts.next().unwrap_or_default();
151    let subtype = parts.next().unwrap_or_default();
152    let valid_token = |token: &str| {
153        !token.is_empty()
154            && token.bytes().all(|byte| {
155                byte.is_ascii_alphanumeric()
156                    || matches!(
157                        byte,
158                        b'!' | b'#' | b'$' | b'&' | b'^' | b'_' | b'.' | b'+' | b'-'
159                    )
160            })
161    };
162    if !valid_token(top_level) || !valid_token(subtype) || parts.next().is_some() {
163        return Err(GuiError::Backend(format!("Invalid drag MIME type: {mime}")));
164    }
165    Ok(mime)
166}
167
168fn check_payload_size(size: usize) -> GuiResult<()> {
169    if size > MAX_DRAG_PAYLOAD_BYTES {
170        return Err(GuiError::Backend(format!(
171            "Drag payload exceeds the {MAX_DRAG_PAYLOAD_BYTES}-byte limit"
172        )));
173    }
174    Ok(())
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180    use crate::test_support::MockBackend;
181    use crate::{Ui, UiEvent, WidgetId, WidgetKind};
182
183    fn full_capabilities() -> DragCapabilities {
184        DragCapabilities {
185            text: true,
186            custom_mime: true,
187            drop_feedback: true,
188            preview: false,
189        }
190    }
191
192    fn custom(mime: &str) -> DragPayloadKind {
193        DragPayloadKind::Custom {
194            mime: mime.to_owned(),
195        }
196    }
197
198    fn configured_ui() -> (Ui<MockBackend>, WidgetId, WidgetId) {
199        let mut ui = Ui::new(MockBackend::default());
200        let source = ui.create(WidgetKind::ListView, Some("source")).unwrap();
201        let target = ui.create(WidgetKind::ListView, Some("target")).unwrap();
202        (ui, source, target)
203    }
204
205    fn configure_source_target(ui: &mut Ui<MockBackend>, source: WidgetId, target: WidgetId) {
206        ui.set_drag_source(
207            source,
208            DragSourceOptions {
209                kinds: vec![
210                    DragPayloadKind::Text,
211                    custom("application/x-nativegui-test"),
212                ],
213            },
214        )
215        .unwrap();
216        ui.set_drag_target_options(
217            target,
218            DragTargetOptions {
219                kinds: vec![custom("application/x-nativegui-test")],
220                effect: DropEffect::Move,
221            },
222        )
223        .unwrap();
224    }
225
226    #[test]
227    fn source_and_target_options_normalize_mime_without_changing_row_drag_state() {
228        let (mut ui, source, target) = configured_ui();
229        ui.set_row_drag(source, true, true).unwrap();
230        ui.set_drag_source(
231            source,
232            DragSourceOptions {
233                kinds: vec![
234                    custom(" Application/Vnd.Nativegui-Test+Json "),
235                    DragPayloadKind::Text,
236                    custom("application/vnd.nativegui-test+json"),
237                ],
238            },
239        )
240        .unwrap();
241        ui.set_drag_target_options(
242            target,
243            DragTargetOptions {
244                kinds: vec![custom("APPLICATION/VND.NATIVEGUI-TEST+JSON")],
245                effect: DropEffect::Copy,
246            },
247        )
248        .unwrap();
249
250        assert_eq!(
251            ui.backend().drag_source_options[&source].kinds,
252            vec![
253                custom("application/vnd.nativegui-test+json"),
254                DragPayloadKind::Text
255            ]
256        );
257        assert!(ui.backend().created[&source].row_drag_source);
258        assert!(ui.backend().created[&source].row_drop_target);
259        assert_eq!(
260            ui.backend().drag_target_options[&target].effect,
261            DropEffect::Copy
262        );
263    }
264
265    #[test]
266    fn mock_drag_session_filters_kinds_orders_phases_and_ends_once() {
267        let (mut ui, source, target) = configured_ui();
268        configure_source_target(&mut ui, source, target);
269        let session = ui.backend_mut().mock_start_drag(source).unwrap();
270        assert_eq!(session, DragSessionId(1));
271        assert_eq!(
272            ui.backend_mut().mock_start_drag(source).unwrap_err(),
273            GuiError::UnsupportedCapability("drag_busy".to_owned())
274        );
275        assert!(ui
276            .backend_mut()
277            .mock_drag_enter(session, target, (12, 28))
278            .unwrap());
279        assert!(ui.backend_mut().mock_drag_move(session, target, (14, 31)));
280        assert!(ui
281            .backend_mut()
282            .mock_drag_drop(
283                session,
284                target,
285                (16, 32),
286                DragPayload::Custom {
287                    mime: "APPLICATION/X-NATIVEGUI-TEST".to_owned(),
288                    bytes: vec![1, 2, 3],
289                },
290            )
291            .unwrap());
292        assert!(!ui
293            .backend_mut()
294            .mock_cancel_drag(session, DropCancelReason::Escape));
295
296        assert_eq!(
297            ui.poll_event().unwrap(),
298            Some(UiEvent::DragSessionStarted {
299                widget_id: source,
300                session,
301                kinds: vec![
302                    DragPayloadKind::Text,
303                    custom("application/x-nativegui-test")
304                ],
305            })
306        );
307        assert_eq!(
308            ui.poll_event().unwrap(),
309            Some(UiEvent::DragEntered {
310                target,
311                session,
312                position: (12, 28),
313                offered: vec!["application/x-nativegui-test".to_owned()],
314            })
315        );
316        assert_eq!(
317            ui.poll_event().unwrap(),
318            Some(UiEvent::DragMoved {
319                target,
320                session,
321                position: (14, 31),
322            })
323        );
324        assert_eq!(
325            ui.poll_event().unwrap(),
326            Some(UiEvent::DragExited { target, session })
327        );
328        assert_eq!(
329            ui.poll_event().unwrap(),
330            Some(UiEvent::DragDropped {
331                target,
332                session,
333                position: (16, 32),
334                payload: DragPayload::Custom {
335                    mime: "application/x-nativegui-test".to_owned(),
336                    bytes: vec![1, 2, 3],
337                },
338                effect: DropEffect::Move,
339            })
340        );
341        assert_eq!(ui.poll_event().unwrap(), None);
342    }
343
344    #[test]
345    fn mock_text_drop_preserves_utf8_payload_and_copy_effect() {
346        let (mut ui, source, target) = configured_ui();
347        ui.set_drag_source(
348            source,
349            DragSourceOptions {
350                kinds: vec![DragPayloadKind::Text],
351            },
352        )
353        .unwrap();
354        ui.set_drag_target_options(
355            target,
356            DragTargetOptions {
357                kinds: vec![DragPayloadKind::Text],
358                effect: DropEffect::Copy,
359            },
360        )
361        .unwrap();
362        let session = ui.backend_mut().mock_start_drag(source).unwrap();
363        assert!(ui
364            .backend_mut()
365            .mock_drag_enter(session, target, (3, 7))
366            .unwrap());
367        assert!(ui
368            .backend_mut()
369            .mock_drag_drop(
370                session,
371                target,
372                (4, 9),
373                DragPayload::Text {
374                    text: "Grüße".to_owned(),
375                },
376            )
377            .unwrap());
378
379        let mut dropped = 0;
380        while let Some(event) = ui.poll_event().unwrap() {
381            if let UiEvent::DragDropped {
382                payload, effect, ..
383            } = event
384            {
385                assert_eq!(
386                    payload,
387                    DragPayload::Text {
388                        text: "Grüße".to_owned()
389                    }
390                );
391                assert_eq!(effect, DropEffect::Copy);
392                dropped += 1;
393            }
394        }
395        assert_eq!(dropped, 1, "the session has exactly one terminal event");
396    }
397
398    #[test]
399    fn cancel_reasons_and_source_removal_terminate_exactly_once() {
400        for reason in [
401            DropCancelReason::Escape,
402            DropCancelReason::FocusLost,
403            DropCancelReason::BackendFailed,
404        ] {
405            let (mut ui, source, target) = configured_ui();
406            configure_source_target(&mut ui, source, target);
407            let session = ui.backend_mut().mock_start_drag(source).unwrap();
408            ui.backend_mut()
409                .mock_drag_enter(session, target, (0, 0))
410                .unwrap();
411            assert!(ui.backend_mut().mock_cancel_drag(session, reason));
412            assert!(!ui.backend_mut().mock_cancel_drag(session, reason));
413            assert_eq!(
414                ui.poll_event().unwrap(),
415                Some(UiEvent::DragSessionStarted {
416                    widget_id: source,
417                    session,
418                    kinds: vec![
419                        DragPayloadKind::Text,
420                        custom("application/x-nativegui-test")
421                    ],
422                })
423            );
424            assert!(matches!(
425                ui.poll_event().unwrap(),
426                Some(UiEvent::DragEntered { .. })
427            ));
428            assert_eq!(
429                ui.poll_event().unwrap(),
430                Some(UiEvent::DragExited { target, session })
431            );
432            assert_eq!(
433                ui.poll_event().unwrap(),
434                Some(UiEvent::DragCancelled { session, reason })
435            );
436            assert_eq!(ui.poll_event().unwrap(), None);
437        }
438
439        let mut ui = Ui::new(MockBackend::default());
440        let owner = ui.create(WidgetKind::Window, Some("owner")).unwrap();
441        let source = ui.create(WidgetKind::ListView, Some("source")).unwrap();
442        let target = ui.create(WidgetKind::ListView, Some("target")).unwrap();
443        ui.attach(owner, source).unwrap();
444        configure_source_target(&mut ui, source, target);
445        let session = ui.backend_mut().mock_start_drag(source).unwrap();
446        ui.backend_mut()
447            .mock_drag_enter(session, target, (0, 0))
448            .unwrap();
449        ui.remove(source).unwrap();
450        assert_eq!(
451            ui.poll_event().unwrap(),
452            Some(UiEvent::DragSessionStarted {
453                widget_id: source,
454                session,
455                kinds: vec![
456                    DragPayloadKind::Text,
457                    custom("application/x-nativegui-test")
458                ],
459            })
460        );
461        assert!(matches!(
462            ui.poll_event().unwrap(),
463            Some(UiEvent::DragEntered { .. })
464        ));
465        assert_eq!(
466            ui.poll_event().unwrap(),
467            Some(UiEvent::DragExited { target, session })
468        );
469        assert_eq!(
470            ui.poll_event().unwrap(),
471            Some(UiEvent::DragCancelled {
472                session,
473                reason: DropCancelReason::SourceRemoved,
474            })
475        );
476        assert_eq!(ui.poll_event().unwrap(), None);
477    }
478
479    #[test]
480    fn owner_close_cancels_drag_before_window_closed() {
481        let mut ui = Ui::new(MockBackend::default());
482        let owner = ui.create(WidgetKind::Window, Some("owner")).unwrap();
483        let source = ui.create(WidgetKind::ListView, Some("source")).unwrap();
484        ui.attach(owner, source).unwrap();
485        ui.set_drag_source(
486            source,
487            DragSourceOptions {
488                kinds: vec![DragPayloadKind::Text],
489            },
490        )
491        .unwrap();
492        let session = ui.backend_mut().mock_start_drag(source).unwrap();
493        ui.backend_mut().inject_window_closed(owner);
494        assert_eq!(
495            ui.poll_event().unwrap(),
496            Some(UiEvent::DragSessionStarted {
497                widget_id: source,
498                session,
499                kinds: vec![DragPayloadKind::Text],
500            })
501        );
502        assert_eq!(
503            ui.poll_event().unwrap(),
504            Some(UiEvent::DragCancelled {
505                session,
506                reason: DropCancelReason::OwnerClosed,
507            })
508        );
509        assert_eq!(
510            ui.poll_event().unwrap(),
511            Some(UiEvent::WindowClosed { widget_id: owner })
512        );
513    }
514
515    #[test]
516    fn drag_session_events_run_inside_a_scripted_modal_pump() {
517        let (mut ui, source, _target) = configured_ui();
518        ui.set_drag_source(
519            source,
520            DragSourceOptions {
521                kinds: vec![DragPayloadKind::Text],
522            },
523        )
524        .unwrap();
525        ui.backend_mut().begin_modal_loop();
526        let session = ui.backend_mut().mock_start_drag(source).unwrap();
527        ui.backend_mut()
528            .mock_cancel_drag(session, DropCancelReason::Escape);
529
530        assert_eq!(
531            ui.poll_event().unwrap(),
532            Some(UiEvent::DragSessionStarted {
533                widget_id: source,
534                session,
535                kinds: vec![DragPayloadKind::Text],
536            })
537        );
538        assert_eq!(
539            ui.poll_event().unwrap(),
540            Some(UiEvent::DragCancelled {
541                session,
542                reason: DropCancelReason::Escape,
543            })
544        );
545        assert_eq!(ui.backend().modal_loops[0].delivered, 2);
546        assert!(ui.backend_mut().end_modal_loop().is_empty());
547    }
548
549    #[test]
550    fn unsupported_payloads_feedback_and_oversize_values_fail_explicitly() {
551        let (mut ui, source, target) = configured_ui();
552        let mut capabilities = full_capabilities();
553        capabilities.text = false;
554        ui.backend_mut().set_drag_capabilities(capabilities);
555        assert_eq!(
556            ui.set_drag_source(
557                source,
558                DragSourceOptions {
559                    kinds: vec![DragPayloadKind::Text],
560                }
561            )
562            .unwrap_err(),
563            GuiError::UnsupportedCapability("drag_text".to_owned())
564        );
565
566        capabilities.text = true;
567        capabilities.custom_mime = false;
568        ui.backend_mut().set_drag_capabilities(capabilities);
569        assert_eq!(
570            ui.set_drag_source(
571                source,
572                DragSourceOptions {
573                    kinds: vec![custom("application/x-test")],
574                }
575            )
576            .unwrap_err(),
577            GuiError::UnsupportedCapability("drag_custom_mime".to_owned())
578        );
579
580        capabilities.custom_mime = true;
581        capabilities.drop_feedback = false;
582        ui.backend_mut().set_drag_capabilities(capabilities);
583        assert_eq!(
584            ui.set_drag_target_options(
585                target,
586                DragTargetOptions {
587                    kinds: vec![DragPayloadKind::Text],
588                    effect: DropEffect::Copy,
589                }
590            )
591            .unwrap_err(),
592            GuiError::UnsupportedCapability("drop_feedback".to_owned())
593        );
594        assert!(!ui.drag_capabilities().preview);
595
596        ui.set_drag_source(
597            source,
598            DragSourceOptions {
599                kinds: vec![DragPayloadKind::Text],
600            },
601        )
602        .unwrap();
603        ui.set_drag_target_options(
604            target,
605            DragTargetOptions {
606                kinds: vec![DragPayloadKind::Text],
607                effect: DropEffect::None,
608            },
609        )
610        .unwrap();
611        let session = ui.backend_mut().mock_start_drag(source).unwrap();
612        ui.backend_mut()
613            .mock_drag_enter(session, target, (0, 0))
614            .unwrap();
615        assert!(ui
616            .backend_mut()
617            .mock_drag_drop(
618                session,
619                target,
620                (1, 1),
621                DragPayload::Text {
622                    text: "still delivered".to_owned(),
623                },
624            )
625            .unwrap());
626        let mut dropped = false;
627        while let Some(event) = ui.poll_event().unwrap() {
628            if let UiEvent::DragDropped { effect, .. } = event {
629                assert_eq!(effect, DropEffect::None);
630                dropped = true;
631            }
632        }
633        assert!(dropped, "events still flow without OS feedback support");
634
635        assert!(DragPayload::Text {
636            text: "x".repeat(MAX_DRAG_PAYLOAD_BYTES),
637        }
638        .normalized()
639        .is_ok());
640        assert!(matches!(
641            DragPayload::Text {
642                text: "x".repeat(MAX_DRAG_PAYLOAD_BYTES + 1),
643            }
644            .normalized(),
645            Err(GuiError::Backend(_))
646        ));
647        assert!(matches!(
648            DragPayload::Custom {
649                mime: "application/x-test".to_owned(),
650                bytes: vec![0; MAX_DRAG_PAYLOAD_BYTES + 1],
651            }
652            .normalized(),
653            Err(GuiError::Backend(_))
654        ));
655        assert!(matches!(
656            custom("not-a-mime").normalized(),
657            Err(GuiError::Backend(_))
658        ));
659    }
660
661    #[test]
662    fn drag_source_and_target_reject_missing_widgets() {
663        let mut ui = Ui::new(MockBackend::default());
664        assert_eq!(
665            ui.set_drag_source(
666                WidgetId(u64::MAX),
667                DragSourceOptions {
668                    kinds: vec![DragPayloadKind::Text],
669                }
670            )
671            .unwrap_err(),
672            GuiError::WidgetNotFound(u64::MAX)
673        );
674        assert_eq!(
675            ui.set_drag_target_options(WidgetId(u64::MAX), DragTargetOptions::default())
676                .unwrap_err(),
677            GuiError::WidgetNotFound(u64::MAX)
678        );
679    }
680}