quickgui 0.1.1

A damage-driven, GPU-accelerated desktop GUI foundation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
use super::*;

/// A QuickGUI application whose native event loop is advanced by an external runtime.
///
/// Create and pump this value on the platform application thread. Each call still dispatches
/// redraw and lifecycle callbacks synchronously inside Winit, which is required for correct macOS
/// resize behavior. A blocking [`Application::run`] remains the simplest choice for ordinary Rust
/// apps.
#[cfg(not(target_arch = "wasm32"))]
pub struct AppRunner {
    pub(super) event_loop: EventLoop<RuntimeEvent>,
    pub(super) runtime: Runtime,
    pub(super) root_window: WindowHandle,
    pub(super) root_window_pending: bool,
    pub(super) status: AppRunStatus,
    pub(super) relaunched_process: Option<RelaunchedProcess>,
}

#[cfg(not(target_arch = "wasm32"))]
impl AppRunner {
    /// Advance native events until a redraw completes, the timeout elapses, or the app exits.
    ///
    /// `None` may block indefinitely. External runtimes can pair it with [`Self::waker`] so their
    /// command producer interrupts the blocked pump without periodic polling.
    pub fn pump(&mut self, timeout: Option<Duration>) -> Result<AppRunStatus, AppError> {
        if matches!(self.status, AppRunStatus::Exited(_)) {
            return Ok(self.status);
        }
        let status = self.event_loop.pump_app_events(timeout, &mut self.runtime);
        if let Some(error) = self.runtime.fatal_error.take() {
            self.status = AppRunStatus::Exited(1);
            self.runtime.relaunch_request.take();
            self.runtime.finalize_process_services();
            return Err(error);
        }
        self.status = match status {
            PumpStatus::Continue => AppRunStatus::Continue,
            PumpStatus::Exit(code) => AppRunStatus::Exited(code),
        };
        if matches!(self.status, AppRunStatus::Exited(_)) {
            self.runtime.finalize_process_services();
            if let Some(request) = self.runtime.relaunch_request.take() {
                self.relaunched_process = Some(
                    request
                        .spawn()
                        .map_err(|error| AppError::Platform(error.to_string()))?,
                );
            }
        }
        Ok(self.status)
    }

    /// Return a thread-safe handle that interrupts a blocking [`Self::pump`] call.
    pub fn waker(&self) -> AppRunnerWaker {
        AppRunnerWaker {
            proxy: self.runtime.event_proxy.clone(),
        }
    }

    /// Stable handle of the initial application window.
    ///
    /// A windowless [`Application`] reserves this handle until [`Self::open_window`] queues its
    /// first top-level window.
    pub const fn root_window(&self) -> WindowHandle {
        self.root_window
    }

    /// Whether the platform application completed its native initialization.
    ///
    /// A newly created runner becomes ready during its first [`Self::pump`] call, even when it
    /// does not yet own a window. Embedding runtimes should wait for this boundary before opening
    /// their first window.
    pub const fn is_ready(&self) -> bool {
        self.runtime.ready
    }

    /// Window currently activated for a synchronous core callback, if any.
    ///
    /// View and event callbacks should normally use [`ViewContext::window_handle`] and
    /// [`EventContext::window_handle`] directly. This accessor lets bindings project that same
    /// core context into their host language without maintaining separate window identity.
    pub fn current_window(&self) -> Option<WindowHandle> {
        self.runtime.current_handle()
    }

    /// Read the hardware pointer in global logical desktop coordinates.
    pub fn cursor_screen_position(&self) -> Result<Point, PlatformError> {
        cursor_screen_position(&self.runtime.displays)
    }

    /// Immutable package identity supplied before application startup.
    pub fn app_info(&self) -> Option<&AppInfo> {
        self.runtime.app_info.as_ref()
    }

    /// Standard application paths resolved once during startup.
    pub fn app_paths(&self) -> Option<&AppPaths> {
        self.runtime.app_paths.as_ref()
    }

    /// Immutable operating-system and preferred-language snapshot captured at startup.
    pub fn system_info(&self) -> &SystemInfo {
        &self.runtime.system_info
    }

    /// Native integration backends compiled for this target.
    pub const fn desktop_integration_support(&self) -> DesktopIntegrationSupport {
        DesktopIntegrationSupport::current()
    }

    /// Current application-wide native menu declaration, including a queued replacement.
    pub fn application_menus(&self) -> &[Menu] {
        self.runtime
            .external_menus
            .as_deref()
            .unwrap_or(&self.runtime.menus)
    }

    /// Effective native menu declaration for one queued or mounted window.
    pub fn window_menus(&self, handle: WindowHandle) -> Option<&[Menu]> {
        let application_menus = self.application_menus();
        if self.runtime.current_handle() == Some(handle) {
            return Some(
                self.runtime
                    .config
                    .window_menus
                    .as_deref()
                    .unwrap_or(application_menus),
            );
        }
        if let Some(window_id) = self.runtime.window_handles.get(&handle)
            && let Some(entry) = self.runtime.windows.get(window_id)
        {
            return Some(
                entry
                    .config
                    .window_menus
                    .as_deref()
                    .unwrap_or(application_menus),
            );
        }
        self.runtime
            .pending_windows
            .iter()
            .find(|request| request.handle == handle)
            .map(|request| {
                request
                    .options
                    .window_menus
                    .as_deref()
                    .unwrap_or(application_menus)
            })
    }

    /// Current bounded system appearance and accessibility-preference snapshot.
    pub const fn system_preferences(&self) -> SystemPreferences {
        self.runtime.system_preferences
    }

    /// Immutable bounded lookup of mounted and queued application windows.
    pub fn window_registry(&self) -> WindowRegistry {
        self.runtime.window_registry()
    }

    pub fn active_window(&self) -> Option<WindowHandle> {
        self.runtime.active_window_handle()
    }

    /// Queue a new top-level window from an embedding runtime.
    ///
    /// The handle is stable immediately. The platform window is created during the next event
    /// loop turn, so callers can finish installing retained state before pumping again.
    pub fn open_window<V: View>(
        &mut self,
        options: WindowOptions,
        view: V,
    ) -> Result<WindowHandle, AppError> {
        if !matches!(self.status, AppRunStatus::Continue) {
            return Err(AppError::Window(
                "cannot open a window after the application event loop exited".to_owned(),
            ));
        }
        validate_window_options(&options).map_err(|error| AppError::Window(error.to_string()))?;
        self.runtime
            .event_proxy
            .send_event(RuntimeEvent::ExternalCommandsReady)
            .map_err(|_| AppError::Window("application event loop is closed".to_owned()))?;
        let request = if self.root_window_pending {
            self.root_window_pending = false;
            WindowRequest::with_handle(view, options, None, self.root_window)
        } else {
            WindowRequest::new(view, options)
        };
        let handle = request.handle;
        self.runtime.pending_windows.push_back(request);
        Ok(handle)
    }

    /// Queue a native popover anchored to one currently mounted element in a parent window.
    ///
    /// Embedding runtimes may call this before the parent's first presented frame. Resolution is
    /// queued with the child request and occurs at the window-creation boundary, after every
    /// earlier parent request has completed retained layout. This preserves the same display-aware
    /// behavior and core-owned trigger focus restoration as [`EventContext::open_system_popover`]
    /// without polling or a geometry observer.
    pub fn open_system_popover<V: View>(
        &mut self,
        parent: WindowHandle,
        anchor: ElementId,
        options: WindowOptions,
        view: V,
    ) -> Result<WindowHandle, AppError> {
        if !matches!(self.status, AppRunStatus::Continue) {
            return Err(AppError::Window(
                "cannot open a popover after the application event loop exited".to_owned(),
            ));
        }
        validate_window_options(&options).map_err(|error| AppError::Window(error.to_string()))?;
        if options.kind != WindowKind::SystemPopover || options.popover.is_none() {
            return Err(AppError::Window(
                WindowCommandError::InvalidPopoverConfiguration.to_string(),
            ));
        }
        self.runtime
            .event_proxy
            .send_event(RuntimeEvent::ExternalCommandsReady)
            .map_err(|_| AppError::Window("application event loop is closed".to_owned()))?;
        let mut request = WindowRequest::with_parent(view, options, Some(parent));
        request.popover_anchor_element = Some(anchor);
        let handle = request.handle;
        self.runtime.pending_windows.push_back(request);
        Ok(handle)
    }

    /// Mark one externally owned view dirty and request at most one native redraw.
    ///
    /// A window queued for creation also returns `true`: its first render will read the newest
    /// retained state without scheduling a redundant frame.
    pub fn invalidate_window(&mut self, handle: WindowHandle) -> bool {
        if !matches!(self.status, AppRunStatus::Continue) {
            return false;
        }
        if self
            .runtime
            .pending_windows
            .iter()
            .any(|request| request.handle == handle)
        {
            return true;
        }
        self.runtime.invalidate_external(handle)
    }

    /// Focus one mounted element from an embedding runtime.
    ///
    /// This is the imperative counterpart to [`crate::Element::auto_focus`]. It is intended for
    /// host bindings that expose web-like `element.focus()` behavior after an external event has
    /// returned to the host language. The request is applied synchronously, reasserts native
    /// keyboard ownership, and schedules one redraw even when the element was already logically
    /// focused.
    pub fn focus_element(&mut self, handle: WindowHandle, element: ElementId) -> bool {
        if !matches!(self.status, AppRunStatus::Continue) {
            return false;
        }
        self.runtime.focus_external(handle, element)
    }

    /// Present a platform-native prompt owned by one mounted window.
    ///
    /// This is the embedding-runtime counterpart to [`EventContext::prompt`]. The returned
    /// future remains on the platform thread and resolves after the operating system closes the
    /// prompt; no redraw polling is introduced while it is visible.
    pub fn prompt(
        &mut self,
        window: WindowHandle,
        level: PromptLevel,
        message: impl Into<Arc<str>>,
        detail: Option<&str>,
        buttons: &[PromptButton],
    ) -> Result<PlatformResponse<usize>, PlatformError> {
        if !matches!(self.status, AppRunStatus::Continue)
            || !self.runtime.window_handles.contains_key(&window)
        {
            return Err(PlatformError::Unavailable);
        }
        if self.runtime.platform_requests.len() == crate::MAX_PENDING_PLATFORM_REQUESTS {
            return Err(PlatformError::PendingQueueFull);
        }
        let (request, response) =
            PlatformRequest::prompt(window, level, message, detail.map(Arc::from), buttons)?;
        self.runtime
            .event_proxy
            .send_event(RuntimeEvent::ExternalCommandsReady)
            .map_err(|_| PlatformError::Unavailable)?;
        self.runtime.platform_requests.push_back(request);
        Ok(response)
    }

    /// Present an application-modal native prompt without attaching it to a window.
    pub fn prompt_application(
        &mut self,
        level: PromptLevel,
        message: impl Into<Arc<str>>,
        detail: Option<&str>,
        buttons: &[PromptButton],
    ) -> Result<PlatformResponse<usize>, PlatformError> {
        if !matches!(self.status, AppRunStatus::Continue) {
            return Err(PlatformError::Unavailable);
        }
        if self.runtime.platform_requests.len() == crate::MAX_PENDING_PLATFORM_REQUESTS {
            return Err(PlatformError::PendingQueueFull);
        }
        let (request, response) =
            PlatformRequest::application_prompt(level, message, detail.map(Arc::from), buttons)?;
        self.runtime
            .event_proxy
            .send_event(RuntimeEvent::ExternalCommandsReady)
            .map_err(|_| PlatformError::Unavailable)?;
        self.runtime.platform_requests.push_back(request);
        Ok(response)
    }

    /// Present a platform-native open panel owned by one mounted window.
    ///
    /// `Ok(None)` means the user cancelled. The returned future stays on the platform thread and
    /// resolves after the operating system closes the panel.
    pub fn prompt_for_paths(
        &mut self,
        window: WindowHandle,
        options: PathPromptOptions,
    ) -> Result<PathPromptResponse, PlatformError> {
        if !matches!(self.status, AppRunStatus::Continue)
            || !self.runtime.window_handles.contains_key(&window)
        {
            return Err(PlatformError::Unavailable);
        }
        if self.runtime.platform_requests.len() == crate::MAX_PENDING_PLATFORM_REQUESTS {
            return Err(PlatformError::PendingQueueFull);
        }
        let (request, response) = PlatformRequest::open_paths(window, options)?;
        self.runtime
            .event_proxy
            .send_event(RuntimeEvent::ExternalCommandsReady)
            .map_err(|_| PlatformError::Unavailable)?;
        self.runtime.platform_requests.push_back(request);
        Ok(response)
    }

    /// Present an application-modal native open panel without attaching it to a window.
    pub fn prompt_for_paths_application(
        &mut self,
        options: PathPromptOptions,
    ) -> Result<PathPromptResponse, PlatformError> {
        if !matches!(self.status, AppRunStatus::Continue) {
            return Err(PlatformError::Unavailable);
        }
        if self.runtime.platform_requests.len() == crate::MAX_PENDING_PLATFORM_REQUESTS {
            return Err(PlatformError::PendingQueueFull);
        }
        let (request, response) = PlatformRequest::application_open_paths(options)?;
        self.runtime
            .event_proxy
            .send_event(RuntimeEvent::ExternalCommandsReady)
            .map_err(|_| PlatformError::Unavailable)?;
        self.runtime.platform_requests.push_back(request);
        Ok(response)
    }

    /// Present a platform-native save panel owned by one mounted window.
    ///
    /// `Ok(None)` means the user cancelled. The returned future stays on the platform thread and
    /// resolves after the operating system closes the panel.
    pub fn prompt_for_new_path(
        &mut self,
        window: WindowHandle,
        options: SavePathOptions,
    ) -> Result<SavePathResponse, PlatformError> {
        if !matches!(self.status, AppRunStatus::Continue)
            || !self.runtime.window_handles.contains_key(&window)
        {
            return Err(PlatformError::Unavailable);
        }
        if self.runtime.platform_requests.len() == crate::MAX_PENDING_PLATFORM_REQUESTS {
            return Err(PlatformError::PendingQueueFull);
        }
        let (request, response) = PlatformRequest::save_path(window, options)?;
        self.runtime
            .event_proxy
            .send_event(RuntimeEvent::ExternalCommandsReady)
            .map_err(|_| PlatformError::Unavailable)?;
        self.runtime.platform_requests.push_back(request);
        Ok(response)
    }

    /// Present an application-modal native save panel without attaching it to a window.
    pub fn prompt_for_new_path_application(
        &mut self,
        options: SavePathOptions,
    ) -> Result<SavePathResponse, PlatformError> {
        if !matches!(self.status, AppRunStatus::Continue) {
            return Err(PlatformError::Unavailable);
        }
        if self.runtime.platform_requests.len() == crate::MAX_PENDING_PLATFORM_REQUESTS {
            return Err(PlatformError::PendingQueueFull);
        }
        let (request, response) = PlatformRequest::application_save_path(options)?;
        self.runtime
            .event_proxy
            .send_event(RuntimeEvent::ExternalCommandsReady)
            .map_err(|_| PlatformError::Unavailable)?;
        self.runtime.platform_requests.push_back(request);
        Ok(response)
    }

    /// Close a queued or mounted window.
    ///
    /// Returns `false` when the handle is unknown or the application already exited.
    pub fn close_window(&mut self, handle: WindowHandle) -> bool {
        if !matches!(self.status, AppRunStatus::Continue) {
            return false;
        }
        let pending = self
            .runtime
            .pending_windows
            .iter()
            .position(|request| request.handle == handle);
        let mounted = self.runtime.window_handles.contains_key(&handle)
            || self.runtime.current_handle() == Some(handle);
        if pending.is_none() && !mounted {
            return false;
        }
        if self
            .runtime
            .event_proxy
            .send_event(RuntimeEvent::ExternalCommandsReady)
            .is_err()
        {
            return false;
        }
        if let Some(index) = pending {
            self.runtime.pending_windows.remove(index);
        } else if !self.runtime.close_requests.contains(&handle) {
            self.runtime.close_requests.push(handle);
        }
        true
    }

    /// Mark the root view dirty and request exactly one native redraw.
    ///
    /// Returns `false` only after exit or before the first pump has mounted the root window. State
    /// installed before that first pump is naturally read by the initial render.
    pub fn invalidate_root(&mut self) -> bool {
        self.invalidate_window(self.root_window)
    }

    pub const fn status(&self) -> AppRunStatus {
        self.status
    }

    /// Replacement process spawned after this runner completed orderly teardown, if any.
    pub const fn relaunched_process(&self) -> Option<RelaunchedProcess> {
        self.relaunched_process
    }
}

/// Live application context supplied after native launch and to application callbacks.
///
/// This is the application-wide form of [`EventContext`]. A launch callback has no current
/// window; windows are created with [`App::open_window`].
pub type App = EventContext;

/// Configures and starts a native application independently from its windows.
///
/// Ordinary Rust applications call [`Self::run`] and open their initial windows from its launch
/// callback. Language bindings and other embedders can instead convert it into an [`AppRunner`],
/// pump once until [`AppRunner::is_ready`] is true, then queue a window with
/// [`AppRunner::open_window`].
pub struct Application {
    pub(super) app_info: Option<AppInfo>,
    pub(super) app_paths: Option<AppPaths>,
    pub(super) keymap: Keymap,
    pub(super) menus: Vec<Menu>,
    pub(super) globals: GlobalStore,
    pub(super) assets: Assets,
    pub(super) fonts: Vec<FontSource>,
    pub(super) application_callbacks: ApplicationCallbacks,
    pub(super) quit_mode: QuitMode,
}

impl Application {
    pub fn new() -> Self {
        Self {
            app_info: None,
            app_paths: None,
            keymap: Keymap::default(),
            menus: Vec::new(),
            globals: GlobalStore::default(),
            assets: Assets::default(),
            fonts: Vec::new(),
            application_callbacks: ApplicationCallbacks::default(),
            quit_mode: QuitMode::Default,
        }
    }

    /// Configure when closing the final window terminates the application.
    pub fn quit_mode(mut self, mode: QuitMode) -> Self {
        self.quit_mode = mode;
        self
    }

    /// GPUI-compatible alias for [`Self::quit_mode`].
    pub fn with_quit_mode(self, mode: QuitMode) -> Self {
        self.quit_mode(mode)
    }

    /// Install the immutable package identity exposed by every core context.
    ///
    /// Standard application paths are resolved from its identifier at startup unless
    /// [`Self::app_paths`] supplies an explicit snapshot.
    pub fn app_info(mut self, info: AppInfo) -> Self {
        self.app_info = Some(info);
        self
    }

    pub fn with_app_info(self, info: AppInfo) -> Self {
        self.app_info(info)
    }

    /// Override the standard path snapshot retained by the application core.
    pub fn app_paths(mut self, paths: AppPaths) -> Self {
        self.app_paths = Some(paths);
        self
    }

    pub fn with_app_paths(self, paths: AppPaths) -> Self {
        self.app_paths(paths)
    }

    /// Install the immutable application asset source used by every window.
    pub fn with_assets(mut self, source: impl crate::AssetSource) -> Self {
        self.assets = Assets::new(source);
        self
    }

    /// Install an already shared application asset handle.
    pub fn assets(mut self, assets: Assets) -> Self {
        self.assets = assets;
        self
    }

    /// Register one custom OpenType font file or asset path before launch.
    pub fn font(mut self, font: impl Into<FontSource>) -> Self {
        self.fonts.push(font.into());
        self
    }

    /// Register custom fonts in declaration order before launch.
    pub fn fonts(mut self, fonts: impl IntoIterator<Item = impl Into<FontSource>>) -> Self {
        self.fonts.extend(fonts.into_iter().map(Into::into));
        self
    }

    /// Add application key bindings. Later bindings take precedence at equal context depth.
    pub fn bind_keys(mut self, bindings: impl IntoIterator<Item = KeyBinding>) -> Self {
        self.keymap.add_bindings(bindings);
        self
    }

    /// Replace the complete application keymap.
    pub fn keymap(mut self, keymap: Keymap) -> Self {
        self.keymap = keymap;
        self
    }

    /// Append one declarative application menu.
    pub fn menu(mut self, menu: Menu) -> Self {
        self.menus.push(menu);
        self
    }

    /// Replace the complete declarative application menu set.
    pub fn menus(mut self, menus: impl IntoIterator<Item = Menu>) -> Self {
        self.menus = menus.into_iter().collect();
        self
    }

    /// Install or replace one main-thread application-global value before launch.
    pub fn global<G: Global>(self, global: G) -> Self {
        self.globals.set(global);
        self
    }

    /// Handle URLs supplied by the operating system, including `file:` URLs.
    pub fn on_open_urls(
        mut self,
        callback: impl FnMut(OpenUrls, &mut EventContext) + 'static,
    ) -> Self {
        self.application_callbacks.open_urls = Some(Box::new(callback));
        self
    }

    /// Handle a Dock/Finder request to reopen an already-running macOS application.
    pub fn on_reopen(mut self, callback: impl FnMut(bool, &mut EventContext) + 'static) -> Self {
        self.application_callbacks.reopen = Some(Box::new(callback));
        self
    }

    /// Handle the operating system waking from sleep.
    pub fn on_system_wake(mut self, callback: impl FnMut(&mut EventContext) + 'static) -> Self {
        self.application_callbacks.system_wake = Some(Box::new(callback));
        self
    }

    /// Handle a native keyboard-layout change.
    pub fn on_keyboard_layout_change(
        mut self,
        callback: impl FnMut(&KeyboardLayout, &mut EventContext) + 'static,
    ) -> Self {
        self.application_callbacks.keyboard_layout = Some(Box::new(callback));
        self
    }

    /// Handle activation of a delivered system notification or action button.
    pub fn on_system_notification_response(
        mut self,
        callback: impl FnMut(SystemNotificationResponse, &mut EventContext) + 'static,
    ) -> Self {
        self.application_callbacks.system_notification_response = Some(Box::new(callback));
        self
    }

    /// Handle a registered system-wide keyboard shortcut when it is pressed.
    pub fn on_global_shortcut(
        mut self,
        callback: impl FnMut(GlobalShortcutEvent, &mut EventContext) + 'static,
    ) -> Self {
        self.application_callbacks.global_shortcut = Some(Box::new(callback));
        self
    }

    /// Handle arguments and the working directory forwarded by a later process.
    pub fn on_second_instance(
        mut self,
        callback: impl FnMut(SecondInstanceEvent, &mut EventContext) + 'static,
    ) -> Self {
        self.application_callbacks.second_instance = Some(Box::new(callback));
        self
    }

    /// Handle native power, thermal, shutdown, and login-session transitions.
    pub fn on_power_event(
        mut self,
        callback: impl FnMut(PowerEvent, &mut EventContext) + 'static,
    ) -> Self {
        self.application_callbacks.power_event = Some(Box::new(callback));
        self
    }

    /// Handle clicks, scrolling, and native menu actions from application tray icons.
    pub fn on_tray_event(
        mut self,
        callback: impl FnMut(TrayEvent, &mut EventContext) + 'static,
    ) -> Self {
        self.application_callbacks.tray_event = Some(Box::new(callback));
        self
    }

    /// Run after a native window and its owned resources have been removed.
    pub fn on_window_closed(
        mut self,
        callback: impl FnMut(WindowHandle, &mut EventContext) + 'static,
    ) -> Self {
        self.application_callbacks.window_closed = Some(Box::new(callback));
        self
    }

    /// Run the first preventable phase of an orderly application quit.
    pub fn on_before_quit(
        mut self,
        callback: impl FnMut(QuitRequest, &mut EventContext) + 'static,
    ) -> Self {
        self.application_callbacks.before_quit = Some(Box::new(callback));
        self
    }

    /// Run the final preventable phase immediately before owned windows are torn down.
    pub fn on_will_quit(
        mut self,
        callback: impl FnMut(QuitRequest, &mut EventContext) + 'static,
    ) -> Self {
        self.application_callbacks.will_quit = Some(Box::new(callback));
        self
    }

    /// Convert this windowless application into an externally pumped native event loop.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn into_runner(self) -> Result<AppRunner, AppError> {
        let event_loop = EventLoop::with_user_event().build()?;
        event_loop.set_control_flow(ControlFlow::Wait);
        let root_window = WindowHandle::next();
        let runtime = Runtime::new(
            RuntimeStartup {
                initial_window: None,
                app_info: self.app_info,
                app_paths: self.app_paths,
                globals: self.globals,
                keymap: self.keymap,
                menus: self.menus,
                assets: self.assets,
                fonts: self.fonts,
                application_callbacks: self.application_callbacks,
                quit_mode: self.quit_mode,
            },
            event_loop.create_proxy(),
        )?;
        Ok(AppRunner {
            event_loop,
            runtime,
            root_window,
            root_window_pending: true,
            status: AppRunStatus::Continue,
            relaunched_process: None,
        })
    }

    /// Start the native event loop and invoke `on_finish_launching` once application-wide native
    /// initialization is complete.
    ///
    /// The callback receives a windowless [`App`] context. Open the initial window there with
    /// [`App::open_window`].
    pub fn run(
        mut self,
        on_finish_launching: impl FnOnce(&mut App) + 'static,
    ) -> Result<(), AppError> {
        self.application_callbacks.finish_launching = Some(Box::new(on_finish_launching));

        #[cfg(not(target_arch = "wasm32"))]
        {
            let AppRunner {
                event_loop,
                mut runtime,
                ..
            } = self.into_runner()?;
            let run_result = event_loop.run_app(&mut runtime);
            let fatal_error = runtime.fatal_error.take();
            let relaunch = runtime.relaunch_request.take();
            runtime.finalize_process_services();
            drop(runtime);
            run_result?;
            if let Some(error) = fatal_error {
                return Err(error);
            }
            if let Some(request) = relaunch {
                request
                    .spawn()
                    .map_err(|error| AppError::Platform(error.to_string()))?;
            }
            Ok(())
        }

        #[cfg(target_arch = "wasm32")]
        {
            let event_loop = EventLoop::with_user_event().build()?;
            event_loop.set_control_flow(ControlFlow::Wait);
            let mut runtime = Runtime::new(
                RuntimeStartup {
                    initial_window: None,
                    app_info: self.app_info,
                    app_paths: self.app_paths,
                    globals: self.globals,
                    keymap: self.keymap,
                    menus: self.menus,
                    assets: self.assets,
                    fonts: self.fonts,
                    application_callbacks: self.application_callbacks,
                    quit_mode: self.quit_mode,
                },
                event_loop.create_proxy(),
            )?;
            event_loop.run_app(&mut runtime)?;
            if runtime.relaunch_request.is_some() {
                return Err(AppError::Platform(
                    "application relaunch is unavailable on WebAssembly".to_owned(),
                ));
            }
            match runtime.fatal_error.take() {
                Some(error) => Err(error),
                None => Ok(()),
            }
        }
    }
}

impl Default for Application {
    fn default() -> Self {
        Self::new()
    }
}