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
use super::*;

impl AppRunner {
    /// Request an orderly application exit after native windows and owned resources close.
    pub fn exit(&mut self) -> bool {
        if !matches!(self.status, AppRunStatus::Continue) || self.runtime.exit_requested {
            return false;
        }
        if self
            .runtime
            .event_proxy
            .send_event(RuntimeEvent::ExternalCommandsReady)
            .is_err()
        {
            return false;
        }
        self.runtime.exit_requested = true;
        true
    }

    /// Request an orderly relaunch preserving the current process arguments and directory.
    pub fn relaunch(&mut self) -> std::result::Result<bool, crate::SystemIntegrationError> {
        self.relaunch_with(RelaunchOptions::default())
    }

    /// Request an orderly relaunch with explicit process overrides.
    ///
    /// The replacement is spawned only after a later [`Self::pump`] observes event-loop exit and
    /// releases the single-instance guard, native integrations, windows, and foreground work.
    pub fn relaunch_with(
        &mut self,
        options: RelaunchOptions,
    ) -> std::result::Result<bool, crate::SystemIntegrationError> {
        let request = options.prepare()?;
        if !matches!(self.status, AppRunStatus::Continue) || self.runtime.exit_requested {
            return Ok(false);
        }
        self.runtime
            .event_proxy
            .send_event(RuntimeEvent::ExternalCommandsReady)
            .map_err(|_| {
                crate::SystemIntegrationError::Platform(Arc::from(
                    "the application event loop is closed",
                ))
            })?;
        self.runtime.relaunch_request = Some(request);
        self.runtime.exit_requested = true;
        Ok(true)
    }

    /// Return the latest bounded display snapshot retained by the application runtime.
    ///
    /// This does not poll the operating system. The snapshot is replaced at native display-change
    /// boundaries and is therefore safe for embedding runtimes to read after each pump.
    pub fn displays(&self) -> Displays {
        self.runtime.displays.clone()
    }

    /// Return the latest immutable keyboard-layout snapshot retained by the runtime.
    pub fn keyboard_layout(&self) -> KeyboardLayout {
        self.runtime.keyboard.layout().clone()
    }

    /// Return a constant-size snapshot of one mounted native window.
    pub fn window_state(&self, handle: WindowHandle) -> Option<WindowState> {
        self.runtime.window_state_for(handle)
    }

    /// Read one bounded item from the operating system's general clipboard.
    pub fn read_from_clipboard(&self) -> Result<Option<ClipboardItem>, crate::ClipboardError> {
        self.runtime.clipboard.read(ClipboardTarget::General)
    }

    /// Atomically replace the operating system's general clipboard with one bounded item.
    pub fn write_to_clipboard(&self, item: ClipboardItem) -> Result<(), crate::ClipboardError> {
        self.runtime.clipboard.write(ClipboardTarget::General, item)
    }

    /// Read Linux's primary-selection clipboard.
    #[cfg(target_os = "linux")]
    pub fn read_from_selection_clipboard(
        &self,
    ) -> Result<Option<ClipboardItem>, crate::ClipboardError> {
        self.runtime.clipboard.read(ClipboardTarget::Selection)
    }

    /// Replace Linux's primary-selection clipboard.
    #[cfg(target_os = "linux")]
    pub fn write_to_selection_clipboard(
        &self,
        item: ClipboardItem,
    ) -> Result<(), crate::ClipboardError> {
        self.runtime
            .clipboard
            .write(ClipboardTarget::Selection, item)
    }

    /// Ask the operating system to open a URL with its registered handler.
    pub fn open_external(
        &mut self,
        url: impl Into<Arc<str>>,
    ) -> Result<ShellResponse, PlatformError> {
        let (request, response) = PlatformRequest::open_url_response(url)?;
        self.queue_platform_response(request)?;
        Ok(response)
    }

    /// Ask the operating system to open a filesystem item with its registered application.
    pub fn open_path(&mut self, path: impl Into<PathBuf>) -> Result<ShellResponse, PlatformError> {
        let (request, response) = PlatformRequest::open_path_response(path)?;
        self.queue_platform_response(request)?;
        Ok(response)
    }

    /// Reveal a filesystem item in the platform file manager.
    pub fn reveal_path(
        &mut self,
        path: impl Into<PathBuf>,
    ) -> Result<ShellResponse, PlatformError> {
        let (request, response) = PlatformRequest::reveal_path_response(path)?;
        self.queue_platform_response(request)?;
        Ok(response)
    }

    /// Move a filesystem item to the operating system trash or recycle bin.
    pub fn trash_path(&mut self, path: impl Into<PathBuf>) -> Result<ShellResponse, PlatformError> {
        let (request, response) = PlatformRequest::trash_path_response(path)?;
        self.queue_platform_response(request)?;
        Ok(response)
    }

    /// Post or replace one operating-system notification.
    pub fn show_system_notification(
        &mut self,
        notification: SystemNotification,
    ) -> Result<(), PlatformError> {
        let request = PlatformRequest::show_system_notification(notification)?;
        #[cfg(target_os = "windows")]
        validate_windows_notification_app_info(self.runtime.app_info.as_ref())?;
        self.queue_platform_request(request)
    }

    /// Dismiss the operating-system notification identified by `tag`, where supported.
    pub fn dismiss_system_notification(
        &mut self,
        tag: impl Into<Arc<str>>,
    ) -> Result<(), PlatformError> {
        let request = PlatformRequest::dismiss_system_notification(tag)?;
        #[cfg(target_os = "windows")]
        validate_windows_notification_app_info(self.runtime.app_info.as_ref())?;
        self.queue_platform_request(request)
    }

    /// Query notification authorization without displaying a prompt.
    pub fn notification_permission_status(
        &mut self,
    ) -> Result<NotificationPermissionResponse, PlatformError> {
        #[cfg(target_os = "windows")]
        validate_windows_notification_app_info(self.runtime.app_info.as_ref())?;
        let (request, response) = PlatformRequest::notification_permission_status();
        self.queue_platform_response(request)?;
        Ok(response)
    }

    /// Explicitly request notification authorization where required by the operating system.
    pub fn request_notification_permission(
        &mut self,
    ) -> Result<NotificationPermissionResponse, PlatformError> {
        #[cfg(target_os = "windows")]
        validate_windows_notification_app_info(self.runtime.app_info.as_ref())?;
        let (request, response) = PlatformRequest::request_notification_permission();
        self.queue_platform_response(request)?;
        Ok(response)
    }

    pub fn set_dock_badge(&mut self, value: impl Into<Arc<str>>) -> Result<(), PlatformError> {
        if !DesktopIntegrationSupport::current().dock_badges {
            return Err(PlatformError::Unsupported);
        }
        let value = value.into();
        self.queue_platform_request(PlatformRequest::set_dock_badge(
            (!value.is_empty()).then_some(value),
        )?)
    }

    pub fn clear_dock_badge(&mut self) -> Result<(), PlatformError> {
        if !DesktopIntegrationSupport::current().dock_badges {
            return Err(PlatformError::Unsupported);
        }
        self.queue_platform_request(PlatformRequest::set_dock_badge(None)?)
    }

    /// Last Dock badge successfully applied by the core runtime.
    pub fn dock_badge(&self) -> Option<&str> {
        #[cfg(target_os = "macos")]
        {
            self.runtime.dock_badge.as_deref()
        }
        #[cfg(not(target_os = "macos"))]
        {
            None
        }
    }

    pub fn set_dock_icon(&mut self, icon: Image) -> Result<(), PlatformError> {
        if !DesktopIntegrationSupport::current().dock_icons {
            return Err(PlatformError::Unsupported);
        }
        self.queue_platform_request(PlatformRequest::set_dock_icon(Some(icon)))
    }

    pub fn clear_dock_icon(&mut self) -> Result<(), PlatformError> {
        if !DesktopIntegrationSupport::current().dock_icons {
            return Err(PlatformError::Unsupported);
        }
        self.queue_platform_request(PlatformRequest::set_dock_icon(None))
    }

    pub fn set_dock_menu(&mut self, menu: Menu) -> Result<(), PlatformError> {
        if !DesktopIntegrationSupport::current().dock_menus {
            return Err(PlatformError::Unsupported);
        }
        self.queue_platform_request(PlatformRequest::set_dock_menu(Some(menu))?)
    }

    pub fn clear_dock_menu(&mut self) -> Result<(), PlatformError> {
        if !DesktopIntegrationSupport::current().dock_menus {
            return Err(PlatformError::Unsupported);
        }
        self.queue_platform_request(PlatformRequest::set_dock_menu(None)?)
    }

    /// Current macOS Dock menu declaration, after its request has been processed.
    pub fn dock_menu(&self) -> Option<&Menu> {
        #[cfg(target_os = "macos")]
        {
            self.runtime.dock_menu.as_ref()
        }
        #[cfg(not(target_os = "macos"))]
        {
            None
        }
    }

    pub fn add_recent_document(&mut self, path: impl Into<PathBuf>) -> Result<(), PlatformError> {
        if !DesktopIntegrationSupport::current().recent_documents {
            return Err(PlatformError::Unsupported);
        }
        self.queue_platform_request(PlatformRequest::add_recent_document(path)?)
    }

    pub fn clear_recent_documents(&mut self) -> Result<(), PlatformError> {
        if !DesktopIntegrationSupport::current().recent_documents {
            return Err(PlatformError::Unsupported);
        }
        self.queue_platform_request(PlatformRequest::ClearRecentDocuments)
    }

    pub fn show_about_panel(&mut self, options: AboutPanelOptions) -> Result<(), PlatformError> {
        if !DesktopIntegrationSupport::current().native_about_panel {
            return Err(PlatformError::Unsupported);
        }
        self.queue_platform_request(PlatformRequest::show_about_panel(options)?)
    }

    pub fn file_icon(
        &mut self,
        path: impl Into<PathBuf>,
        size: FileIconSize,
    ) -> Result<FileIconResponse, PlatformError> {
        if !DesktopIntegrationSupport::current().file_icons {
            return Err(PlatformError::Unsupported);
        }
        let (request, response) = PlatformRequest::get_file_icon(path, size)?;
        self.queue_platform_response(request)?;
        Ok(response)
    }

    pub fn set_user_tasks(
        &mut self,
        tasks: impl IntoIterator<Item = UserTask>,
    ) -> Result<ShellResponse, PlatformError> {
        if !DesktopIntegrationSupport::current().user_tasks {
            return Err(PlatformError::Unsupported);
        }
        let (request, response) = PlatformRequest::set_user_tasks(tasks.into_iter().collect())?;
        self.queue_platform_response(request)?;
        Ok(response)
    }

    pub fn clear_user_tasks(&mut self) -> Result<ShellResponse, PlatformError> {
        self.set_user_tasks(std::iter::empty())
    }

    /// Replace the complete native application menu set on the next event-loop turn.
    pub fn set_application_menus(
        &mut self,
        menus: impl IntoIterator<Item = Menu>,
    ) -> Result<(), PlatformError> {
        let menus = menus.into_iter().collect::<Vec<_>>();
        crate::menu::validate_menus(&menus).map_err(|_| PlatformError::InvalidMenu)?;
        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
        {
            let _ = menus;
            return Err(PlatformError::Unsupported);
        }
        #[cfg(any(target_os = "macos", target_os = "windows"))]
        {
            if !matches!(self.status, AppRunStatus::Continue) {
                return Err(PlatformError::Unavailable);
            }
            self.runtime
                .event_proxy
                .send_event(RuntimeEvent::ExternalCommandsReady)
                .map_err(|_| PlatformError::Unavailable)?;
            self.runtime.external_menus = Some(menus);
            Ok(())
        }
    }

    /// Remove every application-wide native menu.
    pub fn clear_application_menus(&mut self) -> Result<(), PlatformError> {
        self.set_application_menus(std::iter::empty())
    }

    /// Queue one title mutation for a mounted native window.
    pub fn set_window_title(
        &mut self,
        handle: WindowHandle,
        title: impl Into<String>,
    ) -> Result<(), WindowCommandError> {
        let title = title.into();
        validate_window_title(&title)?;
        self.queue_window_command(handle, WindowCommand::SetTitle(handle, title))
    }

    pub fn set_window_bounds(
        &mut self,
        handle: WindowHandle,
        bounds: WindowBounds,
    ) -> Result<(), WindowCommandError> {
        validate_window_bounds(bounds)?;
        self.queue_window_command(handle, WindowCommand::SetBounds(handle, bounds))
    }

    pub fn move_window(
        &mut self,
        handle: WindowHandle,
        position: Point,
    ) -> Result<(), WindowCommandError> {
        validate_window_position(position)?;
        self.queue_window_command(handle, WindowCommand::Move(handle, position))
    }

    pub fn resize_window(
        &mut self,
        handle: WindowHandle,
        size: Size,
    ) -> Result<(), WindowCommandError> {
        validate_window_size(size)?;
        self.queue_window_command(handle, WindowCommand::Resize(handle, size))
    }

    /// Queue a native minimize request for a mounted window.
    pub fn minimize_window(&mut self, handle: WindowHandle) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::Minimize(handle))
    }

    /// Restore a minimized or maximized native window to its windowed bounds.
    pub fn restore_window(&mut self, handle: WindowHandle) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::Restore(handle))
    }

    /// Toggle the platform-native maximized/zoomed state.
    pub fn maximize_window(&mut self, handle: WindowHandle) -> Result<(), WindowCommandError> {
        if self
            .window_state(handle)
            .is_some_and(|state| state.maximized)
        {
            return Ok(());
        }
        self.queue_window_command(handle, WindowCommand::Zoom(handle))
    }

    /// Set the native fullscreen state.
    pub fn set_window_fullscreen(
        &mut self,
        handle: WindowHandle,
        fullscreen: bool,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetFullscreen(handle, fullscreen))
    }

    /// Show or hide a mounted native window.
    pub fn set_window_visible(
        &mut self,
        handle: WindowHandle,
        visible: bool,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetVisible(handle, visible))
    }

    pub fn set_window_resizable(
        &mut self,
        handle: WindowHandle,
        resizable: bool,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetResizable(handle, resizable))
    }

    pub fn set_window_movable(
        &mut self,
        handle: WindowHandle,
        movable: bool,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetMovable(handle, movable))
    }

    pub fn set_window_minimum_size(
        &mut self,
        handle: WindowHandle,
        minimum: Option<Size>,
    ) -> Result<(), WindowCommandError> {
        if let Some(minimum) = minimum {
            validate_window_size(minimum)?;
        }
        self.queue_window_command(handle, WindowCommand::SetMinimumSize(handle, minimum))
    }

    pub fn set_window_maximum_size(
        &mut self,
        handle: WindowHandle,
        maximum: Option<Size>,
    ) -> Result<(), WindowCommandError> {
        if let Some(maximum) = maximum {
            validate_window_size(maximum)?;
        }
        self.queue_window_command(handle, WindowCommand::SetMaximumSize(handle, maximum))
    }

    pub fn set_window_minimizable(
        &mut self,
        handle: WindowHandle,
        minimizable: bool,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetMinimizable(handle, minimizable))
    }

    pub fn set_window_maximizable(
        &mut self,
        handle: WindowHandle,
        maximizable: bool,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetMaximizable(handle, maximizable))
    }

    pub fn set_window_closable(
        &mut self,
        handle: WindowHandle,
        closable: bool,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetClosable(handle, closable))
    }

    pub fn set_window_decorated(
        &mut self,
        handle: WindowHandle,
        decorated: bool,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetDecorated(handle, decorated))
    }

    pub fn set_window_shadow(
        &mut self,
        handle: WindowHandle,
        shadow: bool,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetShadow(handle, shadow))
    }

    pub fn set_window_content_protected(
        &mut self,
        handle: WindowHandle,
        protected: bool,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(
            handle,
            WindowCommand::SetContentProtected(handle, protected),
        )
    }

    pub fn set_window_level(
        &mut self,
        handle: WindowHandle,
        level: Option<WindowLevel>,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetWindowLevel(handle, level))
    }

    pub fn set_window_focusable(
        &mut self,
        handle: WindowHandle,
        focusable: bool,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetFocusable(handle, focusable))
    }

    pub fn set_window_skip_taskbar(
        &mut self,
        handle: WindowHandle,
        skip: bool,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetSkipTaskbar(handle, skip))
    }

    pub fn set_window_visible_on_all_workspaces(
        &mut self,
        handle: WindowHandle,
        visible: bool,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(
            handle,
            WindowCommand::SetVisibleOnAllWorkspaces(handle, visible),
        )
    }

    pub fn set_window_opacity(
        &mut self,
        handle: WindowHandle,
        opacity: f32,
    ) -> Result<(), WindowCommandError> {
        validate_window_opacity(opacity)?;
        self.queue_window_command(handle, WindowCommand::SetOpacity(handle, opacity))
    }

    pub fn set_window_icon(
        &mut self,
        handle: WindowHandle,
        icon: Option<Image>,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetIcon(handle, icon))
    }

    pub fn set_cursor_visible(
        &mut self,
        handle: WindowHandle,
        visible: bool,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetCursorVisible(handle, visible))
    }

    pub fn set_cursor_grab(
        &mut self,
        handle: WindowHandle,
        mode: CursorGrabMode,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetCursorGrab(handle, mode))
    }

    pub fn set_cursor_hit_test(
        &mut self,
        handle: WindowHandle,
        hit_test: bool,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetCursorHitTest(handle, hit_test))
    }

    pub fn set_cursor_position(
        &mut self,
        handle: WindowHandle,
        position: Point,
    ) -> Result<(), WindowCommandError> {
        validate_window_position(position)?;
        self.queue_window_command(handle, WindowCommand::SetCursorPosition(handle, position))
    }

    pub fn set_taskbar_progress(
        &mut self,
        handle: WindowHandle,
        state: TaskbarProgressState,
        progress: f32,
    ) -> Result<(), WindowCommandError> {
        validate_taskbar_progress(progress)?;
        self.queue_window_command(
            handle,
            WindowCommand::SetTaskbarProgress(handle, state, progress),
        )
    }

    pub fn set_taskbar_overlay_icon(
        &mut self,
        handle: WindowHandle,
        icon: Image,
        description: impl Into<String>,
    ) -> Result<(), WindowCommandError> {
        let description = description.into();
        validate_taskbar_overlay_description(Some(&description))?;
        self.queue_window_command(
            handle,
            WindowCommand::SetTaskbarOverlayIcon(handle, Some(icon), Some(description)),
        )
    }

    pub fn clear_taskbar_overlay_icon(
        &mut self,
        handle: WindowHandle,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(
            handle,
            WindowCommand::SetTaskbarOverlayIcon(handle, None, None),
        )
    }

    /// Bring a mounted native window to the front and give it keyboard focus.
    pub fn focus_window(&mut self, handle: WindowHandle) -> Result<(), WindowCommandError> {
        self.ensure_window_command_target(handle)?;
        if self.runtime.focus_requests.len() == MAX_PENDING_WINDOW_COMMANDS {
            return Err(WindowCommandError::QueueFull);
        }
        self.wake_for_external_command()?;
        if !self.runtime.focus_requests.contains(&handle) {
            self.runtime.focus_requests.push(handle);
        }
        Ok(())
    }

    /// Request informational attention for a mounted native window.
    pub fn request_window_attention(
        &mut self,
        handle: WindowHandle,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::RequestAttention(handle))
    }

    /// Set or clear the represented document path in native window chrome.
    pub fn set_window_represented_file(
        &mut self,
        handle: WindowHandle,
        path: Option<PathBuf>,
    ) -> Result<(), WindowCommandError> {
        if let Some(path) = &path {
            validate_window_document_path(path)?;
        }
        self.queue_window_command(handle, WindowCommand::SetRepresentedFile(handle, path))
    }

    /// Set the native unsaved-document indicator for a mounted window.
    pub fn set_window_document_edited(
        &mut self,
        handle: WindowHandle,
        edited: bool,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetDocumentEdited(handle, edited))
    }

    /// Force one native window to light/dark appearance, or follow the operating system with
    /// `None`.
    pub fn set_window_appearance(
        &mut self,
        handle: WindowHandle,
        appearance: Option<WindowAppearance>,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(handle, WindowCommand::SetAppearance(handle, appearance))
    }

    pub fn set_window_background_appearance(
        &mut self,
        handle: WindowHandle,
        appearance: WindowBackgroundAppearance,
    ) -> Result<(), WindowCommandError> {
        self.queue_window_command(
            handle,
            WindowCommand::SetBackgroundAppearance(handle, appearance),
        )
    }

    fn queue_window_command(
        &mut self,
        handle: WindowHandle,
        command: WindowCommand,
    ) -> Result<(), WindowCommandError> {
        self.ensure_window_command_target(handle)?;
        if self.runtime.window_commands.len() == MAX_PENDING_WINDOW_COMMANDS {
            return Err(WindowCommandError::QueueFull);
        }
        self.wake_for_external_command()?;
        self.runtime.window_commands.push(command);
        Ok(())
    }

    fn queue_platform_response(&mut self, request: PlatformRequest) -> Result<(), PlatformError> {
        self.queue_platform_request(request)
    }

    fn queue_platform_request(&mut self, request: PlatformRequest) -> Result<(), 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);
        }
        self.runtime
            .event_proxy
            .send_event(RuntimeEvent::ExternalCommandsReady)
            .map_err(|_| PlatformError::Unavailable)?;
        self.runtime.platform_requests.push_back(request);
        Ok(())
    }

    fn ensure_window_command_target(&self, handle: WindowHandle) -> Result<(), WindowCommandError> {
        if !matches!(self.status, AppRunStatus::Continue)
            || !(self.runtime.window_handles.contains_key(&handle)
                || self.runtime.current_handle() == Some(handle))
        {
            Err(WindowCommandError::Unavailable)
        } else {
            Ok(())
        }
    }

    fn wake_for_external_command(&self) -> Result<(), WindowCommandError> {
        self.runtime
            .event_proxy
            .send_event(RuntimeEvent::ExternalCommandsReady)
            .map_err(|_| WindowCommandError::Unavailable)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn external_window_commands_keep_public_validation() {
        assert_eq!(
            validate_window_title(&"x".repeat(MAX_WINDOW_TITLE_BYTES + 1)),
            Err(WindowCommandError::TitleTooLong)
        );
        assert_eq!(
            validate_window_document_path(Path::new("")),
            Err(WindowCommandError::InvalidDocumentPath)
        );
    }
}