zng_view_api/
types.rs

1//! General event types.
2
3use crate::{
4    access::{AccessCmd, AccessNodeId},
5    api_extension::{ApiExtensionId, ApiExtensionPayload, ApiExtensions},
6    audio::{AudioDeviceId, AudioDeviceInfo},
7    config::{
8        AnimationsConfig, ChromeConfig, ColorsConfig, FontAntiAliasing, KeyRepeatConfig, LocaleConfig, MultiClickConfig, TouchConfig,
9    },
10    dialog::{DialogId, FileDialogResponse, MsgDialogResponse},
11    drag_drop::{DragDropData, DragDropEffect},
12    image::{ImageId, ImageLoadedData, ImagePpi},
13    ipc::{self, IpcBytes},
14    keyboard::{Key, KeyCode, KeyLocation, KeyState},
15    mouse::{ButtonState, MouseButton, MouseScrollDelta},
16    raw_input::{InputDeviceCapability, InputDeviceEvent, InputDeviceId, InputDeviceInfo},
17    touch::{TouchPhase, TouchUpdate},
18    window::{EventFrameRendered, FrameId, HeadlessOpenData, MonitorId, MonitorInfo, WindowChanged, WindowId, WindowOpenData},
19};
20use serde::{Deserialize, Serialize};
21use std::fmt;
22use zng_txt::Txt;
23use zng_unit::{DipPoint, PxRect, PxSize, Rgba};
24
25macro_rules! declare_id {
26    ($(
27        $(#[$docs:meta])+
28        pub struct $Id:ident(_);
29    )+) => {$(
30        $(#[$docs])+
31        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
32        #[serde(transparent)]
33        pub struct $Id(u32);
34
35        impl $Id {
36            /// Dummy ID, zero.
37            pub const INVALID: Self = Self(0);
38
39            /// Create the first valid ID.
40            pub const fn first() -> Self {
41                Self(1)
42            }
43
44            /// Create the next ID.
45            ///
46            /// IDs wrap around to [`first`] when the entire `u32` space is used, it is never `INVALID`.
47            ///
48            /// [`first`]: Self::first
49            #[must_use]
50            pub const fn next(self) -> Self {
51                let r = Self(self.0.wrapping_add(1));
52                if r.0 == Self::INVALID.0 {
53                    Self::first()
54                } else {
55                    r
56                }
57            }
58
59            /// Returns self and replace self with [`next`].
60            ///
61            /// [`next`]: Self::next
62            #[must_use]
63            pub fn incr(&mut self) -> Self {
64                std::mem::replace(self, self.next())
65            }
66
67            /// Get the raw ID.
68            pub const fn get(self) -> u32 {
69                self.0
70            }
71
72            /// Create an ID using a custom value.
73            ///
74            /// Note that only the documented process must generate IDs, and that it must only
75            /// generate IDs using this function or the [`next`] function.
76            ///
77            /// If the `id` is zero it will still be [`INVALID`] and handled differently by the other process,
78            /// zero is never valid.
79            ///
80            /// [`next`]: Self::next
81            /// [`INVALID`]: Self::INVALID
82            pub const fn from_raw(id: u32) -> Self {
83                Self(id)
84            }
85        }
86    )+};
87}
88
89pub(crate) use declare_id;
90
91declare_id! {
92    /// View-process generation, starts at one and changes every respawn, it is never zero.
93    ///
94    /// The View Process defines the ID.
95    pub struct ViewProcessGen(_);
96}
97
98/// Identifier for a specific analog axis on some device.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
100#[serde(transparent)]
101pub struct AxisId(pub u32);
102
103/// Identifier for a drag drop operation.
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
105#[serde(transparent)]
106pub struct DragDropId(pub u32);
107
108#[derive(Debug, Clone, Serialize, Deserialize)]
109/// View process is connected and ready.
110///
111/// The [`ViewProcessGen`] is the generation of the new view-process, it must be passed to
112/// [`Controller::handle_inited`].
113///
114/// [`Controller::handle_inited`]: crate::Controller::handle_inited
115#[non_exhaustive]
116pub struct Inited {
117    /// View-process generation, changes after respawns and is never zero.
118    pub generation: ViewProcessGen,
119    /// If the view-process is a respawn from a previous crashed process.
120    pub is_respawn: bool,
121    /// API extensions implemented by the view-process.
122    ///
123    /// The extension IDs will stay valid for the duration of the view-process.
124    pub extensions: ApiExtensions,
125}
126impl Inited {
127    /// New response.
128    #[allow(clippy::too_many_arguments)] // already grouping stuff.
129    pub fn new(generation: ViewProcessGen, is_respawn: bool, extensions: ApiExtensions) -> Self {
130        Self {
131            generation,
132            is_respawn,
133            extensions,
134        }
135    }
136}
137
138/// IME preview or insert event.
139#[derive(Debug, Clone, Serialize, Deserialize)]
140pub enum Ime {
141    /// Preview an IME insert at the last non-preview caret/selection.
142    ///
143    /// The associated values are the preview string and caret/selection inside the preview string.
144    ///
145    /// The preview must visually replace the last non-preview selection or insert at the last non-preview
146    /// caret index. If the preview string is empty the preview must be cancelled.
147    Preview(Txt, (usize, usize)),
148
149    /// Apply an IME insert at the last non-preview caret/selection. The caret must be moved to
150    /// the end of the inserted sub-string.
151    Commit(Txt),
152}
153
154/// System and User events sent from the View Process.
155#[derive(Debug, Clone, Serialize, Deserialize)]
156#[non_exhaustive]
157pub enum Event {
158    /// View-process inited.
159    Inited(Inited),
160    /// View-process suspended.
161    Suspended,
162
163    /// The event channel disconnected, probably because the view-process crashed.
164    ///
165    /// The [`ViewProcessGen`] is the generation of the view-process that was lost, it must be passed to
166    /// [`Controller::handle_disconnect`].
167    ///
168    /// [`Controller::handle_disconnect`]: crate::Controller::handle_disconnect
169    Disconnected(ViewProcessGen),
170
171    /// Window, context and renderer have finished initializing and is ready to receive commands.
172    WindowOpened(WindowId, WindowOpenData),
173
174    /// Headless context and renderer have finished initializing and is ready to receive commands.
175    HeadlessOpened(WindowId, HeadlessOpenData),
176
177    /// Window open or headless context open request failed.
178    WindowOrHeadlessOpenError {
179        /// Id from the request.
180        id: WindowId,
181        /// Error message.
182        error: Txt,
183    },
184
185    /// A frame finished rendering.
186    ///
187    /// `EventsCleared` is not send after this event.
188    FrameRendered(EventFrameRendered),
189
190    /// Window moved, resized, or minimized/maximized etc.
191    ///
192    /// This event aggregates events moves, resizes and other state changes into a
193    /// single event to simplify tracking composite changes, for example, the window changes size and position
194    /// when maximized, this can be trivially observed with this event.
195    ///
196    /// The [`EventCause`] can be used to identify a state change initiated by the app.
197    ///
198    /// [`EventCause`]: crate::window::EventCause
199    WindowChanged(WindowChanged),
200
201    /// A drag&drop gesture started dragging over the window.
202    DragHovered {
203        /// Window that is hovered.
204        window: WindowId,
205        /// Data payload.
206        data: Vec<DragDropData>,
207        /// Allowed effects.
208        allowed: DragDropEffect,
209    },
210    /// A drag&drop gesture moved over the window.
211    DragMoved {
212        /// Window that is hovered.
213        window: WindowId,
214        /// Cursor positions in between the previous event and this one.
215        coalesced_pos: Vec<DipPoint>,
216        /// Cursor position, relative to the window top-left in device independent pixels.
217        position: DipPoint,
218    },
219    /// A drag&drop gesture finished over the window.
220    DragDropped {
221        /// Window that received the file drop.
222        window: WindowId,
223        /// Data payload.
224        data: Vec<DragDropData>,
225        /// Allowed effects.
226        allowed: DragDropEffect,
227        /// ID of this drop operation.
228        ///
229        /// Handlers must call `drag_dropped` with this ID and what effect was applied to the data.
230        drop_id: DragDropId,
231    },
232    /// A drag&drop gesture stopped hovering the window without dropping.
233    DragCancelled {
234        /// Window that was previous hovered.
235        window: WindowId,
236    },
237    /// A drag started by the app was dropped or canceled.
238    AppDragEnded {
239        /// Window that started the drag.
240        window: WindowId,
241        /// Drag ID.
242        drag: DragDropId,
243        /// Effect applied to the data by the drop target.
244        ///
245        /// Is a single flag if the data was dropped in a valid drop target, or is empty if was canceled.
246        applied: DragDropEffect,
247    },
248
249    /// App window(s) focus changed.
250    FocusChanged {
251        /// Window that lost focus.
252        prev: Option<WindowId>,
253        /// Window that got focus.
254        new: Option<WindowId>,
255    },
256    /// An event from the keyboard has been received.
257    ///
258    /// This event is only send if the window is focused, all pressed keys should be considered released
259    /// after [`FocusChanged`] to `None`. Modifier keys receive special treatment, after they are pressed,
260    /// the modifier key state is monitored directly so that the `Released` event is always send, unless the
261    /// focus changed to none.
262    ///
263    /// [`FocusChanged`]: Self::FocusChanged
264    KeyboardInput {
265        /// Window that received the key event.
266        window: WindowId,
267        /// Device that generated the key event.
268        device: InputDeviceId,
269        /// Physical key.
270        key_code: KeyCode,
271        /// If the key was pressed or released.
272        state: KeyState,
273        /// The location of the key on the keyboard.
274        key_location: KeyLocation,
275
276        /// Semantic key unmodified.
277        ///
278        /// Pressing `Shift+A` key will produce `Key::Char('a')` in QWERTY keyboards, the modifiers are not applied. Note that
279        /// the numpad keys do not represents the numbers unmodified
280        key: Key,
281        /// Semantic key modified by the current active modifiers.
282        ///
283        /// Pressing `Shift+A` key will produce `Key::Char('A')` in QWERTY keyboards, the modifiers are applied.
284        key_modified: Key,
285        /// Text typed.
286        ///
287        /// This is only set during [`KeyState::Pressed`] of a key that generates text.
288        ///
289        /// This is usually the `key_modified` char, but is also `'\r'` for `Key::Enter`. On Windows when a dead key was
290        /// pressed earlier but cannot be combined with the character from this key press, the produced text
291        /// will consist of two characters: the dead-key-character followed by the character resulting from this key press.
292        text: Txt,
293    },
294    /// IME composition event.
295    Ime {
296        /// Window that received the IME event.
297        window: WindowId,
298        /// IME event.
299        ime: Ime,
300    },
301
302    /// The mouse cursor has moved on the window.
303    ///
304    /// This event can be coalesced, i.e. multiple cursor moves packed into the same event.
305    MouseMoved {
306        /// Window that received the cursor move.
307        window: WindowId,
308        /// Device that generated the cursor move.
309        device: InputDeviceId,
310
311        /// Cursor positions in between the previous event and this one.
312        coalesced_pos: Vec<DipPoint>,
313
314        /// Cursor position, relative to the window top-left in device independent pixels.
315        position: DipPoint,
316    },
317
318    /// The mouse cursor has entered the window.
319    MouseEntered {
320        /// Window that now is hovered by the cursor.
321        window: WindowId,
322        /// Device that generated the cursor move event.
323        device: InputDeviceId,
324    },
325    /// The mouse cursor has left the window.
326    MouseLeft {
327        /// Window that is no longer hovered by the cursor.
328        window: WindowId,
329        /// Device that generated the cursor move event.
330        device: InputDeviceId,
331    },
332    /// A mouse wheel movement or touchpad scroll occurred.
333    MouseWheel {
334        /// Window that was hovered by the cursor when the mouse wheel was used.
335        window: WindowId,
336        /// Device that generated the mouse wheel event.
337        device: InputDeviceId,
338        /// Delta of change in the mouse scroll wheel state.
339        delta: MouseScrollDelta,
340        /// Touch state if the device that generated the event is a touchpad.
341        phase: TouchPhase,
342    },
343    /// An mouse button press has been received.
344    MouseInput {
345        /// Window that was hovered by the cursor when the mouse button was used.
346        window: WindowId,
347        /// Mouse device that generated the event.
348        device: InputDeviceId,
349        /// If the button was pressed or released.
350        state: ButtonState,
351        /// The mouse button.
352        button: MouseButton,
353    },
354    /// Touchpad pressure event.
355    TouchpadPressure {
356        /// Window that was hovered when the touchpad was touched.
357        window: WindowId,
358        /// Touchpad device.
359        device: InputDeviceId,
360        /// Pressure level between 0 and 1.
361        pressure: f32,
362        /// Click level.
363        stage: i64,
364    },
365    /// Motion on some analog axis. May report data redundant to other, more specific events.
366    AxisMotion {
367        /// Window that was focused when the motion was realized.
368        window: WindowId,
369        /// Analog device.
370        device: InputDeviceId,
371        /// Axis.
372        axis: AxisId,
373        /// Motion value.
374        value: f64,
375    },
376    /// Touch event has been received.
377    Touch {
378        /// Window that was touched.
379        window: WindowId,
380        /// Touch device.
381        device: InputDeviceId,
382
383        /// Coalesced touch updates, never empty.
384        touches: Vec<TouchUpdate>,
385    },
386    /// The monitor’s scale factor has changed.
387    ScaleFactorChanged {
388        /// Monitor that has changed.
389        monitor: MonitorId,
390        /// Windows affected by this change.
391        ///
392        /// Note that a window's scale factor can also change if it is moved to another monitor,
393        /// the [`Event::WindowChanged`] event notifies this using the [`WindowChanged::monitor`].
394        windows: Vec<WindowId>,
395        /// The new scale factor.
396        scale_factor: f32,
397    },
398
399    /// The available monitors have changed.
400    MonitorsChanged(Vec<(MonitorId, MonitorInfo)>),
401    /// The available audio input and output devices have changed.
402    AudioDevicesChanged(Vec<(AudioDeviceId, AudioDeviceInfo)>),
403    /// The available raw input devices have changed.
404    InputDevicesChanged(Vec<(InputDeviceId, InputDeviceInfo)>),
405
406    /// The window has been requested to close.
407    WindowCloseRequested(WindowId),
408    /// The window has closed.
409    WindowClosed(WindowId),
410
411    /// An image resource already decoded size and PPI.
412    ImageMetadataLoaded {
413        /// The image that started loading.
414        image: ImageId,
415        /// The image pixel size.
416        size: PxSize,
417        /// The image pixels-per-inch metadata.
418        ppi: Option<ImagePpi>,
419        /// The image is a single channel R8.
420        is_mask: bool,
421    },
422    /// An image resource finished decoding.
423    ImageLoaded(ImageLoadedData),
424    /// An image resource, progressively decoded has decoded more bytes.
425    ImagePartiallyLoaded {
426        /// The image that has decoded more pixels.
427        image: ImageId,
428        /// The size of the decoded pixels, can be different then the image size if the
429        /// image is not *interlaced*.
430        partial_size: PxSize,
431        /// The image pixels-per-inch metadata.
432        ppi: Option<ImagePpi>,
433        /// If the decoded pixels so-far are all opaque (255 alpha).
434        is_opaque: bool,
435        /// If the decoded pixels so-far are a single channel.
436        is_mask: bool,
437        /// Updated BGRA8 pre-multiplied pixel buffer or R8 if `is_mask`. This includes all the pixels
438        /// decoded so-far.
439        partial_pixels: IpcBytes,
440    },
441    /// An image resource failed to decode, the image ID is not valid.
442    ImageLoadError {
443        /// The image that failed to decode.
444        image: ImageId,
445        /// The error message.
446        error: Txt,
447    },
448    /// An image finished encoding.
449    ImageEncoded {
450        /// The image that finished encoding.
451        image: ImageId,
452        /// The format of the encoded data.
453        format: Txt,
454        /// The encoded image data.
455        data: IpcBytes,
456    },
457    /// An image failed to encode.
458    ImageEncodeError {
459        /// The image that failed to encode.
460        image: ImageId,
461        /// The encoded format that was requested.
462        format: Txt,
463        /// The error message.
464        error: Txt,
465    },
466
467    /// An image generated from a rendered frame is ready.
468    FrameImageReady {
469        /// Window that had pixels copied.
470        window: WindowId,
471        /// The frame that was rendered when the pixels where copied.
472        frame: FrameId,
473        /// The frame image.
474        image: ImageId,
475        /// The pixel selection relative to the top-left.
476        selection: PxRect,
477    },
478
479    /* Config events */
480    /// System fonts have changed.
481    FontsChanged,
482    /// System text anti-aliasing configuration has changed.
483    FontAaChanged(FontAntiAliasing),
484    /// System double-click definition changed.
485    MultiClickConfigChanged(MultiClickConfig),
486    /// System animations config changed.
487    AnimationsConfigChanged(AnimationsConfig),
488    /// System definition of pressed key repeat event changed.
489    KeyRepeatConfigChanged(KeyRepeatConfig),
490    /// System touch config changed.
491    TouchConfigChanged(TouchConfig),
492    /// System locale changed.
493    LocaleChanged(LocaleConfig),
494    /// System color scheme or colors changed.
495    ColorsConfigChanged(ColorsConfig),
496    /// System window chrome (decorations) preference changed.
497    ChromeConfigChanged(ChromeConfig),
498
499    /// Raw input device event.
500    InputDeviceEvent {
501        /// Device that generated the event.
502        device: InputDeviceId,
503        /// Event.
504        event: InputDeviceEvent,
505    },
506
507    /// User responded to a native message dialog.
508    MsgDialogResponse(DialogId, MsgDialogResponse),
509    /// User responded to a native file dialog.
510    FileDialogResponse(DialogId, FileDialogResponse),
511
512    /// Accessibility info tree is now required for the window.
513    AccessInit {
514        /// Window that must now build access info.
515        window: WindowId,
516    },
517    /// Accessibility command.
518    AccessCommand {
519        /// Window that had pixels copied.
520        window: WindowId,
521        /// Target widget.
522        target: AccessNodeId,
523        /// Command.
524        command: AccessCmd,
525    },
526    /// Accessibility info tree is no longer needed for the window.
527    ///
528    /// Note that accessibility may be enabled again after this. It is not an error
529    /// to send access updates after this, but they will be ignored.
530    AccessDeinit {
531        /// Window that can release access info.
532        window: WindowId,
533    },
534
535    /// System low memory warning, some platforms may kill the app if it does not release memory.
536    LowMemory,
537
538    /// An internal component panicked, but the view-process managed to recover from it without
539    /// needing to respawn.
540    RecoveredFromComponentPanic {
541        /// Component identifier.
542        component: Txt,
543        /// How the view-process recovered from the panic.
544        recover: Txt,
545        /// The panic.
546        panic: Txt,
547    },
548
549    /// Represents a custom event send by the extension.
550    ExtensionEvent(ApiExtensionId, ApiExtensionPayload),
551}
552impl Event {
553    /// Change `self` to incorporate `other` or returns `other` if both events cannot be coalesced.
554    #[expect(clippy::result_large_err)]
555    pub fn coalesce(&mut self, other: Event) -> Result<(), Event> {
556        use Event::*;
557
558        match (self, other) {
559            (
560                MouseMoved {
561                    window,
562                    device,
563                    coalesced_pos,
564                    position,
565                },
566                MouseMoved {
567                    window: n_window,
568                    device: n_device,
569                    coalesced_pos: n_coal_pos,
570                    position: n_pos,
571                },
572            ) if *window == n_window && *device == n_device => {
573                coalesced_pos.push(*position);
574                coalesced_pos.extend(n_coal_pos);
575                *position = n_pos;
576            }
577            (
578                DragMoved {
579                    window,
580                    coalesced_pos,
581                    position,
582                },
583                DragMoved {
584                    window: n_window,
585                    coalesced_pos: n_coal_pos,
586                    position: n_pos,
587                },
588            ) if *window == n_window => {
589                coalesced_pos.push(*position);
590                coalesced_pos.extend(n_coal_pos);
591                *position = n_pos;
592            }
593
594            (
595                InputDeviceEvent { device, event },
596                InputDeviceEvent {
597                    device: n_device,
598                    event: n_event,
599                },
600            ) if *device == n_device => {
601                if let Err(e) = event.coalesce(n_event) {
602                    return Err(InputDeviceEvent {
603                        device: n_device,
604                        event: e,
605                    });
606                }
607            }
608
609            // wheel scroll.
610            (
611                MouseWheel {
612                    window,
613                    device,
614                    delta: MouseScrollDelta::LineDelta(delta_x, delta_y),
615                    phase,
616                },
617                MouseWheel {
618                    window: n_window,
619                    device: n_device,
620                    delta: MouseScrollDelta::LineDelta(n_delta_x, n_delta_y),
621                    phase: n_phase,
622                },
623            ) if *window == n_window && *device == n_device && *phase == n_phase => {
624                *delta_x += n_delta_x;
625                *delta_y += n_delta_y;
626            }
627
628            // trackpad scroll-move.
629            (
630                MouseWheel {
631                    window,
632                    device,
633                    delta: MouseScrollDelta::PixelDelta(delta_x, delta_y),
634                    phase,
635                },
636                MouseWheel {
637                    window: n_window,
638                    device: n_device,
639                    delta: MouseScrollDelta::PixelDelta(n_delta_x, n_delta_y),
640                    phase: n_phase,
641                },
642            ) if *window == n_window && *device == n_device && *phase == n_phase => {
643                *delta_x += n_delta_x;
644                *delta_y += n_delta_y;
645            }
646
647            // touch
648            (
649                Touch { window, device, touches },
650                Touch {
651                    window: n_window,
652                    device: n_device,
653                    touches: mut n_touches,
654                },
655            ) if *window == n_window && *device == n_device => {
656                touches.append(&mut n_touches);
657            }
658
659            // window changed.
660            (WindowChanged(change), WindowChanged(n_change))
661                if change.window == n_change.window && change.cause == n_change.cause && change.frame_wait_id.is_none() =>
662            {
663                if n_change.state.is_some() {
664                    change.state = n_change.state;
665                }
666
667                if n_change.position.is_some() {
668                    change.position = n_change.position;
669                }
670
671                if n_change.monitor.is_some() {
672                    change.monitor = n_change.monitor;
673                }
674
675                if n_change.size.is_some() {
676                    change.size = n_change.size;
677                }
678
679                if n_change.safe_padding.is_some() {
680                    change.safe_padding = n_change.safe_padding;
681                }
682
683                change.frame_wait_id = n_change.frame_wait_id;
684            }
685            // window focus changed.
686            (FocusChanged { prev, new }, FocusChanged { prev: n_prev, new: n_new })
687                if prev.is_some() && new.is_none() && n_prev.is_none() && n_new.is_some() =>
688            {
689                *new = n_new;
690            }
691            // IME commit replaces preview.
692            (
693                Ime {
694                    window,
695                    ime: ime @ self::Ime::Preview(_, _),
696                },
697                Ime {
698                    window: n_window,
699                    ime: n_ime @ self::Ime::Commit(_),
700                },
701            ) if *window == n_window => {
702                *ime = n_ime;
703            }
704            // scale factor.
705            (
706                ScaleFactorChanged {
707                    monitor,
708                    windows,
709                    scale_factor,
710                },
711                ScaleFactorChanged {
712                    monitor: n_monitor,
713                    windows: n_windows,
714                    scale_factor: n_scale_factor,
715                },
716            ) if *monitor == n_monitor => {
717                for w in n_windows {
718                    if !windows.contains(&w) {
719                        windows.push(w);
720                    }
721                }
722                *scale_factor = n_scale_factor;
723            }
724            // fonts changed.
725            (FontsChanged, FontsChanged) => {}
726            // text aa.
727            (FontAaChanged(config), FontAaChanged(n_config)) => {
728                *config = n_config;
729            }
730            // double-click timeout.
731            (MultiClickConfigChanged(config), MultiClickConfigChanged(n_config)) => {
732                *config = n_config;
733            }
734            // touch config.
735            (TouchConfigChanged(config), TouchConfigChanged(n_config)) => {
736                *config = n_config;
737            }
738            // animation enabled and caret speed.
739            (AnimationsConfigChanged(config), AnimationsConfigChanged(n_config)) => {
740                *config = n_config;
741            }
742            // key repeat delay and speed.
743            (KeyRepeatConfigChanged(config), KeyRepeatConfigChanged(n_config)) => {
744                *config = n_config;
745            }
746            // locale
747            (LocaleChanged(config), LocaleChanged(n_config)) => {
748                *config = n_config;
749            }
750            // drag hovered
751            (
752                DragHovered {
753                    window,
754                    data,
755                    allowed: effects,
756                },
757                DragHovered {
758                    window: n_window,
759                    data: mut n_data,
760                    allowed: n_effects,
761                },
762            ) if *window == n_window && effects.contains(n_effects) => {
763                data.append(&mut n_data);
764            }
765            // drag dropped
766            (
767                DragDropped {
768                    window,
769                    data,
770                    allowed,
771                    drop_id,
772                },
773                DragDropped {
774                    window: n_window,
775                    data: mut n_data,
776                    allowed: n_allowed,
777                    drop_id: n_drop_id,
778                },
779            ) if *window == n_window && allowed.contains(n_allowed) && *drop_id == n_drop_id => {
780                data.append(&mut n_data);
781            }
782            // drag cancelled
783            (DragCancelled { window }, DragCancelled { window: n_window }) if *window == n_window => {}
784            // input devices changed
785            (InputDevicesChanged(devices), InputDevicesChanged(n_devices)) => {
786                *devices = n_devices;
787            }
788            // audio devices changed
789            (AudioDevicesChanged(devices), AudioDevicesChanged(n_devices)) => {
790                *devices = n_devices;
791            }
792            (_, e) => return Err(e),
793        }
794        Ok(())
795    }
796}
797
798/// View Process IPC result.
799pub(crate) type VpResult<T> = std::result::Result<T, ipc::ViewChannelError>;
800
801/// Offset and color in a gradient.
802#[repr(C)]
803#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Serialize)]
804pub struct GradientStop {
805    /// Offset in pixels.
806    pub offset: f32,
807    /// Color at the offset.
808    pub color: Rgba,
809}
810
811/// Border side line style and color.
812#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Serialize)]
813pub struct BorderSide {
814    /// Line color.
815    pub color: Rgba,
816    /// Line Style.
817    pub style: BorderStyle,
818}
819
820/// Defines if a widget is part of the same 3D space as the parent.
821#[derive(Default, Clone, Copy, serde::Deserialize, Eq, Hash, PartialEq, serde::Serialize)]
822#[repr(u8)]
823pub enum TransformStyle {
824    /// Widget is not a part of the 3D space of the parent. If it has
825    /// 3D children they will be rendered into a flat plane that is placed in the 3D space of the parent.
826    #[default]
827    Flat = 0,
828    /// Widget is a part of the 3D space of the parent. If it has 3D children
829    /// they will be positioned relative to siblings in the same space.
830    ///
831    /// Note that some properties require a flat image to work on, in particular all pixel filter properties including opacity.
832    /// When such a property is set in a widget that is `Preserve3D` and has both a parent and one child also `Preserve3D` the
833    /// filters are ignored and a warning is logged. When the widget is `Preserve3D` and the parent is not the filters are applied
834    /// *outside* the 3D space, when the widget is `Preserve3D` with all `Flat` children the filters are applied *inside* the 3D space.
835    Preserve3D = 1,
836}
837impl fmt::Debug for TransformStyle {
838    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
839        if f.alternate() {
840            write!(f, "TransformStyle::")?;
841        }
842        match self {
843            Self::Flat => write!(f, "Flat"),
844            Self::Preserve3D => write!(f, "Preserve3D"),
845        }
846    }
847}
848
849/// Identifies a reference frame.
850///
851/// This ID is mostly defined by the app process. IDs that set the most significant
852/// bit of the second part (`id.1 & (1 << 63) != 0`) are reserved for the view process.
853#[derive(Default, Debug, Clone, Copy, serde::Deserialize, Eq, Hash, PartialEq, serde::Serialize)]
854pub struct ReferenceFrameId(pub u64, pub u64);
855impl ReferenceFrameId {
856    /// If ID does not set the bit that indicates it is generated by the view process.
857    pub fn is_app_generated(&self) -> bool {
858        self.1 & (1 << 63) == 0
859    }
860}
861
862/// Nine-patch border repeat mode.
863///
864/// Defines how the edges and middle region of a nine-patch border is filled.
865#[repr(u8)]
866#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, Default)]
867pub enum RepeatMode {
868    /// The source image's edge regions are stretched to fill the gap between each border.
869    #[default]
870    Stretch,
871    /// The source image's edge regions are tiled (repeated) to fill the gap between each
872    /// border. Tiles may be clipped to achieve the proper fit.
873    Repeat,
874    /// The source image's edge regions are tiled (repeated) to fill the gap between each
875    /// border. Tiles may be stretched to achieve the proper fit.
876    Round,
877    /// The source image's edge regions are tiled (repeated) to fill the gap between each
878    /// border. Extra space will be distributed in between tiles to achieve the proper fit.
879    Space,
880}
881#[cfg(feature = "var")]
882zng_var::impl_from_and_into_var! {
883    /// Converts `true` to `Repeat` and `false` to the default `Stretch`.
884    fn from(value: bool) -> RepeatMode {
885        match value {
886            true => RepeatMode::Repeat,
887            false => RepeatMode::Stretch,
888        }
889    }
890}
891
892/// Color mix blend mode.
893#[allow(missing_docs)]
894#[repr(u8)]
895#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, Default)]
896#[non_exhaustive]
897pub enum MixBlendMode {
898    #[default]
899    Normal = 0,
900    Multiply = 1,
901    Screen = 2,
902    Overlay = 3,
903    Darken = 4,
904    Lighten = 5,
905    ColorDodge = 6,
906    ColorBurn = 7,
907    HardLight = 8,
908    SoftLight = 9,
909    Difference = 10,
910    Exclusion = 11,
911    Hue = 12,
912    Saturation = 13,
913    Color = 14,
914    Luminosity = 15,
915    PlusLighter = 16,
916}
917
918/// Image scaling algorithm in the renderer.
919///
920/// If an image is not rendered at the same size as their source it must be up-scaled or
921/// down-scaled. The algorithms used for this scaling can be selected using this `enum`.
922///
923/// Note that the algorithms used in the renderer value performance over quality and do a good
924/// enough job for small or temporary changes in scale only, such as a small size correction or a scaling animation.
925/// If and image is constantly rendered at a different scale you should considered scaling it on the CPU using a
926/// slower but more complex algorithm or pre-scaling it before including in the app.
927#[repr(u8)]
928#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize)]
929#[non_exhaustive]
930pub enum ImageRendering {
931    /// Let the renderer select the algorithm, currently this is the same as [`CrispEdges`].
932    ///
933    /// [`CrispEdges`]: ImageRendering::CrispEdges
934    Auto = 0,
935    /// The image is scaled with an algorithm that preserves contrast and edges in the image,
936    /// and which does not smooth colors or introduce blur to the image in the process.
937    ///
938    /// Currently the [Bilinear] interpolation algorithm is used.
939    ///
940    /// [Bilinear]: https://en.wikipedia.org/wiki/Bilinear_interpolation
941    CrispEdges = 1,
942    /// When scaling the image up, the image appears to be composed of large pixels.
943    ///
944    /// Currently the [Nearest-neighbor] interpolation algorithm is used.
945    ///
946    /// [Nearest-neighbor]: https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation
947    Pixelated = 2,
948}
949
950/// Pixel color alpha type.
951#[repr(u8)]
952#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
953pub enum AlphaType {
954    /// Components are not pre-multiplied by alpha.
955    Alpha = 0,
956    /// Components are pre-multiplied by alpha.
957    PremultipliedAlpha = 1,
958}
959
960/// Gradient extend mode.
961#[allow(missing_docs)]
962#[repr(u8)]
963#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize, Ord, PartialOrd)]
964pub enum ExtendMode {
965    Clamp,
966    Repeat,
967}
968
969/// Orientation of a straight line.
970#[derive(Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
971pub enum LineOrientation {
972    /// Top-to-bottom line.
973    Vertical,
974    /// Left-to-right line.
975    Horizontal,
976}
977impl fmt::Debug for LineOrientation {
978    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
979        if f.alternate() {
980            write!(f, "LineOrientation::")?;
981        }
982        match self {
983            LineOrientation::Vertical => {
984                write!(f, "Vertical")
985            }
986            LineOrientation::Horizontal => {
987                write!(f, "Horizontal")
988            }
989        }
990    }
991}
992
993/// Represents a line style.
994#[allow(missing_docs)]
995#[repr(u8)]
996#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
997#[non_exhaustive]
998pub enum LineStyle {
999    Solid,
1000    Dotted,
1001    Dashed,
1002
1003    /// A wavy line, like an error underline.
1004    ///
1005    /// The wave magnitude is defined by the overall line thickness, the associated value
1006    /// here defines the thickness of the wavy line.
1007    Wavy(f32),
1008}
1009
1010/// The line style for the sides of a widget's border.
1011#[repr(u8)]
1012#[derive(Default, Debug, Clone, Copy, PartialEq, Hash, Eq, serde::Serialize, serde::Deserialize)]
1013#[non_exhaustive]
1014pub enum BorderStyle {
1015    /// No border line.
1016    #[default]
1017    None = 0,
1018
1019    /// A single straight solid line.
1020    Solid = 1,
1021    /// Two straight solid lines that add up to the pixel size defined by the side width.
1022    Double = 2,
1023
1024    /// Displays a series of rounded dots.
1025    Dotted = 3,
1026    /// Displays a series of short square-ended dashes or line segments.
1027    Dashed = 4,
1028
1029    /// Fully transparent line.
1030    Hidden = 5,
1031
1032    /// Displays a border with a carved appearance.
1033    Groove = 6,
1034    /// Displays a border with an extruded appearance.
1035    Ridge = 7,
1036
1037    /// Displays a border that makes the widget appear embedded.
1038    Inset = 8,
1039    /// Displays a border that makes the widget appear embossed.
1040    Outset = 9,
1041}
1042
1043/// Result of a focus request.
1044#[repr(u8)]
1045#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
1046#[non_exhaustive]
1047pub enum FocusResult {
1048    /// Focus was requested, an [`Event::FocusChanged`] will be send if the operating system gives focus to the window.
1049    Requested,
1050    /// Window is already focused.
1051    AlreadyFocused,
1052}
1053
1054/// Defines what raw device events the view-process instance should monitor and notify.
1055///
1056/// Raw device events are global and can be received even when the app has no visible window.
1057///
1058/// These events are disabled by default as they can impact performance or may require special security clearance,
1059/// depending on the view-process implementation and operating system.
1060#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
1061#[non_exhaustive]
1062pub struct DeviceEventsFilter {
1063    /// What raw input events should be watched/send.
1064    ///
1065    /// Note that although the view-process will filter input device events using these flags setting
1066    /// just one of them may cause a general native listener to init.
1067    pub input: InputDeviceCapability,
1068}
1069impl DeviceEventsFilter {
1070    /// Default value, no device events are needed.
1071    pub fn empty() -> Self {
1072        Self {
1073            input: InputDeviceCapability::empty(),
1074        }
1075    }
1076
1077    /// If the filter does not include any event.
1078    pub fn is_empty(&self) -> bool {
1079        self.input.is_empty()
1080    }
1081
1082    /// New with input device events needed.
1083    pub fn new(input: InputDeviceCapability) -> Self {
1084        Self { input }
1085    }
1086}
1087impl Default for DeviceEventsFilter {
1088    fn default() -> Self {
1089        Self::empty()
1090    }
1091}
1092
1093#[cfg(test)]
1094mod tests {
1095    use super::*;
1096
1097    #[test]
1098    fn key_code_iter() {
1099        let mut iter = KeyCode::all_identified();
1100        let first = iter.next().unwrap();
1101        assert_eq!(first, KeyCode::Backquote);
1102
1103        for k in iter {
1104            assert_eq!(k.name(), &format!("{k:?}"));
1105        }
1106    }
1107}