Skip to main content

zng_view_api/
types.rs

1//! General event types.
2
3use crate::{
4    access::{AccessCmd, AccessNodeId},
5    api_extension::{ApiExtensionId, ApiExtensionPayload, ApiExtensions},
6    audio::{AudioDecoded, AudioDeviceId, AudioDeviceInfo, AudioId, AudioMetadata, AudioOutputId, AudioOutputOpenData, AudioPlayId},
7    config::{AnimationsConfig, ColorsConfig, FontAntiAliasing, KeyRepeatConfig, LocaleConfig, MultiClickConfig, TouchConfig},
8    dialog::{DialogId, FileDialogResponse, MsgDialogResponse, NotificationResponse},
9    drag_drop::{DragDropData, DragDropEffect},
10    image::{ImageDecoded, ImageEncodeId, ImageId, ImageMetadata},
11    keyboard::{Key, KeyCode, KeyLocation, KeyState},
12    mouse::{ButtonState, MouseButton, MouseScrollDelta},
13    raw_input::{InputDeviceCapability, InputDeviceEvent, InputDeviceId, InputDeviceInfo},
14    touch::{TouchPhase, TouchUpdate},
15    window::{EventFrameRendered, HeadlessOpenData, MonitorId, MonitorInfo, WindowChanged, WindowId, WindowOpenData},
16};
17
18use serde::{Deserialize, Serialize};
19use std::fmt;
20use zng_task::channel::{ChannelError, IpcBytes};
21use zng_txt::Txt;
22use zng_unit::{DipPoint, Rgba};
23
24macro_rules! declare_id {
25    ($(
26        $(#[$docs:meta])+
27        pub struct $Id:ident(_);
28    )+) => {$(
29        $(#[$docs])+
30        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
31        #[serde(transparent)]
32        pub struct $Id(u32);
33
34        impl $Id {
35            /// Dummy ID, zero.
36            pub const INVALID: Self = Self(0);
37
38            /// Create the first valid ID.
39            pub const fn first() -> Self {
40                Self(1)
41            }
42
43            /// Create the next ID.
44            ///
45            /// IDs wrap around to [`first`] when the entire `u32` space is used, it is never `INVALID`.
46            ///
47            /// [`first`]: Self::first
48            #[must_use]
49            pub const fn next(self) -> Self {
50                let r = Self(self.0.wrapping_add(1));
51                if r.0 == Self::INVALID.0 {
52                    Self::first()
53                } else {
54                    r
55                }
56            }
57
58            /// Returns self and replace self with [`next`].
59            ///
60            /// [`next`]: Self::next
61            #[must_use]
62            pub fn incr(&mut self) -> Self {
63                std::mem::replace(self, self.next())
64            }
65
66            /// Get the raw ID.
67            pub const fn get(self) -> u32 {
68                self.0
69            }
70
71            /// Create an ID using a custom value.
72            ///
73            /// Note that only the documented process must generate IDs, and that it must only
74            /// generate IDs using this function or the [`next`] function.
75            ///
76            /// If the `id` is zero it will still be [`INVALID`] and handled differently by the other process,
77            /// zero is never valid.
78            ///
79            /// [`next`]: Self::next
80            /// [`INVALID`]: Self::INVALID
81            pub const fn from_raw(id: u32) -> Self {
82                Self(id)
83            }
84        }
85    )+};
86}
87
88pub(crate) use declare_id;
89
90declare_id! {
91    /// View-process generation, starts at one and changes every respawn, it is never zero.
92    ///
93    /// The View Process defines the ID.
94    pub struct ViewProcessGen(_);
95}
96
97/// Identifier for a specific analog axis on some device.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
99#[serde(transparent)]
100pub struct AxisId(pub u32);
101
102/// Identifier for a drag drop operation.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
104#[serde(transparent)]
105pub struct DragDropId(pub u32);
106
107/// View-process implementation info.
108///
109/// The view-process implementation may not cover the full API, depending on operating system, build, headless mode.
110/// When the view-process does not implement something it just logs an error and ignores the request, this struct contains
111/// detailed info about what operations are available in the view-process instance.
112#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
113#[non_exhaustive]
114pub struct ViewProcessInfo {
115    /// View-process generation, changes after respawns and is never zero.
116    pub generation: ViewProcessGen,
117    /// If the view-process is a respawn from a previous crashed process.
118    pub is_respawn: bool,
119
120    /// Input device events implemented by the view-process.
121    pub input_device: InputDeviceCapability,
122
123    /// Window operations implemented by the view-process.
124    pub window: crate::window::WindowCapability,
125
126    /// Dialog operations implemented by the view-process.
127    pub dialog: crate::dialog::DialogCapability,
128
129    /// System menu capabilities.
130    pub menu: crate::menu::MenuCapability,
131
132    /// Clipboard data types and operations implemented by the view-process.
133    pub clipboard: crate::clipboard::ClipboardTypes,
134
135    /// Image decode and encode capabilities implemented by the view-process.
136    pub image: Vec<crate::image::ImageFormat>,
137
138    /// Audio decode and encode capabilities implemented by the view-process.
139    pub audio: Vec<crate::audio::AudioFormat>,
140
141    /// API extensions implemented by the view-process.
142    ///
143    /// The extension IDs will stay valid for the duration of the view-process.
144    pub extensions: ApiExtensions,
145}
146impl ViewProcessInfo {
147    /// New response.
148    pub const fn new(generation: ViewProcessGen, is_respawn: bool) -> Self {
149        Self {
150            generation,
151            is_respawn,
152            input_device: InputDeviceCapability::empty(),
153            window: crate::window::WindowCapability::empty(),
154            dialog: crate::dialog::DialogCapability::empty(),
155            menu: crate::menu::MenuCapability::empty(),
156            clipboard: crate::clipboard::ClipboardTypes::new(vec![], vec![], false),
157            image: vec![],
158            audio: vec![],
159            extensions: ApiExtensions::new(),
160        }
161    }
162}
163
164/// IME preview or insert event.
165#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
166pub enum Ime {
167    /// Preview an IME insert at the last non-preview caret/selection.
168    ///
169    /// The associated values are the preview string and caret/selection inside the preview string.
170    ///
171    /// The preview must visually replace the last non-preview selection or insert at the last non-preview
172    /// caret index. If the preview string is empty the preview must be cancelled.
173    Preview(Txt, (usize, usize)),
174
175    /// Apply an IME insert at the last non-preview caret/selection. The caret must be moved to
176    /// the end of the inserted sub-string.
177    Commit(Txt),
178}
179
180/// System and User events sent from the View Process.
181#[derive(Debug, Clone, Serialize, Deserialize)]
182#[non_exhaustive]
183pub enum Event {
184    /// View-process inited.
185    Inited(ViewProcessInfo),
186    /// View-process suspended.
187    Suspended,
188
189    /// The event channel disconnected, probably because the view-process crashed.
190    ///
191    /// The [`ViewProcessGen`] is the generation of the view-process that was lost, it must be passed to
192    /// [`Controller::handle_disconnect`].
193    ///
194    /// [`Controller::handle_disconnect`]: crate::Controller::handle_disconnect
195    Disconnected(ViewProcessGen),
196
197    /// Window, context and renderer have finished initializing and is ready to receive commands.
198    WindowOpened(WindowId, WindowOpenData),
199
200    /// Headless context and renderer have finished initializing and is ready to receive commands.
201    HeadlessOpened(WindowId, HeadlessOpenData),
202
203    /// Window open or headless context open request failed.
204    WindowOrHeadlessOpenError {
205        /// Id from the request.
206        id: WindowId,
207        /// Error message.
208        error: Txt,
209    },
210
211    /// A frame finished rendering.
212    FrameRendered(EventFrameRendered),
213
214    /// Window moved, resized, or minimized/maximized etc.
215    ///
216    /// This event aggregates events moves, resizes and other state changes into a
217    /// single event to simplify tracking composite changes, for example, the window changes size and position
218    /// when maximized, this can be trivially observed with this event.
219    ///
220    /// The [`EventCause`] can be used to identify a state change initiated by the app.
221    ///
222    /// [`EventCause`]: crate::window::EventCause
223    WindowChanged(WindowChanged),
224
225    /// A drag&drop gesture started dragging over the window.
226    DragHovered {
227        /// Window that is hovered.
228        window: WindowId,
229        /// Data payload.
230        data: Vec<DragDropData>,
231        /// Allowed effects.
232        allowed: DragDropEffect,
233    },
234    /// A drag&drop gesture moved over the window.
235    DragMoved {
236        /// Window that is hovered.
237        window: WindowId,
238        /// Cursor positions in between the previous event and this one.
239        coalesced_pos: Vec<DipPoint>,
240        /// Cursor position, relative to the window top-left in device independent pixels.
241        position: DipPoint,
242    },
243    /// A drag&drop gesture finished over the window.
244    DragDropped {
245        /// Window that received the file drop.
246        window: WindowId,
247        /// Data payload.
248        data: Vec<DragDropData>,
249        /// Allowed effects.
250        allowed: DragDropEffect,
251        /// ID of this drop operation.
252        ///
253        /// Handlers must call `drag_dropped` with this ID and what effect was applied to the data.
254        drop_id: DragDropId,
255    },
256    /// A drag&drop gesture stopped hovering the window without dropping.
257    DragCancelled {
258        /// Window that was previous hovered.
259        window: WindowId,
260    },
261    /// A drag started by the app was dropped or canceled.
262    AppDragEnded {
263        /// Window that started the drag.
264        window: WindowId,
265        /// Drag ID.
266        drag: DragDropId,
267        /// Effect applied to the data by the drop target.
268        ///
269        /// Is a single flag if the data was dropped in a valid drop target, or is empty if was canceled.
270        applied: DragDropEffect,
271    },
272
273    /// App window(s) focus changed.
274    FocusChanged {
275        /// Window that lost focus.
276        prev: Option<WindowId>,
277        /// Window that got focus.
278        new: Option<WindowId>,
279    },
280    /// An event from the keyboard has been received.
281    ///
282    /// This event is only send if the window is focused, all pressed keys should be considered released
283    /// after [`FocusChanged`] to `None`. Modifier keys receive special treatment, after they are pressed,
284    /// the modifier key state is monitored directly so that the `Released` event is always send, unless the
285    /// focus changed to none.
286    ///
287    /// [`FocusChanged`]: Self::FocusChanged
288    KeyboardInput {
289        /// Window that received the key event.
290        window: WindowId,
291        /// Device that generated the key event.
292        device: InputDeviceId,
293        /// Physical key.
294        key_code: KeyCode,
295        /// If the key was pressed or released.
296        state: KeyState,
297        /// The location of the key on the keyboard.
298        key_location: KeyLocation,
299
300        /// Semantic key unmodified.
301        ///
302        /// Pressing `Shift+A` key will produce `Key::Char('a')` in QWERTY keyboards, the modifiers are not applied. Note that
303        /// the numpad keys do not represents the numbers unmodified
304        key: Key,
305        /// Semantic key modified by the current active modifiers.
306        ///
307        /// Pressing `Shift+A` key will produce `Key::Char('A')` in QWERTY keyboards, the modifiers are applied.
308        key_modified: Key,
309        /// Text typed.
310        ///
311        /// This is only set during [`KeyState::Pressed`] of a key that generates text.
312        ///
313        /// This is usually the `key_modified` char, but is also `'\r'` for `Key::Enter`. On Windows when a dead key was
314        /// pressed earlier but cannot be combined with the character from this key press, the produced text
315        /// will consist of two characters: the dead-key-character followed by the character resulting from this key press.
316        text: Txt,
317    },
318    /// IME composition event.
319    Ime {
320        /// Window that received the IME event.
321        window: WindowId,
322        /// IME event.
323        ime: Ime,
324    },
325
326    /// The mouse cursor has moved on the window.
327    ///
328    /// This event can be coalesced, i.e. multiple cursor moves packed into the same event.
329    MouseMoved {
330        /// Window that received the cursor move.
331        window: WindowId,
332        /// Device that generated the cursor move.
333        device: InputDeviceId,
334
335        /// Cursor positions in between the previous event and this one.
336        coalesced_pos: Vec<DipPoint>,
337
338        /// Cursor position, relative to the window top-left in device independent pixels.
339        position: DipPoint,
340    },
341
342    /// The mouse cursor has entered the window.
343    MouseEntered {
344        /// Window that now is hovered by the cursor.
345        window: WindowId,
346        /// Device that generated the cursor move event.
347        device: InputDeviceId,
348    },
349    /// The mouse cursor has left the window.
350    MouseLeft {
351        /// Window that is no longer hovered by the cursor.
352        window: WindowId,
353        /// Device that generated the cursor move event.
354        device: InputDeviceId,
355    },
356    /// A mouse wheel movement or touchpad scroll occurred.
357    MouseWheel {
358        /// Window that was hovered by the cursor when the mouse wheel was used.
359        window: WindowId,
360        /// Device that generated the mouse wheel event.
361        device: InputDeviceId,
362        /// Delta of change in the mouse scroll wheel state.
363        delta: MouseScrollDelta,
364        /// Touch state if the device that generated the event is a touchpad.
365        phase: TouchPhase,
366    },
367    /// An mouse button press has been received.
368    MouseInput {
369        /// Window that was hovered by the cursor when the mouse button was used.
370        window: WindowId,
371        /// Mouse device that generated the event.
372        device: InputDeviceId,
373        /// If the button was pressed or released.
374        state: ButtonState,
375        /// The mouse button.
376        button: MouseButton,
377    },
378    /// Touchpad pressure event.
379    TouchpadPressure {
380        /// Window that was hovered when the touchpad was touched.
381        window: WindowId,
382        /// Touchpad device.
383        device: InputDeviceId,
384        /// Pressure level between 0 and 1.
385        pressure: f32,
386        /// Click level.
387        stage: i64,
388    },
389    /// Motion on some analog axis. May report data redundant to other, more specific events.
390    AxisMotion {
391        /// Window that was focused when the motion was realized.
392        window: WindowId,
393        /// Analog device.
394        device: InputDeviceId,
395        /// Axis.
396        axis: AxisId,
397        /// Motion value.
398        value: f64,
399    },
400    /// Touch event has been received.
401    Touch {
402        /// Window that was touched.
403        window: WindowId,
404        /// Touch device.
405        device: InputDeviceId,
406
407        /// Coalesced touch updates, never empty.
408        touches: Vec<TouchUpdate>,
409    },
410
411    /// The available monitors have changed or some property of a monitor changed.
412    MonitorsChanged(Vec<(MonitorId, MonitorInfo)>),
413    /// The available audio input and output devices have changed.
414    AudioDevicesChanged(Vec<(AudioDeviceId, AudioDeviceInfo)>),
415    /// The available raw input devices have changed.
416    InputDevicesChanged(Vec<(InputDeviceId, InputDeviceInfo)>),
417
418    /// The window has been requested to close.
419    WindowCloseRequested(WindowId),
420    /// The window has closed.
421    WindowClosed(WindowId),
422
423    /// An image resource already decoded header metadata.
424    ImageMetadataDecoded(ImageMetadata),
425    /// An image resource has partially or fully decoded.
426    ImageDecoded(ImageDecoded),
427    /// An image resource failed to decode, the image ID is not valid.
428    ImageDecodeError {
429        /// The image that failed to decode.
430        image: ImageId,
431        /// The error message.
432        error: Txt,
433    },
434    /// An image finished encoding.
435    ImageEncoded {
436        /// Id of the encode task.
437        task: ImageEncodeId,
438        /// The encoded image data.
439        data: IpcBytes,
440    },
441    /// An image failed to encode.
442    ImageEncodeError {
443        /// Id of the encode task.
444        task: ImageEncodeId,
445        /// The error message.
446        error: Txt,
447    },
448
449    /// An audio resource decoded header metadata.
450    AudioMetadataDecoded(AudioMetadata),
451    /// An audio resource decoded chunk or finished decoding.
452    AudioDecoded(AudioDecoded),
453    /// An audio resource failed to decode, the audio ID is not valid.
454    AudioDecodeError {
455        /// The audio that failed to decode.
456        audio: AudioId,
457        /// The error message.
458        error: Txt,
459    },
460
461    /// Audio output is connected with device and ready to receive commands.
462    AudioOutputOpened(AudioOutputId, AudioOutputOpenData),
463    /// Audio playback stream failed to connect.
464    AudioOutputOpenError {
465        /// The output ID.
466        id: AudioOutputId,
467        /// The error message.
468        error: Txt,
469    },
470    /// Audio playback failed.
471    AudioPlayError {
472        /// The request ID.
473        play: AudioPlayId,
474        /// The error message.
475        error: Txt,
476    },
477
478    /* Config events */
479    /// System fonts have changed.
480    FontsChanged,
481    /// System text anti-aliasing configuration has changed.
482    FontAaChanged(FontAntiAliasing),
483    /// System double-click definition changed.
484    MultiClickConfigChanged(MultiClickConfig),
485    /// System animations config changed.
486    AnimationsConfigChanged(AnimationsConfig),
487    /// System definition of pressed key repeat event changed.
488    KeyRepeatConfigChanged(KeyRepeatConfig),
489    /// System touch config changed.
490    TouchConfigChanged(TouchConfig),
491    /// System locale changed.
492    LocaleChanged(LocaleConfig),
493    /// System color scheme or colors changed.
494    ColorsConfigChanged(ColorsConfig),
495
496    /// Raw input device event.
497    InputDeviceEvent {
498        /// Device that generated the event.
499        device: InputDeviceId,
500        /// Event.
501        event: InputDeviceEvent,
502    },
503
504    /// User responded to a native message dialog.
505    MsgDialogResponse(DialogId, MsgDialogResponse),
506    /// User responded to a native file dialog.
507    FileDialogResponse(DialogId, FileDialogResponse),
508    /// User dismissed a notification dialog.
509    NotificationResponse(DialogId, NotificationResponse),
510
511    /// A system menu command was requested.
512    ///
513    /// The menu item can be from the application menu or tray icon.
514    MenuCommand {
515        /// Menu command ID.
516        id: Txt,
517    },
518
519    /// Accessibility info tree is now required for the window.
520    AccessInit {
521        /// Window that must now build access info.
522        window: WindowId,
523    },
524    /// Accessibility command.
525    AccessCommand {
526        /// Window that had pixels copied.
527        window: WindowId,
528        /// Target widget.
529        target: AccessNodeId,
530        /// Command.
531        command: AccessCmd,
532    },
533    /// Accessibility info tree is no longer needed for the window.
534    ///
535    /// Note that accessibility may be enabled again after this. It is not an error
536    /// to send access updates after this, but they will be ignored.
537    AccessDeinit {
538        /// Window that can release access info.
539        window: WindowId,
540    },
541
542    /// System low memory warning, some platforms may kill the app if it does not release memory.
543    LowMemory,
544
545    /// An internal component panicked, but the view-process managed to recover from it without
546    /// needing to respawn.
547    RecoveredFromComponentPanic {
548        /// Component identifier.
549        component: Txt,
550        /// How the view-process recovered from the panic.
551        recover: Txt,
552        /// The panic.
553        panic: Txt,
554    },
555
556    /// Represents a custom event send by the extension.
557    ExtensionEvent(ApiExtensionId, ApiExtensionPayload),
558
559    /// Signal the view-process is alive.
560    ///
561    /// The associated value must be the count requested by [`Api::ping`](crate::Api::ping).
562    Pong(u16),
563}
564impl Event {
565    /// Change `self` to incorporate `other` or returns `other` if both events cannot be coalesced.
566    #[expect(clippy::result_large_err)]
567    pub fn coalesce(&mut self, other: Event) -> Result<(), Event> {
568        use Event::*;
569
570        match (self, other) {
571            (
572                MouseMoved {
573                    window,
574                    device,
575                    coalesced_pos,
576                    position,
577                },
578                MouseMoved {
579                    window: n_window,
580                    device: n_device,
581                    coalesced_pos: n_coal_pos,
582                    position: n_pos,
583                },
584            ) if *window == n_window && *device == n_device => {
585                coalesced_pos.push(*position);
586                coalesced_pos.extend(n_coal_pos);
587                *position = n_pos;
588            }
589            (
590                DragMoved {
591                    window,
592                    coalesced_pos,
593                    position,
594                },
595                DragMoved {
596                    window: n_window,
597                    coalesced_pos: n_coal_pos,
598                    position: n_pos,
599                },
600            ) if *window == n_window => {
601                coalesced_pos.push(*position);
602                coalesced_pos.extend(n_coal_pos);
603                *position = n_pos;
604            }
605
606            (
607                InputDeviceEvent { device, event },
608                InputDeviceEvent {
609                    device: n_device,
610                    event: n_event,
611                },
612            ) if *device == n_device => {
613                if let Err(e) = event.coalesce(n_event) {
614                    return Err(InputDeviceEvent {
615                        device: n_device,
616                        event: e,
617                    });
618                }
619            }
620
621            // wheel scroll.
622            (
623                MouseWheel {
624                    window,
625                    device,
626                    delta: MouseScrollDelta::LineDelta(delta_x, delta_y),
627                    phase,
628                },
629                MouseWheel {
630                    window: n_window,
631                    device: n_device,
632                    delta: MouseScrollDelta::LineDelta(n_delta_x, n_delta_y),
633                    phase: n_phase,
634                },
635            ) if *window == n_window && *device == n_device && *phase == n_phase => {
636                *delta_x += n_delta_x;
637                *delta_y += n_delta_y;
638            }
639
640            // trackpad scroll-move.
641            (
642                MouseWheel {
643                    window,
644                    device,
645                    delta: MouseScrollDelta::PixelDelta(delta_x, delta_y),
646                    phase,
647                },
648                MouseWheel {
649                    window: n_window,
650                    device: n_device,
651                    delta: MouseScrollDelta::PixelDelta(n_delta_x, n_delta_y),
652                    phase: n_phase,
653                },
654            ) if *window == n_window && *device == n_device && *phase == n_phase => {
655                *delta_x += n_delta_x;
656                *delta_y += n_delta_y;
657            }
658
659            // touch
660            (
661                Touch { window, device, touches },
662                Touch {
663                    window: n_window,
664                    device: n_device,
665                    touches: mut n_touches,
666                },
667            ) if *window == n_window && *device == n_device => {
668                touches.append(&mut n_touches);
669            }
670
671            // window changed.
672            (WindowChanged(change), WindowChanged(n_change))
673                if change.window == n_change.window && change.cause == n_change.cause && change.frame_wait_id.is_none() =>
674            {
675                if n_change.state.is_some() {
676                    change.state = n_change.state;
677                }
678
679                if n_change.position.is_some() {
680                    change.position = n_change.position;
681                }
682
683                if n_change.monitor.is_some() {
684                    change.monitor = n_change.monitor;
685                }
686
687                if n_change.size.is_some() {
688                    change.size = n_change.size;
689                }
690
691                if n_change.safe_padding.is_some() {
692                    change.safe_padding = n_change.safe_padding;
693                }
694
695                if n_change.scale_factor.is_some() {
696                    change.scale_factor = n_change.scale_factor;
697                }
698
699                if n_change.refresh_rate.is_some() {
700                    change.refresh_rate = n_change.refresh_rate;
701                }
702
703                change.frame_wait_id = n_change.frame_wait_id;
704            }
705            // window focus changed.
706            (FocusChanged { prev, new }, FocusChanged { prev: n_prev, new: n_new })
707                if prev.is_some() && new.is_none() && n_prev.is_none() && n_new.is_some() =>
708            {
709                *new = n_new;
710            }
711            // IME commit replaces preview.
712            (
713                Ime {
714                    window,
715                    ime: ime @ self::Ime::Preview(_, _),
716                },
717                Ime {
718                    window: n_window,
719                    ime: n_ime @ self::Ime::Commit(_),
720                },
721            ) if *window == n_window => {
722                *ime = n_ime;
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, ChannelError>;
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#[repr(u8)]
894#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, Default)]
895#[non_exhaustive]
896pub enum MixBlendMode {
897    /// The final color is the top color, regardless of what the bottom color is.
898    /// The effect is like two opaque pieces of paper overlapping.
899    #[default]
900    Normal = 0,
901    /// The final color is the result of multiplying the top and bottom colors.
902    /// A black layer leads to a black final layer, and a white layer leads to no change.
903    /// The effect is like two images printed on transparent film overlapping.
904    Multiply = 1,
905    /// The final color is the result of inverting the colors, multiplying them, and inverting that value.
906    /// A black layer leads to no change, and a white layer leads to a white final layer.
907    /// The effect is like two images shining onto a projection screen.
908    Screen = 2,
909    /// The final color is the result of [`Multiply`] if the bottom color is darker, or [`Screen`] if the bottom color is lighter.
910    /// This blend mode is equivalent to [`HardLight`] but with the layers swapped.
911    ///
912    /// [`Multiply`]: MixBlendMode::Multiply
913    /// [`Screen`]: MixBlendMode::Screen
914    /// [`HardLight`]: MixBlendMode::HardLight
915    Overlay = 3,
916    /// The final color is composed of the darkest values of each color channel.
917    Darken = 4,
918    /// The final color is composed of the lightest values of each color channel.
919    Lighten = 5,
920    /// The final color is the result of dividing the bottom color by the inverse of the top color.
921    /// A black foreground leads to no change.
922    /// A foreground with the inverse color of the backdrop leads to a fully lit color.
923    /// This blend mode is similar to [`Screen`], but the foreground only needs to be as light as the inverse
924    /// of the backdrop to create a fully lit color.
925    ///
926    /// [`Screen`]: MixBlendMode::Screen
927    ColorDodge = 6,
928    /// The final color is the result of inverting the bottom color, dividing the value by the top color, and inverting that value.
929    /// A white foreground leads to no change. A foreground with the inverse color of the backdrop leads to a black final image.
930    /// This blend mode is similar to [`Multiply`], but the foreground only needs to be as dark as the inverse of the backdrop
931    /// to make the final image black.
932    ///
933    /// [`Multiply`]: MixBlendMode::Multiply
934    ColorBurn = 7,
935    /// The final color is the result of [`Multiply`] if the top color is darker, or [`Screen`] if the top color is lighter.
936    /// This blend mode is equivalent to [`Overlay`] but with the layers swapped.
937    /// The effect is similar to shining a harsh spotlight on the backdrop.
938    ///
939    /// The shorthand unit `HardLight!` converts into this.
940    ///
941    /// [`Multiply`]: MixBlendMode::Multiply
942    /// [`Screen`]: MixBlendMode::Screen
943    /// [`Overlay`]: MixBlendMode::Overlay
944    HardLight = 8,
945    /// The final color is similar to [`HardLight`], but softer. This blend mode behaves similar to [`HardLight`].
946    /// The effect is similar to shining a diffused spotlight on the backdrop.
947    ///
948    /// [`HardLight`]: MixBlendMode::HardLight
949    SoftLight = 9,
950    /// The final color is the result of subtracting the darker of the two colors from the lighter one.
951    /// A black layer has no effect, while a white layer inverts the other layer's color.
952    Difference = 10,
953    /// The final color is similar to [`Difference`], but with less contrast.
954    /// As with [`Difference`], a black layer has no effect, while a white layer inverts the other layer's color.
955    ///
956    /// [`Difference`]: MixBlendMode::Difference
957    Exclusion = 11,
958    /// The final color has the *hue* of the top color, while using the *saturation* and *luminosity* of the bottom color.
959    Hue = 12,
960    /// The final color has the *saturation* of the top color, while using the *hue* and *luminosity* of the bottom color.
961    /// A pure gray backdrop, having no saturation, will have no effect.
962    Saturation = 13,
963    /// The final color has the *hue* and *saturation* of the top color, while using the *luminosity* of the bottom color.
964    /// The effect preserves gray levels and can be used to colorize the foreground.
965    Color = 14,
966    /// The final color has the *luminosity* of the top color, while using the *hue* and *saturation* of the bottom color.
967    /// This blend mode is equivalent to [`Color`], but with the layers swapped.
968    ///
969    /// [`Color`]: MixBlendMode::Color
970    Luminosity = 15,
971    /// The final color adds the top color multiplied by alpha to the bottom color multiplied by alpha.
972    /// This blend mode is particularly useful in cross fades where the opacity of both layers transition in reverse.
973    PlusLighter = 16,
974}
975
976/// Image scaling algorithm in the renderer.
977///
978/// If an image is not rendered at the same size as their source it must be up-scaled or
979/// down-scaled. The algorithms used for this scaling can be selected using this `enum`.
980///
981/// Note that the algorithms used in the renderer value performance over quality and do a good
982/// enough job for small or temporary changes in scale only, such as a small size correction or a scaling animation.
983/// If and image is constantly rendered at a different scale you should considered scaling it on the CPU using a
984/// slower but more complex algorithm or pre-scaling it before including in the app.
985#[repr(u8)]
986#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize)]
987#[non_exhaustive]
988pub enum ImageRendering {
989    /// Let the renderer select the algorithm, currently this is the same as [`CrispEdges`].
990    ///
991    /// [`CrispEdges`]: ImageRendering::CrispEdges
992    Auto = 0,
993    /// The image is scaled with an algorithm that preserves contrast and edges in the image,
994    /// and which does not smooth colors or introduce blur to the image in the process.
995    ///
996    /// Currently the [Bilinear] interpolation algorithm is used.
997    ///
998    /// [Bilinear]: https://en.wikipedia.org/wiki/Bilinear_interpolation
999    CrispEdges = 1,
1000    /// When scaling the image up, the image appears to be composed of large pixels.
1001    ///
1002    /// Currently the [Nearest-neighbor] interpolation algorithm is used.
1003    ///
1004    /// [Nearest-neighbor]: https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation
1005    Pixelated = 2,
1006}
1007
1008/// Gradient extend mode.
1009#[allow(missing_docs)]
1010#[repr(u8)]
1011#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize, Ord, PartialOrd)]
1012pub enum ExtendMode {
1013    Clamp,
1014    Repeat,
1015}
1016
1017/// Orientation of a straight line.
1018#[derive(Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1019pub enum LineOrientation {
1020    /// Top-to-bottom line.
1021    Vertical,
1022    /// Left-to-right line.
1023    Horizontal,
1024}
1025impl fmt::Debug for LineOrientation {
1026    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1027        if f.alternate() {
1028            write!(f, "LineOrientation::")?;
1029        }
1030        match self {
1031            LineOrientation::Vertical => {
1032                write!(f, "Vertical")
1033            }
1034            LineOrientation::Horizontal => {
1035                write!(f, "Horizontal")
1036            }
1037        }
1038    }
1039}
1040
1041/// Represents a line style.
1042#[allow(missing_docs)]
1043#[repr(u8)]
1044#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
1045#[non_exhaustive]
1046pub enum LineStyle {
1047    Solid,
1048    Dotted,
1049    Dashed,
1050
1051    /// A wavy line, like an error underline.
1052    ///
1053    /// The wave magnitude is defined by the overall line thickness, the associated value
1054    /// here defines the thickness of the wavy line.
1055    Wavy(f32),
1056}
1057
1058/// The line style for the sides of a widget's border.
1059#[repr(u8)]
1060#[derive(Default, Debug, Clone, Copy, PartialEq, Hash, Eq, serde::Serialize, serde::Deserialize)]
1061#[non_exhaustive]
1062pub enum BorderStyle {
1063    /// No border line.
1064    #[default]
1065    None = 0,
1066
1067    /// A single straight solid line.
1068    Solid = 1,
1069    /// Two straight solid lines that add up to the pixel size defined by the side width.
1070    Double = 2,
1071
1072    /// Displays a series of rounded dots.
1073    Dotted = 3,
1074    /// Displays a series of short square-ended dashes or line segments.
1075    Dashed = 4,
1076
1077    /// Fully transparent line.
1078    Hidden = 5,
1079
1080    /// Displays a border with a carved appearance.
1081    Groove = 6,
1082    /// Displays a border with an extruded appearance.
1083    Ridge = 7,
1084
1085    /// Displays a border that makes the widget appear embedded.
1086    Inset = 8,
1087    /// Displays a border that makes the widget appear embossed.
1088    Outset = 9,
1089}
1090
1091/// Result of a focus request.
1092#[repr(u8)]
1093#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
1094#[non_exhaustive]
1095pub enum FocusResult {
1096    /// Focus was requested, an [`Event::FocusChanged`] will be send if the operating system gives focus to the window.
1097    Requested,
1098    /// Window is already focused.
1099    AlreadyFocused,
1100}
1101
1102/// Defines what raw device events the view-process instance should monitor and notify.
1103///
1104/// Raw device events are global and can be received even when the app has no visible window.
1105///
1106/// These events are disabled by default as they can impact performance or may require special security clearance,
1107/// depending on the view-process implementation and operating system.
1108#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
1109#[non_exhaustive]
1110pub struct DeviceEventsFilter {
1111    /// What raw input events should be watched/send.
1112    ///
1113    /// Note that although the view-process will filter input device events using these flags setting
1114    /// just one of them may cause a general native listener to init.
1115    pub input: InputDeviceCapability,
1116}
1117impl DeviceEventsFilter {
1118    /// Default value, no device events are needed.
1119    pub fn empty() -> Self {
1120        Self {
1121            input: InputDeviceCapability::empty(),
1122        }
1123    }
1124
1125    /// If the filter does not include any event.
1126    pub fn is_empty(&self) -> bool {
1127        self.input.is_empty()
1128    }
1129
1130    /// New with input device events needed.
1131    pub fn new(input: InputDeviceCapability) -> Self {
1132        Self { input }
1133    }
1134}
1135impl Default for DeviceEventsFilter {
1136    fn default() -> Self {
1137        Self::empty()
1138    }
1139}
1140
1141#[cfg(test)]
1142mod tests {
1143    use super::*;
1144
1145    #[test]
1146    fn key_code_iter() {
1147        let mut iter = KeyCode::all_identified();
1148        let first = iter.next().unwrap();
1149        assert_eq!(first, KeyCode::Backquote);
1150
1151        for k in iter {
1152            assert_eq!(k.name(), &format!("{k:?}"));
1153        }
1154    }
1155}