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 /// The monitor’s scale factor has changed.
411 ScaleFactorChanged {
412 /// Monitor that has changed.
413 monitor: MonitorId,
414 /// Windows affected by this change.
415 ///
416 /// Note that a window's scale factor can also change if it is moved to another monitor,
417 /// the [`Event::WindowChanged`] event notifies this using the [`WindowChanged::monitor`].
418 windows: Vec<WindowId>,
419 /// The new scale factor.
420 scale_factor: f32,
421 },
422
423 /// The available monitors have changed.
424 MonitorsChanged(Vec<(MonitorId, MonitorInfo)>),
425 /// The available audio input and output devices have changed.
426 AudioDevicesChanged(Vec<(AudioDeviceId, AudioDeviceInfo)>),
427 /// The available raw input devices have changed.
428 InputDevicesChanged(Vec<(InputDeviceId, InputDeviceInfo)>),
429
430 /// The window has been requested to close.
431 WindowCloseRequested(WindowId),
432 /// The window has closed.
433 WindowClosed(WindowId),
434
435 /// An image resource already decoded header metadata.
436 ImageMetadataDecoded(ImageMetadata),
437 /// An image resource has partially or fully decoded.
438 ImageDecoded(ImageDecoded),
439 /// An image resource failed to decode, the image ID is not valid.
440 ImageDecodeError {
441 /// The image that failed to decode.
442 image: ImageId,
443 /// The error message.
444 error: Txt,
445 },
446 /// An image finished encoding.
447 ImageEncoded {
448 /// Id of the encode task.
449 task: ImageEncodeId,
450 /// The encoded image data.
451 data: IpcBytes,
452 },
453 /// An image failed to encode.
454 ImageEncodeError {
455 /// Id of the encode task.
456 task: ImageEncodeId,
457 /// The error message.
458 error: Txt,
459 },
460
461 /// An audio resource decoded header metadata.
462 AudioMetadataDecoded(AudioMetadata),
463 /// An audio resource decoded chunk or finished decoding.
464 AudioDecoded(AudioDecoded),
465 /// An audio resource failed to decode, the audio ID is not valid.
466 AudioDecodeError {
467 /// The audio that failed to decode.
468 audio: AudioId,
469 /// The error message.
470 error: Txt,
471 },
472
473 /// Audio output is connected with device and ready to receive commands.
474 AudioOutputOpened(AudioOutputId, AudioOutputOpenData),
475 /// Audio playback stream failed to connect.
476 AudioOutputOpenError {
477 /// The output ID.
478 id: AudioOutputId,
479 /// The error message.
480 error: Txt,
481 },
482 /// Audio playback failed.
483 AudioPlayError {
484 /// The request ID.
485 play: AudioPlayId,
486 /// The error message.
487 error: Txt,
488 },
489
490 /* Config events */
491 /// System fonts have changed.
492 FontsChanged,
493 /// System text anti-aliasing configuration has changed.
494 FontAaChanged(FontAntiAliasing),
495 /// System double-click definition changed.
496 MultiClickConfigChanged(MultiClickConfig),
497 /// System animations config changed.
498 AnimationsConfigChanged(AnimationsConfig),
499 /// System definition of pressed key repeat event changed.
500 KeyRepeatConfigChanged(KeyRepeatConfig),
501 /// System touch config changed.
502 TouchConfigChanged(TouchConfig),
503 /// System locale changed.
504 LocaleChanged(LocaleConfig),
505 /// System color scheme or colors changed.
506 ColorsConfigChanged(ColorsConfig),
507
508 /// Raw input device event.
509 InputDeviceEvent {
510 /// Device that generated the event.
511 device: InputDeviceId,
512 /// Event.
513 event: InputDeviceEvent,
514 },
515
516 /// User responded to a native message dialog.
517 MsgDialogResponse(DialogId, MsgDialogResponse),
518 /// User responded to a native file dialog.
519 FileDialogResponse(DialogId, FileDialogResponse),
520 /// User dismissed a notification dialog.
521 NotificationResponse(DialogId, NotificationResponse),
522
523 /// A system menu command was requested.
524 ///
525 /// The menu item can be from the application menu or tray icon.
526 MenuCommand {
527 /// Menu command ID.
528 id: Txt,
529 },
530
531 /// Accessibility info tree is now required for the window.
532 AccessInit {
533 /// Window that must now build access info.
534 window: WindowId,
535 },
536 /// Accessibility command.
537 AccessCommand {
538 /// Window that had pixels copied.
539 window: WindowId,
540 /// Target widget.
541 target: AccessNodeId,
542 /// Command.
543 command: AccessCmd,
544 },
545 /// Accessibility info tree is no longer needed for the window.
546 ///
547 /// Note that accessibility may be enabled again after this. It is not an error
548 /// to send access updates after this, but they will be ignored.
549 AccessDeinit {
550 /// Window that can release access info.
551 window: WindowId,
552 },
553
554 /// System low memory warning, some platforms may kill the app if it does not release memory.
555 LowMemory,
556
557 /// An internal component panicked, but the view-process managed to recover from it without
558 /// needing to respawn.
559 RecoveredFromComponentPanic {
560 /// Component identifier.
561 component: Txt,
562 /// How the view-process recovered from the panic.
563 recover: Txt,
564 /// The panic.
565 panic: Txt,
566 },
567
568 /// Represents a custom event send by the extension.
569 ExtensionEvent(ApiExtensionId, ApiExtensionPayload),
570
571 /// Signal the view-process is alive.
572 ///
573 /// The associated value must be the count requested by [`Api::ping`](crate::Api::ping).
574 Pong(u16),
575}
576impl Event {
577 /// Change `self` to incorporate `other` or returns `other` if both events cannot be coalesced.
578 #[expect(clippy::result_large_err)]
579 pub fn coalesce(&mut self, other: Event) -> Result<(), Event> {
580 use Event::*;
581
582 match (self, other) {
583 (
584 MouseMoved {
585 window,
586 device,
587 coalesced_pos,
588 position,
589 },
590 MouseMoved {
591 window: n_window,
592 device: n_device,
593 coalesced_pos: n_coal_pos,
594 position: n_pos,
595 },
596 ) if *window == n_window && *device == n_device => {
597 coalesced_pos.push(*position);
598 coalesced_pos.extend(n_coal_pos);
599 *position = n_pos;
600 }
601 (
602 DragMoved {
603 window,
604 coalesced_pos,
605 position,
606 },
607 DragMoved {
608 window: n_window,
609 coalesced_pos: n_coal_pos,
610 position: n_pos,
611 },
612 ) if *window == n_window => {
613 coalesced_pos.push(*position);
614 coalesced_pos.extend(n_coal_pos);
615 *position = n_pos;
616 }
617
618 (
619 InputDeviceEvent { device, event },
620 InputDeviceEvent {
621 device: n_device,
622 event: n_event,
623 },
624 ) if *device == n_device => {
625 if let Err(e) = event.coalesce(n_event) {
626 return Err(InputDeviceEvent {
627 device: n_device,
628 event: e,
629 });
630 }
631 }
632
633 // wheel scroll.
634 (
635 MouseWheel {
636 window,
637 device,
638 delta: MouseScrollDelta::LineDelta(delta_x, delta_y),
639 phase,
640 },
641 MouseWheel {
642 window: n_window,
643 device: n_device,
644 delta: MouseScrollDelta::LineDelta(n_delta_x, n_delta_y),
645 phase: n_phase,
646 },
647 ) if *window == n_window && *device == n_device && *phase == n_phase => {
648 *delta_x += n_delta_x;
649 *delta_y += n_delta_y;
650 }
651
652 // trackpad scroll-move.
653 (
654 MouseWheel {
655 window,
656 device,
657 delta: MouseScrollDelta::PixelDelta(delta_x, delta_y),
658 phase,
659 },
660 MouseWheel {
661 window: n_window,
662 device: n_device,
663 delta: MouseScrollDelta::PixelDelta(n_delta_x, n_delta_y),
664 phase: n_phase,
665 },
666 ) if *window == n_window && *device == n_device && *phase == n_phase => {
667 *delta_x += n_delta_x;
668 *delta_y += n_delta_y;
669 }
670
671 // touch
672 (
673 Touch { window, device, touches },
674 Touch {
675 window: n_window,
676 device: n_device,
677 touches: mut n_touches,
678 },
679 ) if *window == n_window && *device == n_device => {
680 touches.append(&mut n_touches);
681 }
682
683 // window changed.
684 (WindowChanged(change), WindowChanged(n_change))
685 if change.window == n_change.window && change.cause == n_change.cause && change.frame_wait_id.is_none() =>
686 {
687 if n_change.state.is_some() {
688 change.state = n_change.state;
689 }
690
691 if n_change.position.is_some() {
692 change.position = n_change.position;
693 }
694
695 if n_change.monitor.is_some() {
696 change.monitor = n_change.monitor;
697 }
698
699 if n_change.size.is_some() {
700 change.size = n_change.size;
701 }
702
703 if n_change.safe_padding.is_some() {
704 change.safe_padding = n_change.safe_padding;
705 }
706
707 change.frame_wait_id = n_change.frame_wait_id;
708 }
709 // window focus changed.
710 (FocusChanged { prev, new }, FocusChanged { prev: n_prev, new: n_new })
711 if prev.is_some() && new.is_none() && n_prev.is_none() && n_new.is_some() =>
712 {
713 *new = n_new;
714 }
715 // IME commit replaces preview.
716 (
717 Ime {
718 window,
719 ime: ime @ self::Ime::Preview(_, _),
720 },
721 Ime {
722 window: n_window,
723 ime: n_ime @ self::Ime::Commit(_),
724 },
725 ) if *window == n_window => {
726 *ime = n_ime;
727 }
728 // scale factor.
729 (
730 ScaleFactorChanged {
731 monitor,
732 windows,
733 scale_factor,
734 },
735 ScaleFactorChanged {
736 monitor: n_monitor,
737 windows: n_windows,
738 scale_factor: n_scale_factor,
739 },
740 ) if *monitor == n_monitor => {
741 for w in n_windows {
742 if !windows.contains(&w) {
743 windows.push(w);
744 }
745 }
746 *scale_factor = n_scale_factor;
747 }
748 // fonts changed.
749 (FontsChanged, FontsChanged) => {}
750 // text aa.
751 (FontAaChanged(config), FontAaChanged(n_config)) => {
752 *config = n_config;
753 }
754 // double-click timeout.
755 (MultiClickConfigChanged(config), MultiClickConfigChanged(n_config)) => {
756 *config = n_config;
757 }
758 // touch config.
759 (TouchConfigChanged(config), TouchConfigChanged(n_config)) => {
760 *config = n_config;
761 }
762 // animation enabled and caret speed.
763 (AnimationsConfigChanged(config), AnimationsConfigChanged(n_config)) => {
764 *config = n_config;
765 }
766 // key repeat delay and speed.
767 (KeyRepeatConfigChanged(config), KeyRepeatConfigChanged(n_config)) => {
768 *config = n_config;
769 }
770 // locale
771 (LocaleChanged(config), LocaleChanged(n_config)) => {
772 *config = n_config;
773 }
774 // drag hovered
775 (
776 DragHovered {
777 window,
778 data,
779 allowed: effects,
780 },
781 DragHovered {
782 window: n_window,
783 data: mut n_data,
784 allowed: n_effects,
785 },
786 ) if *window == n_window && effects.contains(n_effects) => {
787 data.append(&mut n_data);
788 }
789 // drag dropped
790 (
791 DragDropped {
792 window,
793 data,
794 allowed,
795 drop_id,
796 },
797 DragDropped {
798 window: n_window,
799 data: mut n_data,
800 allowed: n_allowed,
801 drop_id: n_drop_id,
802 },
803 ) if *window == n_window && allowed.contains(n_allowed) && *drop_id == n_drop_id => {
804 data.append(&mut n_data);
805 }
806 // drag cancelled
807 (DragCancelled { window }, DragCancelled { window: n_window }) if *window == n_window => {}
808 // input devices changed
809 (InputDevicesChanged(devices), InputDevicesChanged(n_devices)) => {
810 *devices = n_devices;
811 }
812 // audio devices changed
813 (AudioDevicesChanged(devices), AudioDevicesChanged(n_devices)) => {
814 *devices = n_devices;
815 }
816 (_, e) => return Err(e),
817 }
818 Ok(())
819 }
820}
821
822/// View Process IPC result.
823pub(crate) type VpResult<T> = std::result::Result<T, ChannelError>;
824
825/// Offset and color in a gradient.
826#[repr(C)]
827#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Serialize)]
828pub struct GradientStop {
829 /// Offset in pixels.
830 pub offset: f32,
831 /// Color at the offset.
832 pub color: Rgba,
833}
834
835/// Border side line style and color.
836#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Serialize)]
837pub struct BorderSide {
838 /// Line color.
839 pub color: Rgba,
840 /// Line Style.
841 pub style: BorderStyle,
842}
843
844/// Defines if a widget is part of the same 3D space as the parent.
845#[derive(Default, Clone, Copy, serde::Deserialize, Eq, Hash, PartialEq, serde::Serialize)]
846#[repr(u8)]
847pub enum TransformStyle {
848 /// Widget is not a part of the 3D space of the parent. If it has
849 /// 3D children they will be rendered into a flat plane that is placed in the 3D space of the parent.
850 #[default]
851 Flat = 0,
852 /// Widget is a part of the 3D space of the parent. If it has 3D children
853 /// they will be positioned relative to siblings in the same space.
854 ///
855 /// Note that some properties require a flat image to work on, in particular all pixel filter properties including opacity.
856 /// When such a property is set in a widget that is `Preserve3D` and has both a parent and one child also `Preserve3D` the
857 /// filters are ignored and a warning is logged. When the widget is `Preserve3D` and the parent is not the filters are applied
858 /// *outside* the 3D space, when the widget is `Preserve3D` with all `Flat` children the filters are applied *inside* the 3D space.
859 Preserve3D = 1,
860}
861impl fmt::Debug for TransformStyle {
862 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
863 if f.alternate() {
864 write!(f, "TransformStyle::")?;
865 }
866 match self {
867 Self::Flat => write!(f, "Flat"),
868 Self::Preserve3D => write!(f, "Preserve3D"),
869 }
870 }
871}
872
873/// Identifies a reference frame.
874///
875/// This ID is mostly defined by the app process. IDs that set the most significant
876/// bit of the second part (`id.1 & (1 << 63) != 0`) are reserved for the view process.
877#[derive(Default, Debug, Clone, Copy, serde::Deserialize, Eq, Hash, PartialEq, serde::Serialize)]
878pub struct ReferenceFrameId(pub u64, pub u64);
879impl ReferenceFrameId {
880 /// If ID does not set the bit that indicates it is generated by the view process.
881 pub fn is_app_generated(&self) -> bool {
882 self.1 & (1 << 63) == 0
883 }
884}
885
886/// Nine-patch border repeat mode.
887///
888/// Defines how the edges and middle region of a nine-patch border is filled.
889#[repr(u8)]
890#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, Default)]
891pub enum RepeatMode {
892 /// The source image's edge regions are stretched to fill the gap between each border.
893 #[default]
894 Stretch,
895 /// The source image's edge regions are tiled (repeated) to fill the gap between each
896 /// border. Tiles may be clipped to achieve the proper fit.
897 Repeat,
898 /// The source image's edge regions are tiled (repeated) to fill the gap between each
899 /// border. Tiles may be stretched to achieve the proper fit.
900 Round,
901 /// The source image's edge regions are tiled (repeated) to fill the gap between each
902 /// border. Extra space will be distributed in between tiles to achieve the proper fit.
903 Space,
904}
905#[cfg(feature = "var")]
906zng_var::impl_from_and_into_var! {
907 /// Converts `true` to `Repeat` and `false` to the default `Stretch`.
908 fn from(value: bool) -> RepeatMode {
909 match value {
910 true => RepeatMode::Repeat,
911 false => RepeatMode::Stretch,
912 }
913 }
914}
915
916/// Color mix blend mode.
917#[repr(u8)]
918#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, Default)]
919#[non_exhaustive]
920pub enum MixBlendMode {
921 /// The final color is the top color, regardless of what the bottom color is.
922 /// The effect is like two opaque pieces of paper overlapping.
923 #[default]
924 Normal = 0,
925 /// The final color is the result of multiplying the top and bottom colors.
926 /// A black layer leads to a black final layer, and a white layer leads to no change.
927 /// The effect is like two images printed on transparent film overlapping.
928 Multiply = 1,
929 /// The final color is the result of inverting the colors, multiplying them, and inverting that value.
930 /// A black layer leads to no change, and a white layer leads to a white final layer.
931 /// The effect is like two images shining onto a projection screen.
932 Screen = 2,
933 /// The final color is the result of [`Multiply`] if the bottom color is darker, or [`Screen`] if the bottom color is lighter.
934 /// This blend mode is equivalent to [`HardLight`] but with the layers swapped.
935 ///
936 /// [`Multiply`]: MixBlendMode::Multiply
937 /// [`Screen`]: MixBlendMode::Screen
938 /// [`HardLight`]: MixBlendMode::HardLight
939 Overlay = 3,
940 /// The final color is composed of the darkest values of each color channel.
941 Darken = 4,
942 /// The final color is composed of the lightest values of each color channel.
943 Lighten = 5,
944 /// The final color is the result of dividing the bottom color by the inverse of the top color.
945 /// A black foreground leads to no change.
946 /// A foreground with the inverse color of the backdrop leads to a fully lit color.
947 /// This blend mode is similar to [`Screen`], but the foreground only needs to be as light as the inverse
948 /// of the backdrop to create a fully lit color.
949 ///
950 /// [`Screen`]: MixBlendMode::Screen
951 ColorDodge = 6,
952 /// The final color is the result of inverting the bottom color, dividing the value by the top color, and inverting that value.
953 /// A white foreground leads to no change. A foreground with the inverse color of the backdrop leads to a black final image.
954 /// This blend mode is similar to [`Multiply`], but the foreground only needs to be as dark as the inverse of the backdrop
955 /// to make the final image black.
956 ///
957 /// [`Multiply`]: MixBlendMode::Multiply
958 ColorBurn = 7,
959 /// The final color is the result of [`Multiply`] if the top color is darker, or [`Screen`] if the top color is lighter.
960 /// This blend mode is equivalent to [`Overlay`] but with the layers swapped.
961 /// The effect is similar to shining a harsh spotlight on the backdrop.
962 ///
963 /// The shorthand unit `HardLight!` converts into this.
964 ///
965 /// [`Multiply`]: MixBlendMode::Multiply
966 /// [`Screen`]: MixBlendMode::Screen
967 /// [`Overlay`]: MixBlendMode::Overlay
968 HardLight = 8,
969 /// The final color is similar to [`HardLight`], but softer. This blend mode behaves similar to [`HardLight`].
970 /// The effect is similar to shining a diffused spotlight on the backdrop.
971 ///
972 /// [`HardLight`]: MixBlendMode::HardLight
973 SoftLight = 9,
974 /// The final color is the result of subtracting the darker of the two colors from the lighter one.
975 /// A black layer has no effect, while a white layer inverts the other layer's color.
976 Difference = 10,
977 /// The final color is similar to [`Difference`], but with less contrast.
978 /// As with [`Difference`], a black layer has no effect, while a white layer inverts the other layer's color.
979 ///
980 /// [`Difference`]: MixBlendMode::Difference
981 Exclusion = 11,
982 /// The final color has the *hue* of the top color, while using the *saturation* and *luminosity* of the bottom color.
983 Hue = 12,
984 /// The final color has the *saturation* of the top color, while using the *hue* and *luminosity* of the bottom color.
985 /// A pure gray backdrop, having no saturation, will have no effect.
986 Saturation = 13,
987 /// The final color has the *hue* and *saturation* of the top color, while using the *luminosity* of the bottom color.
988 /// The effect preserves gray levels and can be used to colorize the foreground.
989 Color = 14,
990 /// The final color has the *luminosity* of the top color, while using the *hue* and *saturation* of the bottom color.
991 /// This blend mode is equivalent to [`Color`], but with the layers swapped.
992 ///
993 /// [`Color`]: MixBlendMode::Color
994 Luminosity = 15,
995 /// The final color adds the top color multiplied by alpha to the bottom color multiplied by alpha.
996 /// This blend mode is particularly useful in cross fades where the opacity of both layers transition in reverse.
997 PlusLighter = 16,
998}
999
1000/// Image scaling algorithm in the renderer.
1001///
1002/// If an image is not rendered at the same size as their source it must be up-scaled or
1003/// down-scaled. The algorithms used for this scaling can be selected using this `enum`.
1004///
1005/// Note that the algorithms used in the renderer value performance over quality and do a good
1006/// enough job for small or temporary changes in scale only, such as a small size correction or a scaling animation.
1007/// If and image is constantly rendered at a different scale you should considered scaling it on the CPU using a
1008/// slower but more complex algorithm or pre-scaling it before including in the app.
1009#[repr(u8)]
1010#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize)]
1011#[non_exhaustive]
1012pub enum ImageRendering {
1013 /// Let the renderer select the algorithm, currently this is the same as [`CrispEdges`].
1014 ///
1015 /// [`CrispEdges`]: ImageRendering::CrispEdges
1016 Auto = 0,
1017 /// The image is scaled with an algorithm that preserves contrast and edges in the image,
1018 /// and which does not smooth colors or introduce blur to the image in the process.
1019 ///
1020 /// Currently the [Bilinear] interpolation algorithm is used.
1021 ///
1022 /// [Bilinear]: https://en.wikipedia.org/wiki/Bilinear_interpolation
1023 CrispEdges = 1,
1024 /// When scaling the image up, the image appears to be composed of large pixels.
1025 ///
1026 /// Currently the [Nearest-neighbor] interpolation algorithm is used.
1027 ///
1028 /// [Nearest-neighbor]: https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation
1029 Pixelated = 2,
1030}
1031
1032/// Gradient extend mode.
1033#[allow(missing_docs)]
1034#[repr(u8)]
1035#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize, Ord, PartialOrd)]
1036pub enum ExtendMode {
1037 Clamp,
1038 Repeat,
1039}
1040
1041/// Orientation of a straight line.
1042#[derive(Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1043pub enum LineOrientation {
1044 /// Top-to-bottom line.
1045 Vertical,
1046 /// Left-to-right line.
1047 Horizontal,
1048}
1049impl fmt::Debug for LineOrientation {
1050 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1051 if f.alternate() {
1052 write!(f, "LineOrientation::")?;
1053 }
1054 match self {
1055 LineOrientation::Vertical => {
1056 write!(f, "Vertical")
1057 }
1058 LineOrientation::Horizontal => {
1059 write!(f, "Horizontal")
1060 }
1061 }
1062 }
1063}
1064
1065/// Represents a line style.
1066#[allow(missing_docs)]
1067#[repr(u8)]
1068#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
1069#[non_exhaustive]
1070pub enum LineStyle {
1071 Solid,
1072 Dotted,
1073 Dashed,
1074
1075 /// A wavy line, like an error underline.
1076 ///
1077 /// The wave magnitude is defined by the overall line thickness, the associated value
1078 /// here defines the thickness of the wavy line.
1079 Wavy(f32),
1080}
1081
1082/// The line style for the sides of a widget's border.
1083#[repr(u8)]
1084#[derive(Default, Debug, Clone, Copy, PartialEq, Hash, Eq, serde::Serialize, serde::Deserialize)]
1085#[non_exhaustive]
1086pub enum BorderStyle {
1087 /// No border line.
1088 #[default]
1089 None = 0,
1090
1091 /// A single straight solid line.
1092 Solid = 1,
1093 /// Two straight solid lines that add up to the pixel size defined by the side width.
1094 Double = 2,
1095
1096 /// Displays a series of rounded dots.
1097 Dotted = 3,
1098 /// Displays a series of short square-ended dashes or line segments.
1099 Dashed = 4,
1100
1101 /// Fully transparent line.
1102 Hidden = 5,
1103
1104 /// Displays a border with a carved appearance.
1105 Groove = 6,
1106 /// Displays a border with an extruded appearance.
1107 Ridge = 7,
1108
1109 /// Displays a border that makes the widget appear embedded.
1110 Inset = 8,
1111 /// Displays a border that makes the widget appear embossed.
1112 Outset = 9,
1113}
1114
1115/// Result of a focus request.
1116#[repr(u8)]
1117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
1118#[non_exhaustive]
1119pub enum FocusResult {
1120 /// Focus was requested, an [`Event::FocusChanged`] will be send if the operating system gives focus to the window.
1121 Requested,
1122 /// Window is already focused.
1123 AlreadyFocused,
1124}
1125
1126/// Defines what raw device events the view-process instance should monitor and notify.
1127///
1128/// Raw device events are global and can be received even when the app has no visible window.
1129///
1130/// These events are disabled by default as they can impact performance or may require special security clearance,
1131/// depending on the view-process implementation and operating system.
1132#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
1133#[non_exhaustive]
1134pub struct DeviceEventsFilter {
1135 /// What raw input events should be watched/send.
1136 ///
1137 /// Note that although the view-process will filter input device events using these flags setting
1138 /// just one of them may cause a general native listener to init.
1139 pub input: InputDeviceCapability,
1140}
1141impl DeviceEventsFilter {
1142 /// Default value, no device events are needed.
1143 pub fn empty() -> Self {
1144 Self {
1145 input: InputDeviceCapability::empty(),
1146 }
1147 }
1148
1149 /// If the filter does not include any event.
1150 pub fn is_empty(&self) -> bool {
1151 self.input.is_empty()
1152 }
1153
1154 /// New with input device events needed.
1155 pub fn new(input: InputDeviceCapability) -> Self {
1156 Self { input }
1157 }
1158}
1159impl Default for DeviceEventsFilter {
1160 fn default() -> Self {
1161 Self::empty()
1162 }
1163}
1164
1165#[cfg(test)]
1166mod tests {
1167 use super::*;
1168
1169 #[test]
1170 fn key_code_iter() {
1171 let mut iter = KeyCode::all_identified();
1172 let first = iter.next().unwrap();
1173 assert_eq!(first, KeyCode::Backquote);
1174
1175 for k in iter {
1176 assert_eq!(k.name(), &format!("{k:?}"));
1177 }
1178 }
1179}