zng_view_api/
lib.rs

1#![doc(html_favicon_url = "https://zng-ui.github.io/res/zng-logo-icon.png")]
2#![doc(html_logo_url = "https://zng-ui.github.io/res/zng-logo.png")]
3//!
4//! The View Process API.
5//!
6//! Zng isolates all render and windowing related code to a different process (the view-process), this crate
7//! provides the API that must be implemented to create a view-process backend, plus the [`Controller`] that
8//! can be used from an app-process to spawn and communicate with a view-process.
9//!
10//! # VERSION
11//!
12//! The [`VERSION`] of this crate must match exactly in both *App-Process* and *View-Process*, otherwise a runtime
13//! panic error is generated.
14//!
15//! # Same Process Patch
16//!
17//! Dynamically loaded same process implementers must propagate a [`StaticPatch`], otherwise the view will not connect.
18//!
19//! # Crate
20//!
21#![doc = include_str!(concat!("../", std::env!("CARGO_PKG_README")))]
22#![warn(missing_docs)]
23#![warn(unused_extern_crates)]
24
25use drag_drop::{DragDropData, DragDropEffect, DragDropError};
26use serde::{Deserialize, Serialize};
27
28/// The *App Process* and *View Process* must be build using the same exact version and this is
29/// validated during run-time, causing a panic if the versions don't match.
30pub const VERSION: &str = env!("CARGO_PKG_VERSION");
31
32pub mod access;
33pub mod api_extension;
34pub mod audio;
35pub mod clipboard;
36pub mod config;
37pub mod dialog;
38pub mod display_list;
39pub mod drag_drop;
40pub mod font;
41pub mod image;
42pub mod ipc;
43pub mod keyboard;
44pub mod menu;
45pub mod mouse;
46pub mod raw_input;
47pub mod touch;
48pub mod window;
49
50mod types;
51pub use types::*;
52
53mod app_process;
54pub use app_process::*;
55
56mod view_process;
57pub use view_process::*;
58use zng_txt::Txt;
59
60use std::fmt;
61
62use api_extension::{ApiExtensionId, ApiExtensionPayload};
63use clipboard::{ClipboardData, ClipboardError};
64use dialog::DialogId;
65use font::{FontFaceId, FontId, FontOptions, FontVariationName};
66use image::{ImageId, ImageMaskMode, ImageRequest, ImageTextureId};
67use window::WindowId;
68use zng_task::channel::{IpcBytes, IpcReceiver};
69use zng_unit::{DipPoint, DipRect, DipSize, Factor, Px, PxRect};
70
71/// Packaged API request.
72#[derive(Debug, Serialize, Deserialize)]
73pub struct Request(RequestData);
74impl Request {
75    /// Returns `true` if the request can only be made after the *init* event.
76    pub fn must_be_connected(&self) -> bool {
77        !matches!(&self.0, RequestData::init { .. })
78    }
79
80    /// Returns `true` if the request represents a new frame or frame update for the window with the same wait ID.
81    pub fn is_frame(&self, window_id: WindowId, wait_id: Option<window::FrameWaitId>) -> bool {
82        match &self.0 {
83            RequestData::render { id, frame } if *id == window_id && frame.wait_id == wait_id => true,
84            RequestData::render_update { id, frame } if *id == window_id && frame.wait_id == wait_id => true,
85            _ => false,
86        }
87    }
88
89    /// Returns `true` if the request affects position or size of the window.
90    pub fn affects_window_rect(&self, window_id: WindowId) -> bool {
91        matches!(
92            &self.0,
93            RequestData::set_state { id, .. }
94            if *id == window_id
95        )
96    }
97
98    /// Returns `true` if this request will receive a response. Only [`Api`] methods
99    /// that have a return value send back a response.
100    pub fn expect_response(&self) -> bool {
101        self.0.expect_response()
102    }
103}
104
105/// Packaged API response.
106#[derive(Debug, Serialize, Deserialize)]
107pub struct Response(ResponseData);
108impl Response {
109    /// If this response must be send back to the app process. Only [`Api`] methods
110    /// that have a return value send back a response.
111    pub fn must_be_send(&self) -> bool {
112        self.0.must_be_send()
113    }
114}
115
116macro_rules! TypeOrNil {
117    ($T:ty) => {
118        $T
119    };
120    () => {
121        ()
122    };
123}
124
125macro_rules! type_is_some {
126    (if $T:ty { $($t_true:tt)* } else { $($t_false:tt)* }) => {
127        $($t_true)*
128    };
129    (if { $($t_true:tt)* } else { $($t_false:tt)* }) => {
130        $($t_false)*
131    };
132}
133
134/// Declares the internal `Request` and `Response` enums, public methods in `Controller` and the public trait `ViewApp`, in the
135/// controller it packs and sends the request and receives and unpacks the response. In the view it implements
136/// the method.
137macro_rules! declare_api {
138    (
139        $(
140            $(#[$meta:meta])*
141            $vis:vis fn $method:ident(
142                &mut $self:ident
143                $(, $input:ident : $RequestType:ty)* $(,)?
144            ) $(-> $ResponseType:ty)?;
145        )*
146    ) => {
147        #[derive(Serialize, Deserialize)]
148        #[allow(non_camel_case_types)]
149        #[allow(clippy::large_enum_variant)]
150        #[repr(u32)]
151        enum RequestData {
152            $(
153                $(#[$meta])*
154                $method { $($input: $RequestType),* },
155            )*
156        }
157        impl RequestData {
158            #[allow(unused_doc_comments)]
159            pub fn expect_response(&self) -> bool {
160                match self {
161                    $(
162                        $(#[$meta])*
163                        Self::$method { .. } => type_is_some! {
164                            if $($ResponseType)? {
165                                true
166                            } else {
167                                false
168                            }
169                        },
170                    )*
171                }
172            }
173        }
174        impl fmt::Debug for RequestData {
175            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
176                #[allow(unused_doc_comments)]
177                if f.alternate() {
178                    match self {
179                        $(
180                            $(#[$meta])*
181                            RequestData::$method { $($input),* } => write!(f, "{}{:#?}", stringify!($method), ($($input),*)),
182                        )+
183                    }
184                } else {
185                    match self {
186                        $(
187                            $(#[$meta])*
188                            RequestData::$method { .. } => write!(f, "{}(..)", stringify!($method)),
189                        )+
190                    }
191                }
192            }
193        }
194
195        #[derive(Debug)]
196        #[derive(Serialize, Deserialize)]
197        #[allow(non_camel_case_types)]
198        #[repr(u32)]
199        enum ResponseData {
200            $(
201                $(#[$meta])*
202                $method(TypeOrNil![$($ResponseType)?]),
203            )*
204        }
205        impl ResponseData {
206            #[allow(unused_doc_comments)]
207            pub fn must_be_send(&self) -> bool {
208                match self {
209                    $(
210                        $(#[$meta])*
211                        Self::$method(_) => type_is_some! {
212                            if $($ResponseType)? {
213                                true
214                            } else {
215                                false
216                            }
217                        },
218                    )*
219                }
220            }
221        }
222
223        #[allow(unused_parens)]
224        impl Controller {
225            $(
226                $(#[$meta])*
227                #[allow(clippy::too_many_arguments)]
228                $vis fn $method(&mut self $(, $input: $RequestType)*) -> VpResult<TypeOrNil![$($ResponseType)?]> {
229                    let req = Request(RequestData::$method { $($input),* });
230                    type_is_some! {
231                        if $($ResponseType)? {
232                            match self.talk(req)?.0 {
233                                ResponseData::$method(r) => Ok(r),
234                                r => panic!("view-process did not respond correctly for `{}`, {r:?}", stringify!($method))
235                            }
236                        } else {
237                            self.command(req)
238                        }
239                    }
240                }
241            )*
242        }
243
244        /// The view-process API.
245        pub trait Api {
246            /// Already implemented, matches a request, calls the corresponding method and packages the response.
247            fn respond(&mut self, request: Request) -> Response {
248                match request.0 {
249                    $(
250                        #[allow(unused_doc_comments)]
251                        $(#[$meta])* // for the cfg
252                        RequestData::$method { $($input),* } => {
253                            let r = self.$method($($input),*);
254                            Response(ResponseData::$method(r))
255                        }
256                    )*
257                }
258            }
259
260            $(
261                $(#[$meta])*
262                #[allow(clippy::too_many_arguments)]
263                fn $method(&mut self, $($input: $RequestType),*) $(-> $ResponseType)?;
264            )*
265        }
266    };
267}
268declare_api! {
269    /// Called once on init.
270    ///
271    /// Sends an [`Event::Inited`] once the view is completely connected, the event details what API features
272    /// are implemented by the view-process.
273    ///
274    /// Other methods may only be called after this event.
275    fn init(&mut self, vp_gen: ViewProcessGen, is_respawn: bool, headless: bool);
276
277    /// Called once after exit, if running in a managed external process it will be killed after this call.
278    fn exit(&mut self);
279
280    /// Enable/disable global device events.
281    ///
282    /// This filter affects device events not targeted at windows, such as mouse move outside windows or
283    /// key presses when the app has no focused window.
284    pub fn set_device_events_filter(&mut self, filter: DeviceEventsFilter);
285
286    /// Open a window.
287    ///
288    /// Sends an [`Event::WindowOpened`] once the window, context and renderer have finished initializing or a
289    /// [`Event::WindowOrHeadlessOpenError`] if it failed.
290    pub fn open_window(&mut self, request: window::WindowRequest);
291
292    /// Open a headless surface.
293    ///
294    /// This is a real renderer but not connected to any window, you can requests pixels to get the
295    /// rendered frames.
296    ///
297    /// Sends an [`Event::HeadlessOpened`] once the context and renderer have finished initializing or a
298    /// [`Event::WindowOrHeadlessOpenError`] if it failed.
299    pub fn open_headless(&mut self, request: window::HeadlessRequest);
300
301    /// Close the window or headless surface.
302    ///
303    /// All documents associated with the window or surface are also closed.
304    pub fn close(&mut self, id: WindowId);
305
306    /// Set window title.
307    pub fn set_title(&mut self, id: WindowId, title: Txt);
308
309    /// Set window visible.
310    pub fn set_visible(&mut self, id: WindowId, visible: bool);
311
312    /// Set if the window is "top-most".
313    pub fn set_always_on_top(&mut self, id: WindowId, always_on_top: bool);
314
315    /// Set if the user can drag-move the window when it is in `Normal` mode.
316    pub fn set_movable(&mut self, id: WindowId, movable: bool);
317
318    /// Set if the user can resize the window when it is in `Normal` mode.
319    pub fn set_resizable(&mut self, id: WindowId, resizable: bool);
320
321    /// Set the window taskbar icon visibility.
322    pub fn set_taskbar_visible(&mut self, id: WindowId, visible: bool);
323
324    /// Bring the window to the Z top, without focusing it.
325    pub fn bring_to_top(&mut self, id: WindowId);
326
327    /// Set the window state, position, size.
328    pub fn set_state(&mut self, id: WindowId, state: window::WindowStateAll);
329
330    /// Set the headless surface or document area size (viewport size).
331    pub fn set_headless_size(&mut self, id: WindowId, size: DipSize, scale_factor: Factor);
332
333    /// Set the window icon, the icon image must be loaded.
334    pub fn set_icon(&mut self, id: WindowId, icon: Option<ImageId>);
335
336    /// Set the window cursor icon and visibility.
337    pub fn set_cursor(&mut self, id: WindowId, cursor: Option<window::CursorIcon>);
338
339    /// Set the window cursor to a custom image.
340    ///
341    /// Falls back to cursor icon if not supported or if set to `None`.
342    pub fn set_cursor_image(&mut self, id: WindowId, cursor: Option<window::CursorImage>);
343
344    /// Sets the user attention request indicator, the indicator is cleared when the window is focused or
345    /// if canceled by setting to `None`.
346    pub fn set_focus_indicator(&mut self, id: WindowId, indicator: Option<window::FocusIndicator>);
347
348    /// Set enabled window chrome buttons.
349    pub fn set_enabled_buttons(&mut self, id: WindowId, buttons: window::WindowButton);
350
351    /// Brings the window to the front and sets input focus.
352    ///
353    /// Sends an [`Event::FocusChanged`] if the window is focused, the request can be ignored by the window manager, or if the
354    /// window is not visible, minimized or already focused.
355    ///
356    /// This request can steal focus from other apps disrupting the user, be careful with it.
357    pub fn focus(&mut self, id: WindowId) -> FocusResult;
358
359    /// Moves the window with the left mouse button until the button is released.
360    ///
361    /// There's no guarantee that this will work unless the left mouse button was pressed immediately before this function is called.
362    pub fn drag_move(&mut self, id: WindowId);
363
364    /// Resizes the window with the left mouse button until the button is released.
365    ///
366    /// There's no guarantee that this will work unless the left mouse button was pressed immediately before this function is called.
367    pub fn drag_resize(&mut self, id: WindowId, direction: window::ResizeDirection);
368
369    /// Open the system title bar context menu.
370    pub fn open_title_bar_context_menu(&mut self, id: WindowId, position: DipPoint);
371
372    /// Cache an image resource.
373    ///
374    /// The image is decoded asynchronously, the events [`Event::ImageMetadataDecoded`], [`Event::ImageDecoded`]
375    /// or [`Event::ImageDecodeError`] will be send when the image is ready for use or failed.
376    ///
377    /// The [`ImageRequest::data`] handle must contain the full image data already, it will be dropped after the image finishes decoding.
378    ///
379    /// Images are shared between renderers, to use an image in a window you must first call [`use_image`]
380    /// this will register the image data with the renderer.
381    ///
382    /// [`use_image`]: Api::use_image
383    pub fn add_image(&mut self, request: ImageRequest<IpcBytes>) -> ImageId;
384
385    /// Cache an image from data that has not fully loaded.
386    ///
387    /// If the view-process implementation supports **progressive decoding** it will start decoding the image
388    /// as more data is received, otherwise it will collect all data first and then [`add_image`]. Each
389    /// [`ImageRequest::`data`] package is the continuation of the previous call, send an empty package to indicate finish.
390    ///
391    /// The events [`Event::ImageMetadataDecoded`], [`Event::ImageDecoded`] or [`Event::ImageDecodeError`] will
392    /// be send while decoding.
393    ///
394    /// [`add_image`]: Api::add_image
395    pub fn add_image_pro(&mut self, request: ImageRequest<IpcReceiver<IpcBytes>>) -> ImageId;
396
397    /// Remove an image from cache.
398    ///
399    /// Note that if the image is in use in a renderer it will remain in memory until [`delete_image_use`] is
400    /// called or the renderer is deinited by closing the window.
401    ///
402    /// [`delete_image_use`]: Api::delete_image_use
403    pub fn forget_image(&mut self, id: ImageId);
404
405    /// Add an image resource to the window renderer.
406    ///
407    /// Returns the new image texture ID. If the `image_id` is not loaded returns the [`INVALID`] texture ID.
408    ///
409    /// [`INVALID`]: ImageTextureId::INVALID
410    pub fn use_image(&mut self, id: WindowId, image_id: ImageId) -> ImageTextureId;
411
412    /// Replace the image resource in the window renderer.
413    ///
414    /// The new `image_id` must represent an image with same dimensions and format as the previous. If the
415    /// image cannot be updated an error is logged and `false` is returned.
416    ///
417    /// The `dirty_rect` can be set to optimize texture upload to the GPU, if not set the entire image region updates.
418    ///
419    /// The [`ImageTextureId`] will be associated with the new [`ImageId`].
420    pub fn update_image_use(&mut self, id: WindowId, texture_id: ImageTextureId, image_id: ImageId, dirty_rect: Option<PxRect>)
421    -> bool;
422
423    /// Delete the image resource in the window renderer.
424    pub fn delete_image_use(&mut self, id: WindowId, texture_id: ImageTextureId);
425
426    /// Encode the image.
427    ///
428    /// Returns immediately. The encoded data will be send as the event
429    /// [`Event::ImageEncoded`] or [`Event::ImageEncodeError`]. The returned ID identifies this request.
430    pub fn encode_image(&mut self, request: image::ImageEncodeRequest) -> image::ImageEncodeId;
431
432    /// Cache an audio resource.
433    ///
434    /// The entire audio source is already loaded in the request, it may be fully decode or decoded on demand depending on the request
435    /// the returned ID can be played as soon as it starts decoding.
436    ///
437    /// The events [`Event::AudioMetadataDecoded`], [`Event::AudioDecoded`] and [`Event::AudioDecodeError`] will be send while decoding.
438    pub fn add_audio(&mut self, request: audio::AudioRequest<IpcBytes>) -> audio::AudioId;
439
440    /// Cache an streaming audio resource.
441    ///
442    /// The audio is decoded as bytes are buffered in. The returned ID can be played as soon as it starts decoding.
443    ///
444    /// The events [`Event::AudioMetadataDecoded`], [`Event::AudioDecoded`] and [`Event::AudioDecodeError`] will be send while decoding.
445    pub fn add_audio_pro(&mut self, request: audio::AudioRequest<IpcReceiver<IpcBytes>>) -> audio::AudioId;
446
447    /// Remove an audio from cache.
448    ///
449    /// Note that if the audio playing it will continue until the end or it is stopped.
450    pub fn forget_audio(&mut self, id: audio::AudioId);
451
452    /// Create a playback stream.
453    ///
454    /// Opens a connection with the audio device if there are no other streams connected to it.
455    pub fn open_audio_output(&mut self, request: audio::AudioOutputRequest);
456
457    /// Update configuration of an existing playback stream.
458    pub fn update_audio_output(&mut self, request: audio::AudioOutputUpdateRequest);
459
460    /// Stop and drop a playback stream.
461    ///
462    /// Note that even if this is the last connection to the device the underlying system connection may remain open as some systems expect this
463    /// resource to exist for the lifetime of the process.
464    pub fn close_audio_output(&mut self, id: audio::AudioOutputId);
465
466    /// Play or enqueue audio.
467    pub fn cue_audio(&mut self, request: audio::AudioPlayRequest) -> audio::AudioPlayId;
468
469    /// Encode the audio.
470    pub fn encode_audio(&mut self, request: audio::AudioEncodeRequest) -> audio::AudioEncodeId;
471
472    /// Add a raw font resource to the window renderer.
473    ///
474    /// Returns the new font key.
475    pub fn add_font_face(&mut self, id: WindowId, bytes: font::IpcFontBytes, index: u32) -> FontFaceId;
476
477    /// Delete the font resource in the window renderer.
478    pub fn delete_font_face(&mut self, id: WindowId, font_face_id: FontFaceId);
479
480    /// Add a sized font to the window renderer.
481    ///
482    /// Returns the new fond ID.
483    pub fn add_font(
484        &mut self,
485        id: WindowId,
486        font_face_id: FontFaceId,
487        glyph_size: Px,
488        options: FontOptions,
489        variations: Vec<(FontVariationName, f32)>,
490    ) -> FontId;
491
492    /// Delete a font instance.
493    pub fn delete_font(&mut self, id: WindowId, font_id: FontId);
494
495    /// Sets if the headed window is in *capture-mode*. If `true` the resources used to capture
496    /// a screenshot may be kept in memory to be reused in the next screenshot capture.
497    ///
498    /// Note that capture must still be requested in each frame request.
499    pub fn set_capture_mode(&mut self, id: WindowId, enable: bool);
500
501    /// Create a new image resource from the current rendered frame.
502    ///
503    /// If `mask` is set captures an A8 mask, otherwise captures a full BGRA8 image.
504    ///
505    /// Returns immediately, an [`Event::ImageDecoded`] will be send when the image is ready.
506    ///
507    /// Returns [`ImageId::INVALID`] if the window is not found.
508    pub fn frame_image(&mut self, id: WindowId, mask: Option<ImageMaskMode>) -> ImageId;
509
510    /// Create a new image from a selection of the current rendered frame.
511    ///
512    /// If `mask` is set captures an A8 mask, otherwise captures a full BGRA8 image.
513    ///
514    /// Returns immediately, an [`Event::ImageDecoded`] will be send when the image is ready.
515    ///
516    /// Returns [`ImageId::INVALID`] if the window is not found.
517    pub fn frame_image_rect(&mut self, id: WindowId, rect: PxRect, mask: Option<ImageMaskMode>) -> ImageId;
518
519    /// Set the video mode used when the window is in exclusive fullscreen.
520    pub fn set_video_mode(&mut self, id: WindowId, mode: window::VideoMode);
521
522    /// Render a new frame.
523    pub fn render(&mut self, id: WindowId, frame: window::FrameRequest);
524
525    /// Update the current frame and re-render it.
526    pub fn render_update(&mut self, id: WindowId, frame: window::FrameUpdateRequest);
527
528    /// Update the window's accessibility info tree.
529    pub fn access_update(&mut self, id: WindowId, update: access::AccessTreeUpdate);
530
531    /// Shows a native message dialog for the window.
532    ///
533    /// Returns an ID that identifies the response event.
534    pub fn message_dialog(&mut self, id: WindowId, dialog: dialog::MsgDialog) -> DialogId;
535
536    /// Shows a native file/folder picker for the window.
537    ///
538    /// Returns the ID that identifies the response event.
539    pub fn file_dialog(&mut self, id: WindowId, dialog: dialog::FileDialog) -> DialogId;
540
541    /// Register a native notification, either a popup or an entry in the system notifications list.
542    ///
543    /// Returns an ID that identifies the response event.
544    pub fn notification_dialog(&mut self, notification: dialog::Notification) -> DialogId;
545
546    /// Update the notification content.
547    pub fn update_notification(&mut self, id: DialogId, notification: dialog::Notification);
548
549    /// Get the clipboard content that matches the `data_types`.
550    ///
551    /// If `first` is true tries to read all data types requested and returns the first ok. If is false returns all requested data types ok.
552    pub fn read_clipboard(
553        &mut self,
554        data_types: Vec<clipboard::ClipboardType>,
555        first: bool,
556    ) -> Result<Vec<ClipboardData>, ClipboardError>;
557
558    /// Set the clipboard content.
559    ///
560    /// Returns the count of data types that where set, if at least one `data` is supported by the implementation
561    /// the operation is considered a success. If the implementation only support a single data entry the first
562    /// compatible entry is written.
563    pub fn write_clipboard(&mut self, data: Vec<ClipboardData>) -> Result<usize, ClipboardError>;
564
565    /// Start a drag and drop operation, if the window is pressed.
566    pub fn start_drag_drop(
567        &mut self,
568        id: WindowId,
569        data: Vec<DragDropData>,
570        allowed_effects: DragDropEffect,
571    ) -> Result<DragDropId, DragDropError>;
572
573    /// Cancel a drag and drop operation.
574    pub fn cancel_drag_drop(&mut self, id: WindowId, drag_id: DragDropId);
575
576    /// Notify the drag source of what effect was applied for a received drag&drop.
577    pub fn drag_dropped(&mut self, id: WindowId, drop_id: DragDropId, applied: DragDropEffect);
578
579    /// Enable or disable IME by setting a cursor area.
580    ///
581    /// In mobile platforms also shows the software keyboard for `Some(_)` and hides it for `None`.
582    pub fn set_ime_area(&mut self, id: WindowId, area: Option<DipRect>);
583
584    /// Attempt to set a system wide shutdown warning associated with the window.
585    ///
586    /// Operating systems that support this show the `reason` in a warning for the user, it must be a short text
587    /// that identifies the critical operation that cannot be cancelled.
588    ///
589    /// Note that there is no guarantee that the view-process or operating system will actually set a block, there
590    /// is no error result because operating systems can silently ignore block requests at any moment, even after
591    /// an initial successful block.
592    ///
593    /// Set to an empty text to remove the warning.
594    pub fn set_system_shutdown_warn(&mut self, id: WindowId, reason: Txt);
595
596    /// Set the custom menu items for the system application menu.
597    ///
598    /// The application menu is shown outside the app windows, usually at the top of the main screen in macOS and Gnome desktops.
599    ///
600    /// Set to empty to remove the menu.
601    pub fn set_app_menu(&mut self, menu: menu::AppMenu);
602
603    /// Set the tray icon indicator for the app.
604    ///
605    /// This is a small status indicator icon displayed near the notifications area.
606    pub fn set_tray_icon(&mut self, indicator: menu::TrayIcon);
607
608    /// Licenses that may be required to be displayed in the app about screen.
609    ///
610    /// This is specially important for prebuilt view users, as the tools that scrap licenses
611    /// may not find the prebuilt dependencies.
612    pub fn third_party_licenses(&mut self) -> Vec<zng_tp_licenses::LicenseUsed>;
613
614    /// Call the API extension.
615    ///
616    /// The `extension_id` is the index of an extension in the extensions list provided by the view-process on init.
617    /// The `extension_request` is any data required by the extension.
618    ///
619    /// Returns the extension response or [`ApiExtensionPayload::unknown_extension`] if the `extension_id` is
620    /// not on the list, or [`ApiExtensionPayload::invalid_request`] if the `extension_request` is not in a
621    /// format expected by the extension.
622    pub fn app_extension(&mut self, extension_id: ApiExtensionId, extension_request: ApiExtensionPayload) -> ApiExtensionPayload;
623
624    /// Call the API extension.
625    ///
626    /// This is similar to [`Api::app_extension`], but is targeting the instance of an extension associated
627    /// with the `id` window or headless surface.
628    pub fn window_extension(
629        &mut self,
630        id: WindowId,
631        extension_id: ApiExtensionId,
632        extension_request: ApiExtensionPayload,
633    ) -> ApiExtensionPayload;
634
635    /// Call the API extension.
636    ///
637    /// This is similar to [`Api::app_extension`], but is targeting the instance of an extension associated
638    /// with the `id` renderer.
639    pub fn render_extension(
640        &mut self,
641        id: WindowId,
642        extension_id: ApiExtensionId,
643        extension_request: ApiExtensionPayload,
644    ) -> ApiExtensionPayload;
645
646    /// Returns the `count` and notifies [`Event::Pong`] after ensuring the view-process is responsive.
647    ///
648    /// The app-process and view-process automatically monitor message frequency to detect when the paired process
649    /// is stuck. View-process implementers must only ensure the response event goes through its *main loop* to get an
650    /// accurate read of if it is stuck.
651    pub fn ping(&mut self, count: u16) -> u16;
652}
653
654pub(crate) type AnyResult<T> = std::result::Result<T, Box<dyn std::error::Error>>;