1use std::{borrow::Cow, cell::RefCell, rc::Weak, sync::Arc};
5
6use super::{builder::Listener, task::Executor};
7use crate::{
8 Bounds, ContextMenuEvent, EventPayload, JsonValue, MouseEvent, PayloadValue, PinchEvent, Point,
9 Points, PressEvent, Size, TouchEvent, WheelEvent,
10 geometry::{DevicePixels, Radians},
11};
12
13#[derive(Debug, Clone, PartialEq, Default)]
15#[non_exhaustive]
16pub struct FileDropEvent {
17 pub uris: Vec<String>,
19 pub mime_types: Vec<String>,
23 pub page_position: Option<Point<Points>>,
27 pub files: Vec<crate::picker::PickedFile>,
34}
35
36#[derive(Debug, Clone, PartialEq, Default)]
40#[non_exhaustive]
41pub struct FileDragEvent {
42 pub uris: Vec<String>,
44 pub mime_types: Vec<String>,
46}
47
48fn mime_types(uris: &[String]) -> Vec<String> {
50 uris.iter()
51 .map(|uri| crate::platform::file_mime_type(uri).to_owned())
52 .collect()
53}
54
55#[derive(Debug, Clone, Copy, PartialEq)]
57pub struct ScrollEvent {
58 pub offset: Point<Points>,
60 pub content_size: Size<Points>,
62 pub size: Size<Points>,
64 pub zoom_scale: f32,
67}
68
69impl Default for ScrollEvent {
70 fn default() -> Self {
71 Self {
72 offset: Point::default(),
73 content_size: Size::default(),
74 size: Size::default(),
75 zoom_scale: 1.0,
76 }
77 }
78}
79
80#[derive(Debug, Clone, Copy, Default, PartialEq)]
83pub struct PanEvent {
84 pub cancelled: bool,
86 pub origin: Point<Points>,
89 pub translation: Point<Points>,
91 pub velocity_x: f32,
93 pub velocity_y: f32,
95 pub value_x: Option<f32>,
98 pub value_y: Option<f32>,
100}
101
102#[derive(Debug, Clone, Copy, Default, PartialEq)]
106pub struct GestureEvent<T = f32> {
107 pub value: T,
109 pub velocity: f32,
111}
112
113#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
115pub struct Selection {
116 pub start: u32,
118 pub end: u32,
120}
121
122#[derive(Debug, Clone, Default, PartialEq)]
125#[non_exhaustive]
126pub struct TextSelectionEvent {
127 pub text: String,
130 pub start: Option<u32>,
133 pub bounds: Option<Bounds<Points>>,
137 pub page_bounds: Option<Bounds<Points>>,
142 pub anchor: Option<TextSelectionEndpoint>,
149 pub focus: Option<TextSelectionEndpoint>,
153}
154
155#[derive(Debug, Clone, Default, PartialEq, Eq)]
158#[non_exhaustive]
159pub struct TextSelectionEndpoint {
160 pub key: String,
166 pub offset: u32,
169}
170
171#[derive(Debug, Clone, Copy, Default, PartialEq)]
174#[non_exhaustive]
175pub struct CaretEvent {
176 pub bounds: Bounds<Points>,
180 pub page_bounds: Bounds<Points>,
184}
185
186#[derive(Debug, Clone, Default, PartialEq, Eq)]
190#[non_exhaustive]
191pub struct Composition {
192 pub composing: bool,
194 pub text: String,
196}
197
198#[derive(Debug, Clone, Default, PartialEq)]
200pub struct WebNavigation {
201 pub url: String,
203 pub title: String,
205 pub loading: bool,
207 pub can_go_back: bool,
209 pub can_go_forward: bool,
211}
212
213#[derive(Debug, Clone, Copy, Default, PartialEq)]
215pub struct VideoInfo {
216 pub duration: f32,
218 pub size: Size<DevicePixels>,
221}
222
223#[derive(Debug, Clone, Copy, Default, PartialEq)]
225pub struct VideoProgress {
226 pub current_time: f32,
228 pub duration: f32,
230}
231
232#[derive(Debug, Clone, Copy, Default, PartialEq)]
235pub struct ImageProgress {
236 pub loaded: f64,
238 pub total: f64,
240}
241
242pub(crate) fn web_download(p: &EventPayload) -> Option<Cow<'_, crate::webview::WebDownload>> {
245 let EventPayload::Map(entries) = p else {
246 return None;
247 };
248 let text = |key: &str| match entries.iter().find(|(k, _)| *k == key) {
249 Some((_, PayloadValue::Str(value))) => Some(value.clone()),
250 _ => None,
251 };
252 let number = |key: &str| match entries.iter().find(|(k, _)| *k == key) {
253 Some((_, PayloadValue::Number(n))) => Some(*n),
254 _ => None,
255 };
256 let state = crate::webview::WebDownloadState::parse(text("state")?.as_str())?;
257 let id = text("id")?;
258 let handle = (state == crate::webview::WebDownloadState::Started)
260 .then(|| download_handle(id.clone()))
261 .flatten();
262 Some(Cow::Owned(crate::webview::WebDownload {
263 state,
264 id,
265 url: text("url")?,
266 filename: text("filename")?,
267 path: std::path::PathBuf::from(text("path")?),
268 bytes: number("bytes").map(|n| n.max(0.0) as u64),
269 message: text("message"),
270 source: text("source")
271 .as_deref()
272 .and_then(crate::webview::WebDownloadSource::parse)
273 .unwrap_or_default(),
274 code: text("code"),
275 reason: text("reason").as_deref().and_then(cancel_reason),
276 handle,
277 }))
278}
279
280fn cancel_reason(name: &str) -> Option<crate::webview::CancelReason> {
281 use crate::webview::CancelReason;
282 match name {
283 "app" => Some(CancelReason::App),
284 "timeout" => Some(CancelReason::Timeout),
285 "teardown" => Some(CancelReason::Teardown),
286 "noListener" => Some(CancelReason::NoListener),
287 _ => None,
288 }
289}
290
291thread_local! {
292 static DOWNLOAD_TARGET: RefCell<Option<(crate::NodeId, Weak<Executor>)>> =
296 const { RefCell::new(None) };
297}
298
299pub(crate) struct DownloadTarget {
302 previous: Option<(crate::NodeId, Weak<Executor>)>,
303}
304
305impl Drop for DownloadTarget {
306 fn drop(&mut self) {
307 DOWNLOAD_TARGET.with(|target| {
308 *target.borrow_mut() = self.previous.take();
309 });
310 }
311}
312
313pub(crate) fn download_target(node: crate::NodeId, executor: Weak<Executor>) -> DownloadTarget {
315 let previous = DOWNLOAD_TARGET.with(|target| target.borrow_mut().replace((node, executor)));
316 DownloadTarget { previous }
317}
318
319fn download_handle(id: String) -> Option<crate::webview::DownloadHandle> {
322 DOWNLOAD_TARGET.with(|target| {
323 target
324 .borrow()
325 .clone()
326 .map(|(node, executor)| crate::webview::DownloadHandle::new(node, executor, id))
327 })
328}
329
330pub(crate) fn web_download_pending(
333 p: &EventPayload,
334) -> Option<Cow<'_, crate::webview::WebDownloadPending>> {
335 let EventPayload::Json(value) = p else {
336 return None;
337 };
338 let id = value.get("id")?.as_str()?.to_owned();
339 let handle = download_handle(id.clone())?;
340 Some(Cow::Owned(crate::webview::WebDownloadPending {
341 id,
342 url: value.get("url")?.as_str()?.to_owned(),
343 filename: value.get("filename")?.as_str()?.to_owned(),
344 source: value
345 .get("source")
346 .and_then(|v| v.as_str())
347 .and_then(crate::webview::WebDownloadSource::parse)
348 .unwrap_or_default(),
349 mime_type: value
350 .get("mime_type")
351 .and_then(|v| v.as_str())
352 .map(str::to_owned),
353 bytes: value.get("bytes").and_then(|v| {
354 v.as_u64().or_else(|| {
355 v.as_f64()
356 .filter(|n| n.is_finite() && *n >= 0.0 && n.fract() == 0.0)
357 .map(|n| n as u64)
358 })
359 }),
360 method: value
361 .get("method")
362 .and_then(|v| v.as_str())
363 .map(str::to_owned),
364 handle: Some(handle),
365 }))
366}
367
368#[derive(Debug, Clone, PartialEq)]
370pub struct NativeEvent {
371 pub name: Arc<str>,
373 pub data: JsonValue,
375}
376
377#[derive(Debug, Clone, Copy, Default, PartialEq)]
379pub struct OverlayPosition {
380 pub placement: crate::overlay::Placement,
382 pub bounds: Bounds<Points>,
384 pub available: Size<Points>,
386}
387
388#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
391#[non_exhaustive]
392pub enum HintReason {
393 #[default]
395 Pointer,
396 Focus,
398 Escape,
400 View,
402}
403
404impl HintReason {
405 pub(crate) fn as_str(self) -> &'static str {
407 match self {
408 Self::Pointer => "pointer",
409 Self::Focus => "focus",
410 Self::Escape => "escape",
411 Self::View => "view",
412 }
413 }
414}
415
416pub(crate) fn hint_reason(p: &EventPayload) -> Option<Cow<'_, HintReason>> {
417 Some(Cow::Owned(match string(p, "reason") {
418 Some("focus") => HintReason::Focus,
419 Some("escape") => HintReason::Escape,
420 Some("view") => HintReason::View,
421 _ => HintReason::Pointer,
422 }))
423}
424
425fn field<'a>(payload: &'a EventPayload, key: &str) -> Option<&'a PayloadValue> {
427 match payload {
428 EventPayload::Map(entries) => entries.iter().find(|(k, _)| *k == key).map(|(_, v)| v),
429 _ => None,
430 }
431}
432
433fn number(payload: &EventPayload, key: &str) -> f32 {
434 match field(payload, key) {
435 Some(PayloadValue::Number(n)) => *n as f32,
436 _ => 0.0,
437 }
438}
439
440fn flag(payload: &EventPayload, key: &str) -> bool {
441 matches!(field(payload, key), Some(PayloadValue::Bool(true)))
442}
443
444fn string<'a>(payload: &'a EventPayload, key: &str) -> Option<&'a str> {
445 match field(payload, key) {
446 Some(PayloadValue::Str(s)) => Some(s),
447 _ => None,
448 }
449}
450
451fn point_field(payload: &EventPayload, key: &str) -> Point<Points> {
452 match field(payload, key) {
453 Some(PayloadValue::Point(p)) => *p,
454 _ => Point::default(),
455 }
456}
457
458fn size_field(payload: &EventPayload, key: &str) -> Size<Points> {
459 match field(payload, key) {
460 Some(PayloadValue::Size(s)) => *s,
461 _ => Size::default(),
462 }
463}
464
465fn bounds_field(payload: &EventPayload, key: &str) -> Bounds<Points> {
466 match field(payload, key) {
467 Some(PayloadValue::Bounds(b)) => *b,
468 _ => Bounds::default(),
469 }
470}
471
472pub(crate) type Decode<T> = for<'a> fn(&'a EventPayload) -> Option<Cow<'a, T>>;
474
475pub(crate) fn typed<T: ?Sized + ToOwned + 'static>(
478 listener: Listener<T>,
479 decode: Decode<T>,
480) -> Listener<EventPayload> {
481 listener.wrap(move |inner, payload: &EventPayload| {
482 if let Some(value) = decode(payload) {
483 inner(&value);
484 }
485 })
486}
487
488pub(crate) fn sheet_detent(p: &EventPayload) -> Option<Cow<'_, crate::SheetDetent>> {
490 let EventPayload::Json(value) = p else {
491 return None;
492 };
493 crate::SheetDetent::from_json(value.get("detent")?).map(Cow::Owned)
494}
495
496pub(crate) fn unit(_: &EventPayload) -> Option<Cow<'_, ()>> {
498 Some(Cow::Owned(()))
499}
500
501pub(crate) fn overlay_position(p: &EventPayload) -> Option<Cow<'_, OverlayPosition>> {
502 use crate::overlay::Placement;
503 let placement = match string(p, "placement")? {
504 "top" => Placement::Top,
505 "left" => Placement::Left,
506 "right" => Placement::Right,
507 _ => Placement::Bottom,
508 };
509 Some(Cow::Owned(OverlayPosition {
510 placement,
511 bounds: bounds_field(p, "bounds"),
512 available: size_field(p, "available"),
513 }))
514}
515
516pub(crate) fn page_point(p: &EventPayload) -> Option<Cow<'_, Point<Points>>> {
518 Some(Cow::Owned(point_field(p, "pagePosition")))
519}
520
521pub(crate) fn layout(p: &EventPayload) -> Option<Cow<'_, Bounds<Points>>> {
522 match *p {
523 EventPayload::Layout(frame) => Some(Cow::Owned(frame)),
524 _ => None,
525 }
526}
527
528pub(crate) fn text(p: &EventPayload) -> Option<Cow<'_, str>> {
529 match p {
530 EventPayload::Text { text, .. } => Some(Cow::Borrowed(text)),
531 _ => None,
532 }
533}
534
535pub(crate) fn key(p: &EventPayload) -> Option<Cow<'_, str>> {
536 string(p, "key").map(Cow::Borrowed)
537}
538
539pub(crate) fn action(p: &EventPayload) -> Option<Cow<'_, str>> {
540 string(p, "actionName").map(Cow::Borrowed)
541}
542
543pub(crate) fn message(p: &EventPayload) -> Option<Cow<'_, str>> {
544 match p {
545 EventPayload::Error { message } => Some(Cow::Borrowed(message)),
546 _ => string(p, "message").map(Cow::Borrowed),
547 }
548}
549
550pub(crate) fn data(p: &EventPayload) -> Option<Cow<'_, str>> {
551 string(p, "data").map(Cow::Borrowed)
552}
553
554pub(crate) fn unavailable(p: &EventPayload) -> Option<Cow<'_, str>> {
557 (string(p, "code") == Some(crate::element::codes::UNAVAILABLE))
558 .then(|| message(p))
559 .flatten()
560}
561
562pub(crate) fn terminated(p: &EventPayload) -> Option<Cow<'_, str>> {
565 (string(p, "code") == Some(crate::element::codes::WEBVIEW_TERMINATED))
566 .then(|| message(p))
567 .flatten()
568}
569
570pub(crate) fn selection(p: &EventPayload) -> Option<Cow<'_, Selection>> {
571 Some(Cow::Owned(Selection {
572 start: number(p, "start") as u32,
573 end: number(p, "end") as u32,
574 }))
575}
576
577pub(crate) fn selected_text(p: &EventPayload) -> Option<Cow<'_, TextSelectionEvent>> {
579 let start = match field(p, "start") {
580 Some(PayloadValue::Number(n)) if *n >= 0.0 => Some(*n as u32),
581 _ => None,
582 };
583 let optional_bounds = |key| match field(p, key) {
584 Some(PayloadValue::Bounds(b)) => Some(*b),
585 _ => None,
586 };
587 let endpoint = |(key, offset): (&str, &str)| {
588 Some(TextSelectionEndpoint {
589 key: string(p, key)?.to_owned(),
590 offset: match field(p, offset) {
591 Some(PayloadValue::Number(n)) if *n >= 0.0 => *n as u32,
592 _ => return None,
593 },
594 })
595 };
596 let [anchor, focus] = crate::selection::ITEM_FIELDS;
597 Some(Cow::Owned(TextSelectionEvent {
598 text: string(p, "text").unwrap_or_default().to_owned(),
599 start,
600 bounds: optional_bounds("bounds"),
601 page_bounds: optional_bounds("pageBounds"),
602 anchor: endpoint(anchor),
603 focus: endpoint(focus),
604 }))
605}
606
607pub(crate) fn paste(p: &EventPayload) -> Option<Cow<'_, crate::PasteEvent>> {
608 match p {
609 EventPayload::Paste(paste) => Some(Cow::Borrowed(paste)),
610 _ => None,
611 }
612}
613
614pub(crate) fn caret(p: &EventPayload) -> Option<Cow<'_, CaretEvent>> {
615 Some(Cow::Owned(CaretEvent {
616 bounds: bounds_field(p, "bounds"),
617 page_bounds: bounds_field(p, "pageBounds"),
618 }))
619}
620
621pub(crate) fn composition(p: &EventPayload) -> Option<Cow<'_, Composition>> {
622 Some(Cow::Owned(Composition {
623 composing: flag(p, "composing"),
624 text: string(p, "text").unwrap_or_default().to_owned(),
625 }))
626}
627
628pub(crate) fn size(p: &EventPayload) -> Option<Cow<'_, Size<Points>>> {
629 Some(Cow::Owned(crate::geometry::size_pt(
630 number(p, "width"),
631 number(p, "height"),
632 )))
633}
634
635pub(crate) fn pixel_size(p: &EventPayload) -> Option<Cow<'_, Size<DevicePixels>>> {
637 Some(Cow::Owned(match *p {
638 EventPayload::Image(size) => size,
639 _ => Size::new(
640 DevicePixels(number(p, "width").round() as i32),
641 DevicePixels(number(p, "height").round() as i32),
642 ),
643 }))
644}
645
646pub(crate) fn scroll(p: &EventPayload) -> Option<Cow<'_, ScrollEvent>> {
647 Some(Cow::Owned(match *p {
648 EventPayload::Scroll(offset) => ScrollEvent {
649 offset,
650 ..ScrollEvent::default()
651 },
652 _ => ScrollEvent {
653 offset: point_field(p, "offset"),
654 content_size: size_field(p, "contentSize"),
655 size: size_field(p, "size"),
656 zoom_scale: match field(p, "zoomScale") {
657 Some(PayloadValue::Number(n)) => *n as f32,
658 _ => 1.0,
659 },
660 },
661 }))
662}
663
664pub(crate) fn offset(p: &EventPayload) -> Option<Cow<'_, Point<Points>>> {
665 Some(Cow::Owned(match *p {
666 EventPayload::Scroll(offset) => offset,
667 _ => point_field(p, "offset"),
668 }))
669}
670
671pub(crate) fn pan(p: &EventPayload) -> Option<Cow<'_, PanEvent>> {
672 match *p {
673 EventPayload::Pan {
674 origin,
675 translation,
676 velocity_x,
677 velocity_y,
678 value_x,
679 value_y,
680 }
681 | EventPayload::PanCancelled {
682 origin,
683 translation,
684 velocity_x,
685 velocity_y,
686 value_x,
687 value_y,
688 } => Some(Cow::Owned(PanEvent {
689 cancelled: matches!(p, EventPayload::PanCancelled { .. }),
690 origin,
691 translation,
692 velocity_x,
693 velocity_y,
694 value_x: value_x.map(|v| v.0),
695 value_y: value_y.map(|v| v.0),
696 })),
697 _ => None,
698 }
699}
700
701pub(crate) fn pinch(p: &EventPayload) -> Option<Cow<'_, GestureEvent>> {
702 Some(Cow::Owned(GestureEvent {
703 value: number(p, "scale"),
704 velocity: number(p, "velocity"),
705 }))
706}
707
708pub(crate) fn rotation(p: &EventPayload) -> Option<Cow<'_, GestureEvent<Radians>>> {
709 Some(Cow::Owned(GestureEvent {
710 value: Radians(number(p, "rotation")),
711 velocity: number(p, "velocity"),
712 }))
713}
714
715pub(crate) fn touch(p: &EventPayload) -> Option<Cow<'_, TouchEvent>> {
716 match p {
717 EventPayload::Touch(touch) => Some(Cow::Borrowed(touch)),
718 _ => None,
719 }
720}
721
722pub(crate) fn navigation(p: &EventPayload) -> Option<Cow<'_, WebNavigation>> {
723 Some(Cow::Owned(WebNavigation {
724 url: string(p, "url").unwrap_or_default().to_owned(),
725 title: string(p, "title").unwrap_or_default().to_owned(),
726 loading: flag(p, "loading"),
727 can_go_back: flag(p, "canGoBack"),
728 can_go_forward: flag(p, "canGoForward"),
729 }))
730}
731
732pub(crate) fn video(p: &EventPayload) -> Option<Cow<'_, VideoInfo>> {
733 Some(Cow::Owned(VideoInfo {
734 duration: number(p, "duration"),
735 size: Size::new(
736 DevicePixels(number(p, "width").round() as i32),
737 DevicePixels(number(p, "height").round() as i32),
738 ),
739 }))
740}
741
742pub(crate) fn progress(p: &EventPayload) -> Option<Cow<'_, VideoProgress>> {
743 Some(Cow::Owned(VideoProgress {
744 current_time: number(p, "currentTime"),
745 duration: number(p, "duration"),
746 }))
747}
748
749pub(crate) fn image_progress(p: &EventPayload) -> Option<Cow<'_, ImageProgress>> {
750 let number = |key| match field(p, key) {
751 Some(PayloadValue::Number(n)) => *n,
752 _ => 0.0,
753 };
754 Some(Cow::Owned(ImageProgress {
755 loaded: number("loaded"),
756 total: number("total"),
757 }))
758}
759
760pub(crate) fn buffering(p: &EventPayload) -> Option<Cow<'_, bool>> {
761 Some(Cow::Owned(flag(p, "isBuffering")))
762}
763
764pub(crate) fn native(p: &EventPayload) -> Option<Cow<'_, NativeEvent>> {
765 match p {
766 EventPayload::Native { name, data } => Some(Cow::Owned(NativeEvent {
767 name: name.clone(),
768 data: data.clone(),
769 })),
770 _ => None,
771 }
772}
773
774pub(crate) fn press(p: &EventPayload) -> Option<Cow<'_, PressEvent>> {
780 match p {
781 EventPayload::Press(e) => Some(Cow::Borrowed(e)),
782 _ => Some(Cow::Owned(PressEvent::default())),
783 }
784}
785
786pub(crate) fn mouse(p: &EventPayload) -> Option<Cow<'_, MouseEvent>> {
787 match p {
788 EventPayload::Mouse(e) => Some(Cow::Borrowed(e)),
789 _ => Some(Cow::Owned(MouseEvent::default())),
790 }
791}
792
793pub(crate) fn context_menu(p: &EventPayload) -> Option<Cow<'_, ContextMenuEvent>> {
794 match p {
795 EventPayload::ContextMenu(e) => Some(Cow::Borrowed(e)),
796 _ => None,
797 }
798}
799
800pub(crate) fn touchpad_pinch(p: &EventPayload) -> Option<Cow<'_, PinchEvent>> {
801 match p {
802 EventPayload::Pinch(e) => Some(Cow::Borrowed(e)),
803 _ => None,
804 }
805}
806
807pub(crate) fn key_event(p: &EventPayload) -> Option<Cow<'_, crate::KeyEvent>> {
808 match p {
809 EventPayload::Key(event) => Some(Cow::Borrowed(event)),
810 _ => None,
811 }
812}
813pub(crate) fn wheel(p: &EventPayload) -> Option<Cow<'_, WheelEvent>> {
814 match p {
815 EventPayload::Wheel(e) => Some(Cow::Borrowed(e)),
816 _ => None,
817 }
818}
819
820pub(crate) fn file_drop(p: &EventPayload) -> Option<Cow<'_, FileDropEvent>> {
821 match p {
822 EventPayload::FileDrop(uris) => Some(Cow::Owned(FileDropEvent {
823 uris: uris.clone(),
824 mime_types: mime_types(uris),
825 page_position: None,
826 files: Vec::new(),
827 })),
828 EventPayload::FileDropAt {
829 uris,
830 page_position,
831 } => Some(Cow::Owned(FileDropEvent {
832 uris: uris.clone(),
833 mime_types: mime_types(uris),
834 page_position: Some(*page_position),
835 files: Vec::new(),
836 })),
837 EventPayload::FileContents(c) => Some(Cow::Owned(FileDropEvent {
838 uris: Vec::new(),
839 mime_types: c.mime_types.clone(),
840 page_position: c.page_position,
841 files: c.files.clone(),
842 })),
843 _ => None,
844 }
845}
846
847pub(crate) fn file_drag(p: &EventPayload) -> Option<Cow<'_, FileDragEvent>> {
848 match p {
849 EventPayload::FileDrop(uris) | EventPayload::FileDropAt { uris, .. } => {
850 Some(Cow::Owned(FileDragEvent {
851 uris: uris.clone(),
852 mime_types: mime_types(uris),
853 }))
854 }
855 EventPayload::FileContents(c) => Some(Cow::Owned(FileDragEvent {
856 uris: Vec::new(),
857 mime_types: c.mime_types.clone(),
858 })),
859 _ => None,
860 }
861}
862
863#[cfg(test)]
864mod tests {
865 #[test]
866 fn a_cancelled_pan_preserves_its_final_values() {
867 use crate::{EventPayload, Points, geometry::point};
868 let payload = EventPayload::PanCancelled {
869 origin: point(Points(12.0), Points(30.0)),
870 translation: point(Points(4.0), Points(150.0)),
871 velocity_x: 0.0,
872 velocity_y: 900.0,
873 value_x: None,
874 value_y: Some(Points(150.0)),
875 };
876 let event = super::pan(&payload).unwrap();
877 assert!(event.cancelled);
878 assert_eq!(event.origin, point(Points(12.0), Points(30.0)));
879 assert_eq!(event.translation, point(Points(4.0), Points(150.0)));
880 assert_eq!(event.value_y, Some(150.0));
881 assert_eq!(event.velocity_y, 900.0);
882 }
883
884 #[test]
885 fn file_drop_requires_the_file_payload() {
886 assert!(super::file_drop(&crate::EventPayload::None).is_none());
887 let uris = vec!["file:///tmp/a%20b".into(), "file:///tmp/empty/".into()];
888 assert_eq!(
889 super::file_drop(&crate::EventPayload::FileDrop(uris.clone()))
890 .unwrap()
891 .uris,
892 uris
893 );
894 }
895
896 #[test]
897 fn file_drags_and_drops_type_each_offered_file_by_its_name() {
898 use crate::{EventPayload, Points, geometry::point};
899 let uris: Vec<String> = vec![
900 "file:///tmp/a%20b.png".into(),
901 "file:///tmp/c.JPG".into(),
902 "file:///tmp/folder/".into(),
903 ];
904 let types = ["image/png", "image/jpeg", ""];
905 let offered = EventPayload::FileDrop(uris.clone());
906 let drag = super::file_drag(&offered).unwrap();
907 assert_eq!(drag.uris, uris);
908 assert_eq!(drag.mime_types, types);
909 let at = EventPayload::FileDropAt {
910 uris: uris.clone(),
911 page_position: point(Points(3.0), Points(4.0)),
912 };
913 let drop = super::file_drop(&at).unwrap();
914 assert_eq!(drop.mime_types, types);
915 assert_eq!(drop.page_position, Some(point(Points(3.0), Points(4.0))));
916 assert!(super::file_drag(&EventPayload::None).is_none());
917 }
918
919 #[test]
920 fn dropped_contents_arrive_without_uris() {
921 use crate::{
922 EventPayload, FileContents, ImageData, Points, geometry::point, picker::PickedFile,
923 };
924 let file = PickedFile::new("a.txt", "text/plain", ImageData::new(b"hi".to_vec()));
925 let payload = EventPayload::FileContents(Box::new(FileContents::new(
926 vec![file.clone()],
927 vec!["text/plain".into()],
928 Some(point(Points(1.0), Points(2.0))),
929 )));
930 let drop = super::file_drop(&payload).unwrap();
931 assert!(drop.uris.is_empty());
932 assert_eq!(drop.files, vec![file]);
933 assert_eq!(drop.page_position, Some(point(Points(1.0), Points(2.0))));
934 let drag = super::file_drag(&payload).unwrap();
935 assert!(drag.uris.is_empty());
936 assert_eq!(drag.mime_types, ["text/plain"]);
937 }
938
939 #[test]
940 fn composition_reads_its_state_and_text() {
941 use crate::{EventPayload, PayloadValue};
942 let composing = EventPayload::Map(vec![
943 ("composing", PayloadValue::Bool(true)),
944 ("text", PayloadValue::Str("teng".into())),
945 ]);
946 let c = super::composition(&composing).unwrap();
947 assert!(c.composing);
948 assert_eq!(c.text, "teng");
949 let ended = EventPayload::Map(vec![
950 ("composing", PayloadValue::Bool(false)),
951 ("text", PayloadValue::Str(String::new())),
952 ]);
953 assert_eq!(
954 super::composition(&ended).unwrap().into_owned(),
955 super::Composition::default()
956 );
957 }
958}