Skip to main content

nsh_core/element/
events.rs

1//! Typed native events: what the `on_*` methods of elements hand their
2//! listeners, decoded from the platform's [`EventPayload`].
3
4use 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/// Local files or directories dropped on an element (`on_file_drop`).
14#[derive(Debug, Clone, PartialEq, Default)]
15#[non_exhaustive]
16pub struct FileDropEvent {
17    /// Absolute `file:` URLs in platform order; encoded filenames are preserved.
18    pub uris: Vec<String>,
19    /// The MIME type of each of `uris`, in their order, by the file's name
20    /// (TS: `mimeTypes`): `""` when the name says none (a directory, no
21    /// extension), as the DOM's `File.type`.
22    pub mime_types: Vec<String>,
23    /// Where the files were let go, in the window's coordinates, as a
24    /// mouse event's `page_position` (TS: `pagePosition`): on AppKit, GTK,
25    /// Win32, iOS, Android and the Web; `None` on the GPUI backend.
26    pub page_position: Option<Point<Points>>,
27    /// The dropped regular files with their contents, on backends that hand
28    /// over contents instead of paths (the Web, and on macOS files a drag
29    /// only promises, such as an image out of a browser's page; `uris` is
30    /// empty then):
31    /// in the drop's order, directories left out, so not by index of
32    /// `uris`. Each keeps its bytes after the listener returns.
33    pub files: Vec<crate::picker::PickedFile>,
34}
35
36/// Local files or directories a drag offers to an element while it enters
37/// (`on_file_drag_enter`); nothing has been dropped yet, and no file has
38/// been read.
39#[derive(Debug, Clone, PartialEq, Default)]
40#[non_exhaustive]
41pub struct FileDragEvent {
42    /// Absolute `file:` URLs in platform order; encoded filenames are preserved.
43    pub uris: Vec<String>,
44    /// The MIME type of each of `uris`, as [`FileDropEvent::mime_types`].
45    pub mime_types: Vec<String>,
46}
47
48/// The MIME types of the files `uris` name, in their order.
49fn 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/// A scroll view moved (`on_scroll`): the offset, and the sizes it moves in.
56#[derive(Debug, Clone, Copy, PartialEq)]
57pub struct ScrollEvent {
58    /// The content offset (TS: `contentOffset`).
59    pub offset: Point<Points>,
60    /// The content's size (TS: `contentSize`).
61    pub content_size: Size<Points>,
62    /// The scroll view's size (TS: `layoutMeasurement`).
63    pub size: Size<Points>,
64    /// How far a zooming scroll view is zoomed (1: not zoomed; the content
65    /// sizes are the zoomed ones).
66    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/// A drag (`on_pan_start` / `on_pan_end`): where it started, translation
81/// since then and velocity, in points (per second).
82#[derive(Debug, Clone, Copy, Default, PartialEq)]
83pub struct PanEvent {
84    /// The system cancelled the drag rather than releasing it.
85    pub cancelled: bool,
86    /// Where the finger (or the pointer) went down, in the surface's points
87    /// as a touch's `page`: the same at the start and at the end.
88    pub origin: Point<Points>,
89    /// The translation.
90    pub translation: Point<Points>,
91    /// Horizontal velocity.
92    pub velocity_x: f32,
93    /// Vertical velocity.
94    pub velocity_y: f32,
95    /// The bound horizontal animated value now (`Interactive::pan`; the
96    /// values an app binds are of any quantity).
97    pub value_x: Option<f32>,
98    /// The bound vertical animated value now.
99    pub value_y: Option<f32>,
100}
101
102/// A pinch or a rotation: its amount and velocity. A pinch's amount is
103/// its scale (`GestureEvent<f32>`), a rotation's an angle
104/// (`GestureEvent<Radians>`).
105#[derive(Debug, Clone, Copy, Default, PartialEq)]
106pub struct GestureEvent<T = f32> {
107    /// The scale (pinches) or the rotation (rotations).
108    pub value: T,
109    /// Per second.
110    pub velocity: f32,
111}
112
113/// An input's selection (UTF-16 units; equal for a caret).
114#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
115pub struct Selection {
116    /// Start.
117    pub start: u32,
118    /// End.
119    pub end: u32,
120}
121
122/// The selection of a selectable view changed
123/// ([`Interactive::on_text_selection_change`](super::Interactive::on_text_selection_change)).
124#[derive(Debug, Clone, Default, PartialEq)]
125#[non_exhaustive]
126pub struct TextSelectionEvent {
127    /// The selected text, as a copy gives it; empty when nothing is
128    /// selected.
129    pub text: String,
130    /// Where it starts in the copy of the whole view (what a select all
131    /// would copy), in UTF-16 code units, when the platform knows it.
132    pub start: Option<u32>,
133    /// The box around the selected text in the view's coordinates (its
134    /// border box), when something is selected and the platform knows it:
135    /// a bar of actions on the selection goes above it.
136    pub bounds: Option<Bounds<Points>>,
137    /// The same box in the view's root view (the surface, or the dialog
138    /// around it), as of the event:
139    /// [`crate::overlay::OverlayAnchor::Bounds`] places an overlay against
140    /// it.
141    pub page_bounds: Option<Bounds<Points>>,
142    /// Where the selection started (the press, or the end a key extends
143    /// it from), when that is in a list item, as of the event: the
144    /// innermost item of a TSX `List`, else of a Rust component's list.
145    /// `None` outside list items, and in a row its TSX `List` has no key
146    /// for (its `keyExtractor` threw or gave neither a string nor a
147    /// number).
148    pub anchor: Option<TextSelectionEndpoint>,
149    /// Where the selection goes (the end a drag or a key moves), when that
150    /// is in a list item, as of the event. Before [`Self::anchor`] in the
151    /// list when the user selected backward.
152    pub focus: Option<TextSelectionEndpoint>,
153}
154
155/// One end of a selection across a list's items
156/// ([`TextSelectionEvent::anchor`], [`TextSelectionEvent::focus`]).
157#[derive(Debug, Clone, Default, PartialEq, Eq)]
158#[non_exhaustive]
159pub struct TextSelectionEndpoint {
160    /// The item's key, as the list names it: a TSX `List`'s
161    /// `keyExtractor`, else the item's `key` or `id`, else its index. A
162    /// Rust component's list (`virtual_list`) in a TSX `List`'s item leaves
163    /// the key to that item; with no TSX list around, its row goes by its
164    /// index. The index is written in decimal.
165    pub key: String,
166    /// Where the end is in the item's text, as a copy of the whole item
167    /// gives it, in UTF-16 code units.
168    pub offset: u32,
169}
170
171/// Where an input's caret is (`on_caret_move`): what opens at it (an `@`
172/// mention's suggestions) is placed with it.
173#[derive(Debug, Clone, Copy, Default, PartialEq)]
174#[non_exhaustive]
175pub struct CaretEvent {
176    /// The caret in the input's coordinates (its border box), its own
177    /// scrolling applied: as wide as the platform draws it, as tall as its
178    /// line. Empty when the platform could not place it.
179    pub bounds: Bounds<Points>,
180    /// The caret in its root view's coordinates (the surface, or the dialog
181    /// around the input), as of the event:
182    /// [`crate::overlay::OverlayAnchor::Bounds`] places an overlay against it.
183    pub page_bounds: Bounds<Points>,
184}
185
186/// An input method's composition in an input (`on_composition_change`):
187/// the text being composed (pinyin before a character is chosen, kana
188/// before conversion), not yet the input's text.
189#[derive(Debug, Clone, Default, PartialEq, Eq)]
190#[non_exhaustive]
191pub struct Composition {
192    /// A composition is in progress.
193    pub composing: bool,
194    /// The text being composed, empty once the composition ends.
195    pub text: String,
196}
197
198/// Where a web view is (`on_navigation_state_change`, `on_load`).
199#[derive(Debug, Clone, Default, PartialEq)]
200pub struct WebNavigation {
201    /// The page's URL.
202    pub url: String,
203    /// Its title.
204    pub title: String,
205    /// Still loading.
206    pub loading: bool,
207    /// `go_back` would do something.
208    pub can_go_back: bool,
209    /// `go_forward` would do something.
210    pub can_go_forward: bool,
211}
212
213/// A video loaded (`on_load`): its length in seconds and size in pixels.
214#[derive(Debug, Clone, Copy, Default, PartialEq)]
215pub struct VideoInfo {
216    /// Seconds.
217    pub duration: f32,
218    /// Its frames' size in pixels, as decoded (GPUI's images' sizes are
219    /// [`DevicePixels`] too).
220    pub size: Size<DevicePixels>,
221}
222
223/// A video played on (`on_progress`).
224#[derive(Debug, Clone, Copy, Default, PartialEq)]
225pub struct VideoProgress {
226    /// Seconds played.
227    pub current_time: f32,
228    /// Seconds in all.
229    pub duration: f32,
230}
231
232/// An image's download went on (`Image::on_progress`): bytes so far and in
233/// all (0 when the server does not say).
234#[derive(Debug, Clone, Copy, Default, PartialEq)]
235pub struct ImageProgress {
236    /// Bytes loaded.
237    pub loaded: f64,
238    /// Bytes in all, 0 when unknown.
239    pub total: f64,
240}
241
242/// A web view download started, finished, failed or was cancelled
243/// (`WebView::on_download`, the core's `onDownload` payload).
244pub(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    // Only a running download can be cancelled by its event.
259    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    /// The web view a download event is being dispatched to: its node and
293    /// the executor that reaches it. Set only while its listener runs, so
294    /// the event's handle cannot be made anywhere else.
295    static DOWNLOAD_TARGET: RefCell<Option<(crate::NodeId, Weak<Executor>)>> =
296        const { RefCell::new(None) };
297}
298
299/// Makes `node` the target of the download events dispatched while it
300/// lives (the previous target is restored when it drops).
301pub(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
313/// Sets the web view a download event dispatched now belongs to.
314pub(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
319/// The handle of download `id` of the web view being dispatched to, or
320/// `None` outside a download event's dispatch.
321fn 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
330/// A web view's page asked to download a file
331/// (`WebView::on_download_pending`).
332pub(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/// An event of a registered native component (`on_native_event`).
369#[derive(Debug, Clone, PartialEq)]
370pub struct NativeEvent {
371    /// Its name (`regionChange`).
372    pub name: Arc<str>,
373    /// Its data.
374    pub data: JsonValue,
375}
376
377/// Where the core placed an overlay (`Overlay::on_position`).
378#[derive(Debug, Clone, Copy, Default, PartialEq)]
379pub struct OverlayPosition {
380    /// The side of the anchor it went on.
381    pub placement: crate::overlay::Placement,
382    /// Its frame in the root view.
383    pub bounds: Bounds<Points>,
384    /// The room on that side, inside the safe area less the margin.
385    pub available: Size<Points>,
386}
387
388/// Why a hint asks to show or hide (`Overlay::on_hint_show` /
389/// `on_hint_hide`).
390#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
391#[non_exhaustive]
392pub enum HintReason {
393    /// The pointer rested on its anchor, or left or pressed it.
394    #[default]
395    Pointer,
396    /// The keyboard focus came to its anchor, or left it.
397    Focus,
398    /// Escape was pressed while it was shown.
399    Escape,
400    /// It left the view.
401    View,
402}
403
404impl HintReason {
405    /// Its name in an event's payload.
406    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
425/// A field of a map payload.
426fn 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
472/// How a typed event comes out of a payload (`None`: not this event's).
473pub(crate) type Decode<T> = for<'a> fn(&'a EventPayload) -> Option<Cow<'a, T>>;
474
475/// `listener` as a listener of raw payloads: it runs with what `decode`
476/// makes of each payload.
477pub(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
488/// A sheet's new detent (`{ detent }`, [`crate::SheetDetent::change_payload`]).
489pub(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
496/// Events without data.
497pub(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
516/// Where a press went down, in the root view (`Overlay::on_press_outside`).
517pub(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
554/// An error's message when its `code` says the platform has no such
555/// feature (`ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`).
556pub(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
562/// An error's message when its `code` says the web view's web content
563/// process ended (`ERR_NSH_WEBVIEW_TERMINATED`).
564pub(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
577/// The selection of a selectable view (`text`, `start`).
578pub(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
635/// An image's own size, in pixels.
636pub(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
774/// `onMouseEnter`, `onMouseMove` and `onMouseLeave`'s payload; an event
775/// sent without one (an embedder's, a script's) still reaches the
776/// listener, at no known position.
777/// A press's (`on_press`, `on_long_press`, `on_press_down`,
778/// `on_press_up`): the default where the platform reported none.
779pub(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}