Skip to main content

gpui/
app.rs

1use scheduler::Instant;
2use std::{
3    any::{TypeId, type_name},
4    cell::{BorrowMutError, Cell, Ref, RefCell, RefMut},
5    marker::PhantomData,
6    mem,
7    ops::{Deref, DerefMut},
8    path::{Path, PathBuf},
9    rc::{Rc, Weak},
10    sync::{Arc, atomic::Ordering::SeqCst},
11    time::Duration,
12};
13
14use anyhow::{Context as _, Result, anyhow};
15use derive_more::{Deref, DerefMut};
16use futures::{
17    Future, FutureExt,
18    channel::oneshot,
19    future::{LocalBoxFuture, Shared},
20};
21use parking_lot::RwLock;
22use slotmap::SlotMap;
23
24pub use async_context::*;
25#[cfg(feature = "bench")]
26pub use bench_context::{BenchAppContext, BenchReport, BenchWindowContext, bench_platform};
27use collections::{FxHashMap, FxHashSet, HashMap, TypeIdHashMap, TypeIdHashSet, VecDeque};
28pub use context::*;
29pub use entity_map::*;
30use gpui_util::{ResultExt, debug_panic};
31#[cfg(any(test, feature = "test-support"))]
32pub use headless_app_context::*;
33use http_client::{HttpClient, Url};
34use smallvec::SmallVec;
35#[cfg(any(test, feature = "test-support"))]
36pub use test_app::*;
37#[cfg(any(test, feature = "test-support"))]
38pub use test_context::*;
39#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
40pub use visual_test_context::*;
41
42#[cfg(any(feature = "inspector", debug_assertions))]
43use crate::InspectorElementRegistry;
44use crate::{
45    Action, ActionBuildError, ActionRegistry, Any, AnyView, AnyWindowHandle, AppContext, Arena,
46    ArenaBox, Asset, AssetSource, BackgroundExecutor, Bounds, ClipboardItem, CursorStyle,
47    DispatchPhase, DisplayId, EventEmitter, ExternalDragPayload, FocusHandle, FocusMap,
48    ForegroundExecutor, Global, KeyBinding, KeyContext, Keymap, Keystroke, LayoutId, Menu,
49    MenuItem, OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay,
50    PlatformKeyboardLayout, PlatformKeyboardMapper, Point, Priority, PromptBuilder, PromptButton,
51    PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation,
52    ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer,
53    SystemNotification, SystemNotificationResponse, Task, TextRenderingMode, TextSystem,
54    ThermalState, Window, WindowAppearance, WindowButtonLayout, WindowHandle, WindowId,
55    WindowInvalidator,
56    colors::{Colors, GlobalColors},
57    hash, init_app_menus,
58};
59
60mod async_context;
61#[cfg(feature = "bench")]
62mod bench_context;
63mod context;
64mod entity_map;
65#[cfg(any(test, feature = "test-support"))]
66mod headless_app_context;
67#[cfg(any(test, feature = "test-support"))]
68mod test_app;
69#[cfg(any(test, feature = "test-support"))]
70mod test_context;
71#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
72mod visual_test_context;
73
74/// The duration for which futures returned from [Context::on_app_quit] can run before the application fully quits.
75pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(200);
76
77/// Temporary(?) wrapper around [`RefCell<App>`] to help us debug any double borrows.
78/// Strongly consider removing after stabilization.
79#[doc(hidden)]
80pub struct AppCell {
81    app: RefCell<App>,
82}
83
84impl AppCell {
85    #[doc(hidden)]
86    #[track_caller]
87    pub fn borrow(&self) -> AppRef<'_> {
88        if option_env!("TRACK_THREAD_BORROWS").is_some() {
89            let thread_id = std::thread::current().id();
90            eprintln!("borrowed {thread_id:?}");
91        }
92        AppRef(self.app.borrow())
93    }
94
95    #[doc(hidden)]
96    #[track_caller]
97    pub fn borrow_mut(&self) -> AppRefMut<'_> {
98        if option_env!("TRACK_THREAD_BORROWS").is_some() {
99            let thread_id = std::thread::current().id();
100            eprintln!("borrowed {thread_id:?}");
101        }
102        AppRefMut(self.app.borrow_mut())
103    }
104
105    #[doc(hidden)]
106    #[track_caller]
107    pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>, BorrowMutError> {
108        if option_env!("TRACK_THREAD_BORROWS").is_some() {
109            let thread_id = std::thread::current().id();
110            eprintln!("borrowed {thread_id:?}");
111        }
112        Ok(AppRefMut(self.app.try_borrow_mut()?))
113    }
114}
115
116#[doc(hidden)]
117#[derive(Deref, DerefMut)]
118pub struct AppRef<'a>(Ref<'a, App>);
119
120impl Drop for AppRef<'_> {
121    fn drop(&mut self) {
122        if option_env!("TRACK_THREAD_BORROWS").is_some() {
123            let thread_id = std::thread::current().id();
124            eprintln!("dropped borrow from {thread_id:?}");
125        }
126    }
127}
128
129#[doc(hidden)]
130#[derive(Deref, DerefMut)]
131pub struct AppRefMut<'a>(RefMut<'a, App>);
132
133impl Drop for AppRefMut<'_> {
134    fn drop(&mut self) {
135        if option_env!("TRACK_THREAD_BORROWS").is_some() {
136            let thread_id = std::thread::current().id();
137            eprintln!("dropped {thread_id:?}");
138        }
139    }
140}
141
142/// A reference to a GPUI application, typically constructed in the `main` function of your app.
143/// You won't interact with this type much outside of initial configuration and startup.
144pub struct Application(Rc<AppCell>);
145
146/// A strong handle to an [`Application`] started with [`Application::run_embedded`].
147///
148/// Dropping this handle releases the app, so an embedder must hold it for as long as the
149/// app should run. While held, it is the embedder's entry point back into GPUI each time
150/// the external run loop gives it control.
151pub struct ApplicationHandle {
152    app: Rc<AppCell>,
153}
154
155impl ApplicationHandle {
156    /// Invoke `f` with the app context. Must not be called re-entrantly from code that
157    /// is already inside an update; the app state is a `RefCell` and will panic on a
158    /// double borrow.
159    pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
160        let cx = &mut *self.app.borrow_mut();
161        f(cx)
162    }
163
164    /// An [`AsyncApp`] for use across await points. It holds the app weakly; keeping the
165    /// app alive remains this handle's job.
166    pub fn to_async(&self) -> AsyncApp {
167        self.update(|cx| cx.to_async())
168    }
169}
170
171/// Represents an application before it is fully launched. Once your app is
172/// configured, you'll start the app with `App::run`.
173impl Application {
174    /// Builds an app with a caller-provided platform implementation.
175    pub fn with_platform(platform: Rc<dyn Platform>) -> Self {
176        Self(App::new_app(
177            platform,
178            Arc::new(()),
179            Arc::new(NullHttpClient),
180        ))
181    }
182
183    /// Builds an app with accessibility (AccessKit) integration forcibly
184    /// disabled.
185    ///
186    /// In this mode, accessibility APIs (e.g.
187    /// [`div().role()`][crate::StatefulInteractiveElement::role]) silently
188    /// no-op.
189    ///
190    /// See the [accessibility guide](crate::_accessibility) for an overview of
191    /// the features this disables.
192    pub fn new_inaccessible(platform: Rc<dyn Platform>) -> Self {
193        let this = Self::with_platform(platform);
194        this.0.borrow_mut().accessibility_force_disabled = true;
195        this
196    }
197
198    /// Assigns the source of assets for the application.
199    pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
200        let mut context_lock = self.0.borrow_mut();
201        let asset_source = Arc::new(asset_source);
202        context_lock.asset_source = asset_source.clone();
203        context_lock.svg_renderer = SvgRenderer::new(asset_source);
204        drop(context_lock);
205        self
206    }
207
208    /// Sets the HTTP client for the application.
209    pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
210        let mut context_lock = self.0.borrow_mut();
211        context_lock.http_client = http_client;
212        drop(context_lock);
213        self
214    }
215
216    /// Configures when the application should automatically quit.
217    /// By default, [`QuitMode::Default`] is used.
218    pub fn with_quit_mode(self, mode: QuitMode) -> Self {
219        self.0.borrow_mut().quit_mode = mode;
220        self
221    }
222
223    /// Start the application. The provided callback will be called once the
224    /// app is fully launched.
225    pub fn run<F>(self, on_finish_launching: F)
226    where
227        F: 'static + FnOnce(&mut App),
228    {
229        let this = self.0.clone();
230        let platform = self.0.borrow().platform.clone();
231        platform.run(Box::new(move || {
232            let cx = &mut *this.borrow_mut();
233            on_finish_launching(cx);
234        }));
235    }
236
237    /// Start the application for an embedder that drives the run loop itself.
238    ///
239    /// On ordinary platforms `Platform::run` blocks for the lifetime of the app, and the
240    /// app state is kept alive by [`Application::run`]'s stack frame. Embedded platforms —
241    /// where the run loop belongs to someone else, e.g. GPUI compiled into a Wasm guest,
242    /// or a GPUI view hosted inside a foreign native application — implement
243    /// `Platform::run` to invoke the launch callback and return immediately. This method
244    /// supports that shape: it returns an [`ApplicationHandle`] that keeps the app alive
245    /// and lets the embedder re-enter it whenever the external run loop yields control.
246    pub fn run_embedded<F>(self, on_finish_launching: F) -> ApplicationHandle
247    where
248        F: 'static + FnOnce(&mut App),
249    {
250        let this = self.0.clone();
251        let platform = self.0.borrow().platform.clone();
252        platform.run(Box::new(move || {
253            let cx = &mut *this.borrow_mut();
254            on_finish_launching(cx);
255        }));
256        ApplicationHandle { app: self.0 }
257    }
258
259    /// Register a handler to be invoked when the platform instructs the application
260    /// to open one or more URLs.
261    pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
262    where
263        F: 'static + FnMut(Vec<String>),
264    {
265        self.0.borrow().platform.on_open_urls(Box::new(callback));
266        self
267    }
268
269    /// Invokes a handler when an already-running application is launched.
270    /// On macOS, this can occur when the application icon is double-clicked or the app is launched via the dock.
271    pub fn on_reopen<F>(&self, mut callback: F) -> &Self
272    where
273        F: 'static + FnMut(&mut App),
274    {
275        let this = Rc::downgrade(&self.0);
276        self.0.borrow_mut().platform.on_reopen(Box::new(move || {
277            if let Some(app) = this.upgrade() {
278                callback(&mut app.borrow_mut());
279            }
280        }));
281        self
282    }
283
284    /// Invokes a handler when the system wakes from sleep.
285    pub fn on_system_wake<F>(&self, mut callback: F) -> &Self
286    where
287        F: 'static + FnMut(&mut App),
288    {
289        let this = Rc::downgrade(&self.0);
290        self.0
291            .borrow_mut()
292            .platform
293            .on_system_wake(Box::new(move || {
294                if let Some(app) = this.upgrade() {
295                    callback(&mut app.borrow_mut());
296                }
297            }));
298        self
299    }
300
301    /// Returns a handle to the [`BackgroundExecutor`] associated with this app, which can be used to spawn futures in the background.
302    pub fn background_executor(&self) -> BackgroundExecutor {
303        self.0.borrow().background_executor.clone()
304    }
305
306    /// Returns a handle to the [`ForegroundExecutor`] associated with this app, which can be used to spawn futures in the foreground.
307    pub fn foreground_executor(&self) -> ForegroundExecutor {
308        self.0.borrow().foreground_executor.clone()
309    }
310
311    /// Returns a reference to the [`TextSystem`] associated with this app.
312    pub fn text_system(&self) -> Arc<TextSystem> {
313        self.0.borrow().text_system.clone()
314    }
315
316    /// Returns the file URL of the executable with the specified name in the application bundle
317    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
318        self.0.borrow().path_for_auxiliary_executable(name)
319    }
320}
321
322type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
323type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
324pub(crate) type KeystrokeObserver =
325    Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
326type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
327type WindowClosedHandler = Box<dyn FnMut(&mut App, WindowId)>;
328type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
329type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
330
331/// Defines when the application should automatically quit.
332#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
333pub enum QuitMode {
334    /// Use [`QuitMode::Explicit`] on macOS and [`QuitMode::LastWindowClosed`] on other platforms.
335    #[default]
336    Default,
337    /// Quit automatically when the last window is closed.
338    LastWindowClosed,
339    /// Quit only when requested via [`App::quit`].
340    Explicit,
341}
342
343/// Controls when GPUI hides the mouse cursor in response to keyboard input.
344///
345/// Restoration on mouse motion is handled by the platform layer; this enum
346/// only describes the policy for *triggering* a hide.
347#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
348pub enum CursorHideMode {
349    /// Never hide the cursor automatically.
350    Never,
351    /// Hide on character-producing key presses (typing).
352    OnTyping,
353    /// Hide on character-producing key presses, *and* when a key binding
354    /// resolves to an action that consumes the keystroke.
355    #[default]
356    OnTypingAndAction,
357}
358
359#[doc(hidden)]
360#[derive(Clone, PartialEq, Eq)]
361pub struct SystemWindowTab {
362    pub id: WindowId,
363    pub title: SharedString,
364    pub handle: AnyWindowHandle,
365    pub last_active_at: Instant,
366}
367
368impl SystemWindowTab {
369    /// Create a new instance of the window tab.
370    pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self {
371        Self {
372            id: handle.id,
373            title,
374            handle,
375            last_active_at: Instant::now(),
376        }
377    }
378}
379
380/// A controller for managing window tabs.
381#[derive(Default)]
382pub struct SystemWindowTabController {
383    visible: Option<bool>,
384    tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
385}
386
387impl Global for SystemWindowTabController {}
388
389impl SystemWindowTabController {
390    /// Create a new instance of the window tab controller.
391    pub fn new() -> Self {
392        Self {
393            visible: None,
394            tab_groups: FxHashMap::default(),
395        }
396    }
397
398    /// Initialize the global window tab controller.
399    pub fn init(cx: &mut App) {
400        cx.set_global(SystemWindowTabController::new());
401    }
402
403    /// Get all tab groups.
404    pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
405        &self.tab_groups
406    }
407
408    /// Get the next tab group window handle.
409    pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
410        let controller = cx.global::<SystemWindowTabController>();
411        let current_group = controller
412            .tab_groups
413            .iter()
414            .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
415
416        let current_group = current_group?;
417        let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
418        group_ids.sort_unstable();
419        let idx = group_ids.iter().position(|g| *g == current_group)?;
420        let next_idx = (idx + 1) % group_ids.len();
421
422        controller
423            .tab_groups
424            .get(group_ids[next_idx])
425            .and_then(|tabs| {
426                tabs.iter()
427                    .max_by_key(|tab| tab.last_active_at)
428                    .or_else(|| tabs.first())
429                    .map(|tab| &tab.handle)
430            })
431    }
432
433    /// Get the previous tab group window handle.
434    pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
435        let controller = cx.global::<SystemWindowTabController>();
436        let current_group = controller
437            .tab_groups
438            .iter()
439            .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
440
441        let current_group = current_group?;
442        let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
443        group_ids.sort_unstable();
444        let idx = group_ids.iter().position(|g| *g == current_group)?;
445        let prev_idx = if idx == 0 {
446            group_ids.len() - 1
447        } else {
448            idx - 1
449        };
450
451        controller
452            .tab_groups
453            .get(group_ids[prev_idx])
454            .and_then(|tabs| {
455                tabs.iter()
456                    .max_by_key(|tab| tab.last_active_at)
457                    .or_else(|| tabs.first())
458                    .map(|tab| &tab.handle)
459            })
460    }
461
462    /// Get all tabs in the same window.
463    pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
464        self.tab_groups
465            .values()
466            .find(|tabs| tabs.iter().any(|tab| tab.id == id))
467    }
468
469    /// Initialize the visibility of the system window tab controller.
470    pub fn init_visible(cx: &mut App, visible: bool) {
471        let mut controller = cx.global_mut::<SystemWindowTabController>();
472        if controller.visible.is_none() {
473            controller.visible = Some(visible);
474        }
475    }
476
477    /// Get the visibility of the system window tab controller.
478    pub fn is_visible(&self) -> bool {
479        self.visible.unwrap_or(false)
480    }
481
482    /// Set the visibility of the system window tab controller.
483    pub fn set_visible(cx: &mut App, visible: bool) {
484        let mut controller = cx.global_mut::<SystemWindowTabController>();
485        controller.visible = Some(visible);
486    }
487
488    /// Update the last active of a window.
489    pub fn update_last_active(cx: &mut App, id: WindowId) {
490        let mut controller = cx.global_mut::<SystemWindowTabController>();
491        for windows in controller.tab_groups.values_mut() {
492            for tab in windows.iter_mut() {
493                if tab.id == id {
494                    tab.last_active_at = Instant::now();
495                }
496            }
497        }
498    }
499
500    /// Update the position of a tab within its group.
501    pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
502        let mut controller = cx.global_mut::<SystemWindowTabController>();
503        for (_, windows) in controller.tab_groups.iter_mut() {
504            if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
505                if ix < windows.len() && current_pos != ix {
506                    let window_tab = windows.remove(current_pos);
507                    windows.insert(ix, window_tab);
508                }
509                break;
510            }
511        }
512    }
513
514    /// Update the title of a tab.
515    pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
516        let controller = cx.global::<SystemWindowTabController>();
517        let tab = controller
518            .tab_groups
519            .values()
520            .flat_map(|windows| windows.iter())
521            .find(|tab| tab.id == id);
522
523        if tab.map_or(true, |t| t.title == title) {
524            return;
525        }
526
527        let mut controller = cx.global_mut::<SystemWindowTabController>();
528        for windows in controller.tab_groups.values_mut() {
529            for tab in windows.iter_mut() {
530                if tab.id == id {
531                    tab.title = title;
532                    return;
533                }
534            }
535        }
536    }
537
538    fn next_group_id(&self) -> usize {
539        self.tab_groups
540            .keys()
541            .max()
542            .map_or(Some(0), |id| id.checked_add(1))
543            .unwrap_or_else(|| (0..).find(|id| !self.tab_groups.contains_key(id)).unwrap())
544    }
545
546    /// Reconcile a native tab group snapshot, preserving its tab order.
547    pub fn add_tab(cx: &mut App, id: WindowId, mut tabs: Vec<SystemWindowTab>) {
548        if !tabs.iter().any(|tab| tab.id == id) {
549            return;
550        }
551        let controller = cx.global_mut::<SystemWindowTabController>();
552        let mut incoming_ids = FxHashSet::default();
553        tabs.retain(|tab| incoming_ids.insert(tab.id));
554        let previous_activity: FxHashMap<_, _> = controller
555            .tab_groups
556            .values()
557            .flatten()
558            .map(|tab| (tab.id, tab.last_active_at))
559            .collect();
560        for tab in &mut tabs {
561            if let Some(previous) = previous_activity.get(&tab.id) {
562                tab.last_active_at = *previous;
563            }
564        }
565
566        // Reuse a complete group or the group this tab has just joined. A partial
567        // overlap needs a new group so that unreported tabs keep their own group.
568        let group_id = controller
569            .tab_groups
570            .iter()
571            .filter(|(_, group)| {
572                let ids: FxHashSet<_> = group.iter().map(|tab| tab.id).collect();
573                ids == incoming_ids
574                    || (ids.len() + 1 == incoming_ids.len()
575                        && !ids.contains(&id)
576                        && ids.is_subset(&incoming_ids))
577            })
578            .map(|(id, _)| *id)
579            .min()
580            .unwrap_or_else(|| controller.next_group_id());
581
582        controller.tab_groups.retain(|_, group| {
583            group.retain(|tab| !incoming_ids.contains(&tab.id));
584            !group.is_empty()
585        });
586        controller.tab_groups.insert(group_id, tabs);
587    }
588
589    /// Remove a tab from a tab group.
590    pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
591        let mut controller = cx.global_mut::<SystemWindowTabController>();
592        let mut removed_tab = None;
593
594        controller.tab_groups.retain(|_, tabs| {
595            if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
596                removed_tab = Some(tabs.remove(pos));
597            }
598            !tabs.is_empty()
599        });
600
601        removed_tab
602    }
603
604    /// Move a tab to a new tab group.
605    pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
606        let mut removed_tab = Self::remove_tab(cx, id);
607        let mut controller = cx.global_mut::<SystemWindowTabController>();
608
609        if let Some(tab) = removed_tab {
610            let new_group_id = controller.next_group_id();
611            controller.tab_groups.insert(new_group_id, vec![tab]);
612        }
613    }
614
615    /// Merge all tab groups into a single group.
616    pub fn merge_all_windows(cx: &mut App, id: WindowId) {
617        let mut controller = cx.global_mut::<SystemWindowTabController>();
618        let Some(initial_tabs) = controller.tabs(id) else {
619            return;
620        };
621
622        let mut all_tabs = initial_tabs.clone();
623        let mut seen: FxHashSet<_> = all_tabs.iter().map(|tab| tab.id).collect();
624        let mut groups: Vec<_> = controller.tab_groups.drain().collect();
625        groups.sort_unstable_by_key(|(id, _)| *id);
626        for (_, tabs) in groups {
627            all_tabs.extend(tabs.into_iter().filter(|tab| seen.insert(tab.id)));
628        }
629
630        controller.tab_groups.insert(0, all_tabs);
631    }
632
633    /// Selects the next tab in the tab group in the trailing direction.
634    pub fn select_next_tab(cx: &mut App, id: WindowId) {
635        let mut controller = cx.global_mut::<SystemWindowTabController>();
636        let Some(tabs) = controller.tabs(id) else {
637            return;
638        };
639
640        let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
641        let next_index = (current_index + 1) % tabs.len();
642
643        let _ = &tabs[next_index].handle.update(cx, |_, window, _| {
644            window.activate_window();
645        });
646    }
647
648    /// Selects the previous tab in the tab group in the leading direction.
649    pub fn select_previous_tab(cx: &mut App, id: WindowId) {
650        let mut controller = cx.global_mut::<SystemWindowTabController>();
651        let Some(tabs) = controller.tabs(id) else {
652            return;
653        };
654
655        let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
656        let previous_index = if current_index == 0 {
657            tabs.len() - 1
658        } else {
659            current_index - 1
660        };
661
662        let _ = &tabs[previous_index].handle.update(cx, |_, window, _| {
663            window.activate_window();
664        });
665    }
666}
667
668pub(crate) enum GpuiMode {
669    #[cfg(any(test, feature = "test-support"))]
670    Test {
671        skip_drawing: bool,
672    },
673    Production,
674}
675
676impl GpuiMode {
677    #[cfg(any(test, feature = "test-support"))]
678    pub fn test() -> Self {
679        GpuiMode::Test {
680            skip_drawing: false,
681        }
682    }
683
684    #[inline]
685    pub(crate) fn skip_drawing(&self) -> bool {
686        match self {
687            #[cfg(any(test, feature = "test-support"))]
688            GpuiMode::Test { skip_drawing } => *skip_drawing,
689            GpuiMode::Production => false,
690        }
691    }
692}
693
694struct PlatformOwnedDrag {
695    source_window: WindowId,
696    state: PlatformOwnedDragState,
697}
698
699enum PlatformOwnedDragState {
700    Suspended(AnyDrag),
701    // A source-window drop consumes `active_drag` before AppKit ends the dragging session, so this
702    // marker can outlive the active drag and is cleaned up by `FileDropEvent::Ended`.
703    RestoredInSourceWindow,
704}
705
706/// Contains the state of the full application, and passed as a reference to a variety of callbacks.
707/// Other [Context] derefs to this type.
708/// You need a reference to an `App` to access the state of a [Entity].
709pub struct App {
710    pub(crate) this: Weak<AppCell>,
711    pub(crate) platform: Rc<dyn Platform>,
712    text_system: Arc<TextSystem>,
713
714    pub(crate) actions: Rc<ActionRegistry>,
715    pub(crate) active_drag: Option<AnyDrag>,
716    platform_owned_drag: Option<PlatformOwnedDrag>,
717    pub(crate) background_executor: BackgroundExecutor,
718    pub(crate) foreground_executor: ForegroundExecutor,
719    pub(crate) entities: EntityMap,
720    pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
721    pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
722    pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
723    pub(crate) focus_handles: Arc<FocusMap>,
724    pub(crate) keymap: Rc<RefCell<Keymap>>,
725    pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
726    pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
727    pub(crate) global_action_listeners:
728        TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
729    pending_effects: VecDeque<Effect>,
730
731    pub(crate) observers: SubscriberSet<EntityId, Handler>,
732    pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
733    pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
734    pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
735    pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
736    pub(crate) thermal_state_observers: SubscriberSet<(), Handler>,
737    pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
738    pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
739    pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
740    pub(crate) restart_observers: SubscriberSet<(), Handler>,
741    pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
742
743    /// Per-App element arena. This isolates element allocations between different
744    /// App instances (important for tests where multiple Apps run concurrently).
745    ///
746    /// Kept in its own allocation because draws reach it through a raw pointer
747    /// (`CURRENT_ELEMENT_ARENA`) while a `&mut App` is live. If it were stored
748    /// inline, those accesses would alias memory the `&mut App` claims
749    /// exclusively, which is undefined behavior.
750    pub(crate) element_arena: Rc<RefCell<Arena>>,
751    /// Per-App event arena.
752    pub(crate) event_arena: Arena,
753
754    // Drop globals last. We need to ensure all tasks owned by entities and
755    // callbacks are marked cancelled at this point as this will also shutdown
756    // the tokio runtime. As any task attempting to spawn a blocking tokio task,
757    // might panic.
758    pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
759
760    // assets
761    pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
762    asset_source: Arc<dyn AssetSource>,
763    pub(crate) svg_renderer: SvgRenderer,
764    http_client: Arc<dyn HttpClient>,
765
766    // below is plain data, the drop order is insignificant here
767    pub(crate) pending_notifications: FxHashSet<EntityId>,
768    pub(crate) pending_global_notifications: TypeIdHashSet,
769    pub(crate) restart_path: Option<PathBuf>,
770    pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
771    pub(crate) propagate_event: bool,
772    pub(crate) prompt_builder: Option<PromptBuilder>,
773    pub(crate) window_invalidators_by_entity:
774        FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
775    pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
776    pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
777    #[cfg(any(feature = "inspector", debug_assertions))]
778    pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
779    #[cfg(any(feature = "inspector", debug_assertions))]
780    pub(crate) inspector_element_registry: InspectorElementRegistry,
781    #[cfg(any(test, feature = "test-support", debug_assertions))]
782    pub(crate) name: Option<&'static str>,
783    pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
784
785    pub(crate) window_update_stack: Vec<WindowId>,
786    pub(crate) mode: GpuiMode,
787    pub(crate) cursor_hide_mode: CursorHideMode,
788    pub(crate) reduce_motion: bool,
789    /// Whether the app was created by [`Application::new_inaccessible`]. No
790    /// accesskit APIs will be called when this flag is set.
791    pub(crate) accessibility_force_disabled: bool,
792    flushing_effects: bool,
793    pending_updates: usize,
794    quit_mode: QuitMode,
795    quitting: bool,
796
797    // We need to ensure the leak detector drops last, after all tasks, callbacks and things have been dropped.
798    // Otherwise it may report false positives.
799    #[cfg(any(test, feature = "leak-detection"))]
800    _ref_counts: Arc<RwLock<EntityRefCounts>>,
801}
802
803impl App {
804    #[allow(clippy::new_ret_no_self)]
805    pub(crate) fn new_app(
806        platform: Rc<dyn Platform>,
807        asset_source: Arc<dyn AssetSource>,
808        http_client: Arc<dyn HttpClient>,
809    ) -> Rc<AppCell> {
810        let background_executor = platform.background_executor();
811        let foreground_executor = platform.foreground_executor();
812        assert!(
813            background_executor.is_main_thread(),
814            "must construct App on main thread"
815        );
816
817        let text_system = Arc::new(TextSystem::new(platform.text_system()));
818        let entities = EntityMap::new();
819        let keyboard_layout = platform.keyboard_layout();
820        let keyboard_mapper = platform.keyboard_mapper();
821
822        #[cfg(any(test, feature = "leak-detection"))]
823        let _ref_counts = entities.ref_counts_drop_handle();
824
825        let app = Rc::new_cyclic(|this| AppCell {
826            app: RefCell::new(App {
827                this: this.clone(),
828                platform: platform.clone(),
829                text_system,
830                text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
831                mode: GpuiMode::Production,
832                actions: Rc::new(ActionRegistry::default()),
833                flushing_effects: false,
834                pending_updates: 0,
835                active_drag: None,
836                platform_owned_drag: None,
837                background_executor,
838                foreground_executor,
839                svg_renderer: SvgRenderer::new(asset_source.clone()),
840                loading_assets: Default::default(),
841                asset_source,
842                http_client,
843                globals_by_type: Default::default(),
844                entities,
845                new_entity_observers: SubscriberSet::new(),
846                windows: SlotMap::with_key(),
847                window_update_stack: Vec::new(),
848                window_handles: FxHashMap::default(),
849                focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
850                keymap: Rc::new(RefCell::new(Keymap::default())),
851                keyboard_layout,
852                keyboard_mapper,
853                global_action_listeners: Default::default(),
854                pending_effects: VecDeque::new(),
855                pending_notifications: FxHashSet::default(),
856                pending_global_notifications: Default::default(),
857                observers: SubscriberSet::new(),
858                tracked_entities: FxHashMap::default(),
859                window_invalidators_by_entity: FxHashMap::default(),
860                current_window_by_entity: FxHashMap::default(),
861                event_listeners: SubscriberSet::new(),
862                release_listeners: SubscriberSet::new(),
863                keystroke_observers: SubscriberSet::new(),
864                keystroke_interceptors: SubscriberSet::new(),
865                keyboard_layout_observers: SubscriberSet::new(),
866                thermal_state_observers: SubscriberSet::new(),
867                global_observers: SubscriberSet::new(),
868                quit_observers: SubscriberSet::new(),
869                restart_observers: SubscriberSet::new(),
870                restart_path: None,
871                window_closed_observers: SubscriberSet::new(),
872                layout_id_buffer: Default::default(),
873                propagate_event: true,
874                prompt_builder: Some(PromptBuilder::Default),
875                #[cfg(any(feature = "inspector", debug_assertions))]
876                inspector_renderer: None,
877                #[cfg(any(feature = "inspector", debug_assertions))]
878                inspector_element_registry: InspectorElementRegistry::default(),
879                quit_mode: QuitMode::default(),
880                quitting: false,
881                cursor_hide_mode: CursorHideMode::default(),
882                reduce_motion: false,
883                accessibility_force_disabled: false,
884
885                #[cfg(any(test, feature = "test-support", debug_assertions))]
886                name: None,
887                element_arena: Rc::new(RefCell::new(Arena::new(1024 * 1024))),
888                event_arena: Arena::new(1024 * 1024),
889
890                #[cfg(any(test, feature = "leak-detection"))]
891                _ref_counts,
892            }),
893        });
894
895        init_app_menus(platform.as_ref(), &app.borrow());
896        SystemWindowTabController::init(&mut app.borrow_mut());
897
898        platform.on_keyboard_layout_change(Box::new({
899            let app = Rc::downgrade(&app);
900            move || {
901                if let Some(app) = app.upgrade() {
902                    let cx = &mut app.borrow_mut();
903                    cx.keyboard_layout = cx.platform.keyboard_layout();
904                    cx.keyboard_mapper = cx.platform.keyboard_mapper();
905                    cx.keyboard_layout_observers
906                        .clone()
907                        .retain(&(), move |callback| (callback)(cx));
908                }
909            }
910        }));
911
912        platform.on_thermal_state_change(Box::new({
913            let app = Rc::downgrade(&app);
914            move || {
915                if let Some(app) = app.upgrade() {
916                    let cx = &mut app.borrow_mut();
917                    cx.thermal_state_observers
918                        .clone()
919                        .retain(&(), move |callback| (callback)(cx));
920                }
921            }
922        }));
923
924        platform.on_quit(Box::new({
925            let cx = Rc::downgrade(&app);
926            move || {
927                if let Some(cx) = cx.upgrade() {
928                    cx.borrow_mut().shutdown();
929                }
930            }
931        }));
932
933        app
934    }
935
936    #[doc(hidden)]
937    pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
938        self.entities.ref_counts_drop_handle()
939    }
940
941    /// Captures a snapshot of all entities that currently have alive handles.
942    ///
943    /// The returned [`LeakDetectorSnapshot`] can later be passed to
944    /// [`assert_no_new_leaks`](Self::assert_no_new_leaks) to verify that no
945    /// entities created after the snapshot are still alive.
946    #[cfg(any(test, feature = "leak-detection"))]
947    pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
948        self.entities.leak_detector_snapshot()
949    }
950
951    /// Asserts that no entities created after `snapshot` still have alive handles.
952    ///
953    /// Entities that were already tracked at the time of the snapshot are ignored,
954    /// even if they still have handles. Only *new* entities (those whose
955    /// `EntityId` was not present in the snapshot) are considered leaks.
956    ///
957    /// # Panics
958    ///
959    /// Panics if any new entity handles exist. The panic message lists every
960    /// leaked entity with its type name, and includes allocation-site backtraces
961    /// when `LEAK_BACKTRACE` is set.
962    #[cfg(any(test, feature = "leak-detection"))]
963    pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
964        self.entities.assert_no_new_leaks(snapshot)
965    }
966
967    /// Quit the application gracefully. Handlers registered with [`Context::on_app_quit`]
968    /// will be given `SHUTDOWN_TIMEOUT` to complete before exiting.
969    pub fn shutdown(&mut self) {
970        let mut futures = Vec::new();
971
972        for observer in self.quit_observers.remove(&()) {
973            futures.push(observer(self));
974        }
975
976        self.windows.clear();
977        self.window_handles.clear();
978        self.flush_effects();
979        self.quitting = true;
980
981        let futures = futures::future::join_all(futures);
982        if self
983            .foreground_executor
984            .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
985            .is_err()
986        {
987            log::error!("timed out waiting on app_will_quit");
988        }
989
990        self.quitting = false;
991    }
992
993    /// Get the id of the current keyboard layout
994    pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
995        self.keyboard_layout.as_ref()
996    }
997
998    /// Get the current keyboard mapper.
999    pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
1000        &self.keyboard_mapper
1001    }
1002
1003    /// Invokes a handler when the current keyboard layout changes
1004    pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
1005    where
1006        F: 'static + FnMut(&mut App),
1007    {
1008        let (subscription, activate) = self.keyboard_layout_observers.insert(
1009            (),
1010            Box::new(move |cx| {
1011                callback(cx);
1012                true
1013            }),
1014        );
1015        activate();
1016        subscription
1017    }
1018
1019    /// Gracefully quit the application via the platform's standard routine.
1020    pub fn quit(&self) {
1021        self.platform.quit();
1022    }
1023
1024    /// Returns the current policy for hiding the cursor in response to
1025    /// keyboard input.
1026    pub fn cursor_hide_mode(&self) -> CursorHideMode {
1027        self.cursor_hide_mode
1028    }
1029
1030    /// Sets the policy controlling when GPUI hides the cursor in response
1031    /// to keyboard input.
1032    pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1033        self.cursor_hide_mode = mode;
1034    }
1035
1036    /// Returns whether the cursor is currently visible according to the
1037    /// platform. This will report `false` after a keyboard input has hidden
1038    /// the cursor and the user has not yet moved the mouse to restore it.
1039    ///
1040    /// See [`App::set_cursor_hide_mode`].
1041    pub fn is_cursor_visible(&self) -> bool {
1042        self.platform.is_cursor_visible()
1043    }
1044
1045    /// Returns whether non-essential animations (e.g. loading spinners) should
1046    /// be rendered in a static state instead of animating.
1047    pub fn reduce_motion(&self) -> bool {
1048        self.reduce_motion
1049    }
1050
1051    /// Sets whether non-essential animations (e.g. loading spinners) should be
1052    /// rendered in a static state instead of animating.
1053    pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1054        if self.reduce_motion != reduce_motion {
1055            self.reduce_motion = reduce_motion;
1056            self.refresh_windows();
1057        }
1058    }
1059
1060    /// Schedules all windows in the application to be redrawn. This can be called
1061    /// multiple times in an update cycle and still result in a single redraw.
1062    pub fn refresh_windows(&mut self) {
1063        self.pending_effects.push_back(Effect::RefreshWindows);
1064    }
1065
1066    pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1067        self.start_update();
1068        let result = update(self);
1069        self.finish_update();
1070        result
1071    }
1072
1073    pub(crate) fn start_update(&mut self) {
1074        self.pending_updates += 1;
1075    }
1076
1077    pub(crate) fn finish_update(&mut self) {
1078        if !self.flushing_effects && self.pending_updates == 1 {
1079            self.flushing_effects = true;
1080            self.flush_effects();
1081            self.flushing_effects = false;
1082        }
1083        self.pending_updates -= 1;
1084    }
1085
1086    /// Arrange a callback to be invoked when the given entity calls `notify` on its respective context.
1087    pub fn observe<W>(
1088        &mut self,
1089        entity: &Entity<W>,
1090        mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1091    ) -> Subscription
1092    where
1093        W: 'static,
1094    {
1095        self.observe_internal(entity, move |e, cx| {
1096            on_notify(e, cx);
1097            true
1098        })
1099    }
1100
1101    pub(crate) fn detect_accessed_entities<R>(
1102        &mut self,
1103        callback: impl FnOnce(&mut App) -> R,
1104    ) -> (R, FxHashSet<EntityId>) {
1105        let accessed_entities_start = self.entities.accessed_entities.get_mut().clone();
1106        let result = callback(self);
1107        let entities_accessed_in_callback = self
1108            .entities
1109            .accessed_entities
1110            .get_mut()
1111            .difference(&accessed_entities_start)
1112            .copied()
1113            .collect::<FxHashSet<EntityId>>();
1114        (result, entities_accessed_in_callback)
1115    }
1116
1117    pub(crate) fn record_entities_accessed(
1118        &mut self,
1119        window_handle: AnyWindowHandle,
1120        invalidator: WindowInvalidator,
1121        entities: &FxHashSet<EntityId>,
1122    ) {
1123        let mut tracked_entities =
1124            std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1125        for entity in tracked_entities.iter() {
1126            self.window_invalidators_by_entity
1127                .entry(*entity)
1128                .and_modify(|windows| {
1129                    windows.remove(&window_handle.id);
1130                });
1131        }
1132        for entity in entities.iter() {
1133            self.window_invalidators_by_entity
1134                .entry(*entity)
1135                .or_default()
1136                .insert(window_handle.id, invalidator.clone());
1137            self.current_window_by_entity
1138                .insert(*entity, window_handle.id);
1139        }
1140        tracked_entities.clear();
1141        tracked_entities.extend(entities.iter().copied());
1142        self.tracked_entities
1143            .insert(window_handle.id, tracked_entities);
1144    }
1145
1146    pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1147        let (subscription, activate) = self.observers.insert(key, value);
1148        self.defer(move |_| activate());
1149        subscription
1150    }
1151
1152    pub(crate) fn observe_internal<W>(
1153        &mut self,
1154        entity: &Entity<W>,
1155        mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1156    ) -> Subscription
1157    where
1158        W: 'static,
1159    {
1160        let entity_id = entity.entity_id();
1161        let handle = entity.downgrade();
1162        self.new_observer(
1163            entity_id,
1164            Box::new(move |cx| {
1165                if let Some(entity) = handle.upgrade() {
1166                    on_notify(entity, cx)
1167                } else {
1168                    false
1169                }
1170            }),
1171        )
1172    }
1173
1174    /// Arrange for the given callback to be invoked whenever the given entity emits an event of a given type.
1175    /// The callback is provided a handle to the emitting entity and a reference to the emitted event.
1176    pub fn subscribe<T, Event>(
1177        &mut self,
1178        entity: &Entity<T>,
1179        mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1180    ) -> Subscription
1181    where
1182        T: 'static + EventEmitter<Event>,
1183        Event: 'static,
1184    {
1185        self.subscribe_internal(entity, move |entity, event, cx| {
1186            on_event(entity, event, cx);
1187            true
1188        })
1189    }
1190
1191    pub(crate) fn new_subscription(
1192        &mut self,
1193        key: EntityId,
1194        value: (TypeId, Listener),
1195    ) -> Subscription {
1196        let (subscription, activate) = self.event_listeners.insert(key, value);
1197        self.defer(move |_| activate());
1198        subscription
1199    }
1200    pub(crate) fn subscribe_internal<T, Evt>(
1201        &mut self,
1202        entity: &Entity<T>,
1203        mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1204    ) -> Subscription
1205    where
1206        T: 'static + EventEmitter<Evt>,
1207        Evt: 'static,
1208    {
1209        let entity_id = entity.entity_id();
1210        let handle = entity.downgrade();
1211        self.new_subscription(
1212            entity_id,
1213            (
1214                TypeId::of::<Evt>(),
1215                Box::new(move |event, cx| {
1216                    let event: &Evt = event.downcast_ref().expect("invalid event type");
1217                    if let Some(entity) = handle.upgrade() {
1218                        on_event(entity, event, cx)
1219                    } else {
1220                        false
1221                    }
1222                }),
1223            ),
1224        )
1225    }
1226
1227    /// Returns handles to all open windows in the application.
1228    /// Each handle could be downcast to a handle typed for the root view of that window.
1229    /// To find all windows of a given type, you could filter on
1230    pub fn windows(&self) -> Vec<AnyWindowHandle> {
1231        self.windows
1232            .keys()
1233            .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1234            .collect()
1235    }
1236
1237    /// Returns the window handles ordered by their appearance on screen, front to back.
1238    ///
1239    /// The first window in the returned list is the active/topmost window of the application.
1240    ///
1241    /// This method returns None if the platform doesn't implement the method yet.
1242    pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1243        self.platform.window_stack()
1244    }
1245
1246    /// Returns a handle to the window that is currently focused at the platform level, if one exists.
1247    pub fn active_window(&self) -> Option<AnyWindowHandle> {
1248        self.platform.active_window()
1249    }
1250
1251    /// Opens a new window with the given option and the root view returned by the given function.
1252    /// The function is invoked with a `Window`, which can be used to interact with window-specific
1253    /// functionality.
1254    pub fn open_window<V: 'static + Render>(
1255        &mut self,
1256        options: crate::WindowOptions,
1257        build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1258    ) -> anyhow::Result<WindowHandle<V>> {
1259        self.update(|cx| {
1260            let id = cx.windows.insert(None);
1261            let handle = WindowHandle::new(id);
1262            match Window::new(handle.into(), options, cx) {
1263                Ok(mut window) => {
1264                    cx.window_update_stack.push(id);
1265                    let root_view = build_root_view(&mut window, cx);
1266                    cx.window_update_stack.pop();
1267                    window.root.replace(root_view.into());
1268                    window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1269
1270                    // allow a window to draw at least once before returning
1271                    // this didn't cause any issues on non windows platforms as it seems we always won the race to on_request_frame
1272                    // on windows we quite frequently lose the race and return a window that has never rendered, which leads to a crash
1273                    // where DispatchTree::root_node_id asserts on empty nodes
1274                    let clear = window.draw(cx);
1275                    clear.clear(cx);
1276
1277                    cx.window_handles.insert(id, window.handle);
1278                    cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1279                    Ok(handle)
1280                }
1281                Err(e) => {
1282                    cx.windows.remove(id);
1283                    Err(e)
1284                }
1285            }
1286        })
1287    }
1288
1289    /// Instructs the platform to activate the application by bringing it to the foreground.
1290    pub fn activate(&self, ignoring_other_apps: bool) {
1291        self.platform.activate(ignoring_other_apps);
1292    }
1293
1294    /// Hide the application at the platform level.
1295    pub fn hide(&self) {
1296        self.platform.hide();
1297    }
1298
1299    /// Hide other applications at the platform level.
1300    pub fn hide_other_apps(&self) {
1301        self.platform.hide_other_apps();
1302    }
1303
1304    /// Unhide other applications at the platform level.
1305    pub fn unhide_other_apps(&self) {
1306        self.platform.unhide_other_apps();
1307    }
1308
1309    /// Returns the list of currently active displays.
1310    pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1311        self.platform.displays()
1312    }
1313
1314    /// Returns the primary display that will be used for new windows.
1315    pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1316        self.platform.primary_display()
1317    }
1318
1319    /// Returns whether `screen_capture_sources` may work.
1320    pub fn is_screen_capture_supported(&self) -> bool {
1321        self.platform.is_screen_capture_supported()
1322    }
1323
1324    /// Returns a list of available screen capture sources.
1325    pub fn screen_capture_sources(
1326        &self,
1327    ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1328        self.platform.screen_capture_sources()
1329    }
1330
1331    /// Returns the display with the given ID, if one exists.
1332    pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1333        self.displays()
1334            .iter()
1335            .find(|display| display.id() == id)
1336            .cloned()
1337    }
1338
1339    /// Returns the current thermal state of the system.
1340    pub fn thermal_state(&self) -> ThermalState {
1341        self.platform.thermal_state()
1342    }
1343
1344    /// Invokes a handler when the thermal state changes
1345    pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1346    where
1347        F: 'static + FnMut(&mut App),
1348    {
1349        let (subscription, activate) = self.thermal_state_observers.insert(
1350            (),
1351            Box::new(move |cx| {
1352                callback(cx);
1353                true
1354            }),
1355        );
1356        activate();
1357        subscription
1358    }
1359
1360    /// Returns the appearance of the application's windows.
1361    pub fn window_appearance(&self) -> WindowAppearance {
1362        self.platform.window_appearance()
1363    }
1364
1365    /// Overrides the appearance (light/dark) applied to the app's windows, independent of
1366    /// the OS-wide setting. Pass `None` to clear the override and follow the system again.
1367    /// The current value is reported by [`App::window_appearance`].
1368    ///
1369    /// On macOS this sets the underlying `NSApplication.appearance`, which controls the
1370    /// native window chrome (the window border and titlebar) of every window. Use this
1371    /// when the app uses a dark theme while the system is in light mode (or vice versa)
1372    /// so the window edges render to match the theme. While an appearance is forced,
1373    /// windows stop tracking system light/dark changes; pass `None` to resume following
1374    /// the system. On other platforms this is a no-op.
1375    pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
1376        self.platform.set_window_appearance(appearance);
1377    }
1378
1379    /// Returns the window button layout configuration when supported.
1380    pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1381        self.platform.button_layout()
1382    }
1383
1384    /// Reads data from the platform clipboard.
1385    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1386        self.platform.read_from_clipboard()
1387    }
1388
1389    /// Reads plain clipboard text asynchronously on the desktop backends.
1390    ///
1391    /// Returns `None` for empty, unavailable, or unsupported text. Images,
1392    /// file lists, and application metadata are not requested. Line endings
1393    /// are preserved; callers decide whether to normalize them.
1394    ///
1395    /// The clipboard may change before the native request is serviced. Callers
1396    /// must preserve input order and reject results for obsolete edit targets.
1397    /// Dropping the task ignores its result; an in-flight OS transfer may finish.
1398    /// The default implementation for custom backends uses their synchronous
1399    /// read method; override `Platform::read_text_from_clipboard_async` to avoid it.
1400    pub fn read_text_from_clipboard_async(&self) -> Task<Option<String>> {
1401        self.platform.read_text_from_clipboard_async()
1402    }
1403
1404    /// Sets the text rendering mode for the application.
1405    pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1406        self.text_rendering_mode.set(mode);
1407    }
1408
1409    /// Returns the current text rendering mode for the application.
1410    pub fn text_rendering_mode(&self) -> TextRenderingMode {
1411        self.text_rendering_mode.get()
1412    }
1413
1414    /// Reports backend support for native file clipboard writes with this intent.
1415    pub fn supports_file_clipboard(&self, operation: crate::FileClipboardOperation) -> bool {
1416        self.platform.supports_file_clipboard(operation)
1417    }
1418
1419    /// Publishes file paths and copy/move intent to the native clipboard.
1420    ///
1421    /// GPUI never moves or deletes files. Success means the native write was
1422    /// accepted, not that a recipient pasted the files. On error the clipboard
1423    /// may have been partially replaced; callers must not delete source files.
1424    /// Unsupported backends return an error without replacing the clipboard.
1425    pub fn write_files_to_clipboard(
1426        &self,
1427        paths: crate::ExternalPaths,
1428        operation: crate::FileClipboardOperation,
1429    ) -> std::result::Result<(), crate::FileClipboardError> {
1430        if !self.supports_file_clipboard(operation) {
1431            return Err(crate::FileClipboardError::Unsupported);
1432        }
1433        paths.validate_for_clipboard()?;
1434        self.platform.write_files_to_clipboard(paths, operation)
1435    }
1436
1437    /// Writes data to the platform clipboard.
1438    pub fn write_to_clipboard(&self, item: ClipboardItem) {
1439        self.platform.write_to_clipboard(item)
1440    }
1441
1442    /// Reads data from the primary selection buffer.
1443    /// Only available on Linux.
1444    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1445    pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1446        self.platform.read_from_primary()
1447    }
1448
1449    /// Writes data to the primary selection buffer.
1450    /// Only available on Linux.
1451    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1452    pub fn write_to_primary(&self, item: ClipboardItem) {
1453        self.platform.write_to_primary(item)
1454    }
1455
1456    /// Reads data from macOS's "Find" pasteboard.
1457    ///
1458    /// Used to share the current search string between apps.
1459    ///
1460    /// https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find
1461    #[cfg(target_os = "macos")]
1462    pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1463        self.platform.read_from_find_pasteboard()
1464    }
1465
1466    /// Writes data to macOS's "Find" pasteboard.
1467    ///
1468    /// Used to share the current search string between apps.
1469    ///
1470    /// https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find
1471    #[cfg(target_os = "macos")]
1472    pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1473        self.platform.write_to_find_pasteboard(item)
1474    }
1475
1476    /// Writes credentials to the platform keychain.
1477    pub fn write_credentials(
1478        &self,
1479        url: &str,
1480        username: &str,
1481        password: &[u8],
1482    ) -> Task<Result<()>> {
1483        self.platform.write_credentials(url, username, password)
1484    }
1485
1486    /// Reads credentials from the platform keychain.
1487    pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1488        self.platform.read_credentials(url)
1489    }
1490
1491    /// Deletes credentials from the platform keychain.
1492    pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1493        self.platform.delete_credentials(url)
1494    }
1495
1496    /// Directs the platform's default browser to open the given URL.
1497    pub fn open_url(&self, url: &str) {
1498        self.platform.open_url(url);
1499    }
1500
1501    /// Registers the given URL scheme (e.g. `zed` for `zed://` urls) to be
1502    /// opened by the current app.
1503    ///
1504    /// On some platforms (e.g. macOS) you may be able to register URL schemes
1505    /// as part of app distribution, but this method exists to let you register
1506    /// schemes at runtime.
1507    pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1508        self.platform.register_url_scheme(scheme)
1509    }
1510
1511    /// Sets the application's process-wide identity and user-visible name.
1512    ///
1513    /// The identifier is used for platform identity mechanisms such as the
1514    /// Windows AppUserModelID. The name is used wherever the operating system
1515    /// presents the application to the user. Call this once, early in startup,
1516    /// before opening windows or posting notifications.
1517    pub fn set_app_identity(&self, identifier: &str, name: &str) {
1518        self.platform.set_app_identity(identifier, name);
1519    }
1520
1521    /// Posts a notification to the operating system's notification center.
1522    ///
1523    /// Posting a notification whose [`SystemNotification::tag`] matches an
1524    /// earlier one replaces that notification where the platform supports it.
1525    /// No-op on platforms without notification support, or when delivery is
1526    /// unavailable (e.g. authorization was denied).
1527    pub fn show_system_notification(&self, notification: SystemNotification) {
1528        self.platform.show_system_notification(notification);
1529    }
1530
1531    /// Removes the delivered or pending notification with this tag.
1532    ///
1533    /// Best-effort: some platforms cannot retract a notification once shown,
1534    /// in which case it ages out of the notification center on its own.
1535    pub fn dismiss_system_notification(&self, tag: &str) {
1536        self.platform.dismiss_system_notification(tag);
1537    }
1538
1539    /// Registers the handler invoked when the user activates a system
1540    /// notification, either by clicking its body or one of its action
1541    /// buttons. Subsequent registrations replace the handler.
1542    pub fn on_system_notification_response<F>(&self, mut callback: F)
1543    where
1544        F: 'static + FnMut(SystemNotificationResponse, &mut App),
1545    {
1546        let this = self.this.clone();
1547        self.platform
1548            .on_system_notification_response(Box::new(move |response| {
1549                if let Some(app) = this.upgrade() {
1550                    callback(response, &mut app.borrow_mut());
1551                }
1552            }));
1553    }
1554
1555    /// Returns the full pathname of the current app bundle.
1556    ///
1557    /// Returns an error if the app is not being run from a bundle.
1558    pub fn app_path(&self) -> Result<PathBuf> {
1559        self.platform.app_path()
1560    }
1561
1562    /// On Linux, returns the name of the compositor in use.
1563    ///
1564    /// Returns an empty string on other platforms.
1565    pub fn compositor_name(&self) -> &'static str {
1566        self.platform.compositor_name()
1567    }
1568
1569    /// Returns the file URL of the executable with the specified name in the application bundle
1570    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
1571        self.platform.path_for_auxiliary_executable(name)
1572    }
1573
1574    /// Displays a platform modal for selecting paths.
1575    ///
1576    /// When one or more paths are selected, they'll be relayed asynchronously via the returned oneshot channel.
1577    /// If cancelled, a `None` will be relayed instead.
1578    /// May return an error on Linux if the file picker couldn't be opened.
1579    pub fn prompt_for_paths(
1580        &self,
1581        options: PathPromptOptions,
1582    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
1583        self.platform.prompt_for_paths(options)
1584    }
1585
1586    /// Displays a platform modal for selecting a new path where a file can be saved.
1587    ///
1588    /// The provided directory will be used to set the initial location.
1589    /// When a path is selected, it is relayed asynchronously via the returned oneshot channel.
1590    /// If cancelled, a `None` will be relayed instead.
1591    /// May return an error on Linux if the file picker couldn't be opened.
1592    pub fn prompt_for_new_path(
1593        &self,
1594        directory: &Path,
1595        suggested_name: Option<&str>,
1596    ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
1597        self.platform.prompt_for_new_path(directory, suggested_name)
1598    }
1599
1600    /// Reveals the specified path at the platform level, such as in Finder on macOS.
1601    pub fn reveal_path(&self, path: &Path) {
1602        self.platform.reveal_path(path)
1603    }
1604
1605    /// Opens the specified path with the system's default application.
1606    pub fn open_with_system(&self, path: &Path) {
1607        self.platform.open_with_system(path)
1608    }
1609
1610    /// Returns whether the user has configured scrollbars to auto-hide at the platform level.
1611    pub fn should_auto_hide_scrollbars(&self) -> bool {
1612        self.platform.should_auto_hide_scrollbars()
1613    }
1614
1615    /// Restarts the application.
1616    pub fn restart(&mut self) {
1617        self.restart_observers
1618            .clone()
1619            .retain(&(), |observer| observer(self));
1620        self.platform.restart(self.restart_path.take())
1621    }
1622
1623    /// Sets the path to use when restarting the application.
1624    pub fn set_restart_path(&mut self, path: PathBuf) {
1625        self.restart_path = Some(path);
1626    }
1627
1628    /// Returns the HTTP client for the application.
1629    pub fn http_client(&self) -> Arc<dyn HttpClient> {
1630        self.http_client.clone()
1631    }
1632
1633    /// Sets the HTTP client for the application.
1634    pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
1635        self.http_client = new_client;
1636    }
1637
1638    /// Configures when the application should automatically quit.
1639    /// By default, [`QuitMode::Default`] is used.
1640    pub fn set_quit_mode(&mut self, mode: QuitMode) {
1641        self.quit_mode = mode;
1642    }
1643
1644    /// Returns the SVG renderer used by the application.
1645    pub fn svg_renderer(&self) -> SvgRenderer {
1646        self.svg_renderer.clone()
1647    }
1648
1649    pub(crate) fn push_effect(&mut self, effect: Effect) {
1650        match &effect {
1651            Effect::Notify { emitter } => {
1652                if !self.pending_notifications.insert(*emitter) {
1653                    return;
1654                }
1655            }
1656            Effect::NotifyGlobalObservers { global_type } => {
1657                if !self.pending_global_notifications.insert(*global_type) {
1658                    return;
1659                }
1660            }
1661            _ => {}
1662        };
1663
1664        self.pending_effects.push_back(effect);
1665    }
1666
1667    /// Called at the end of [`App::update`] to complete any side effects
1668    /// such as notifying observers, emitting events, etc. Effects can themselves
1669    /// cause effects, so we continue looping until all effects are processed.
1670    fn flush_effects(&mut self) {
1671        loop {
1672            self.release_dropped_entities();
1673            self.release_dropped_focus_handles();
1674            if let Some(effect) = self.pending_effects.pop_front() {
1675                match effect {
1676                    Effect::Notify { emitter } => {
1677                        self.apply_notify_effect(emitter);
1678                    }
1679
1680                    Effect::Emit {
1681                        emitter,
1682                        event_type,
1683                        event,
1684                    } => self.apply_emit_effect(emitter, event_type, &*event),
1685
1686                    Effect::RefreshWindows => {
1687                        self.apply_refresh_effect();
1688                    }
1689
1690                    Effect::NotifyGlobalObservers { global_type } => {
1691                        self.apply_notify_global_observers_effect(global_type);
1692                    }
1693
1694                    Effect::Defer { callback } => {
1695                        self.apply_defer_effect(callback);
1696                    }
1697                    Effect::EntityCreated {
1698                        entity,
1699                        tid,
1700                        window,
1701                    } => {
1702                        self.apply_entity_created_effect(entity, tid, window);
1703                    }
1704                }
1705            } else {
1706                #[cfg(any(test, feature = "test-support", feature = "bench"))]
1707                for window in self
1708                    .windows
1709                    .values()
1710                    .filter_map(|window| {
1711                        let window = window.as_deref()?;
1712                        window.invalidator.is_dirty().then_some(window.handle)
1713                    })
1714                    .collect::<Vec<_>>()
1715                {
1716                    self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
1717                        .unwrap();
1718                }
1719
1720                if self.pending_effects.is_empty() {
1721                    self.event_arena.clear();
1722                    break;
1723                }
1724            }
1725        }
1726    }
1727
1728    /// Repeatedly called during `flush_effects` to release any entities whose
1729    /// reference count has become zero. We invoke any release observers before dropping
1730    /// each entity.
1731    fn release_dropped_entities(&mut self) {
1732        loop {
1733            let dropped = self.entities.take_dropped();
1734            if dropped.is_empty() {
1735                break;
1736            }
1737
1738            for (entity_id, mut entity) in dropped {
1739                self.observers.remove(&entity_id);
1740                self.event_listeners.remove(&entity_id);
1741                self.window_invalidators_by_entity.remove(&entity_id);
1742                self.current_window_by_entity.remove(&entity_id);
1743                for release_callback in self.release_listeners.remove(&entity_id) {
1744                    release_callback(entity.as_mut(), self);
1745                }
1746            }
1747        }
1748    }
1749
1750    /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
1751    fn release_dropped_focus_handles(&mut self) {
1752        self.focus_handles
1753            .clone()
1754            .write()
1755            .retain(|handle_id, focus| {
1756                if focus.ref_count.load(SeqCst) == 0 {
1757                    for window_handle in self.windows() {
1758                        window_handle
1759                            .update(self, |_, window, _| {
1760                                if window.focus == Some(handle_id) {
1761                                    window.blur();
1762                                }
1763                            })
1764                            .unwrap();
1765                    }
1766                    false
1767                } else {
1768                    true
1769                }
1770            });
1771    }
1772
1773    fn apply_notify_effect(&mut self, emitter: EntityId) {
1774        self.pending_notifications.remove(&emitter);
1775
1776        self.observers
1777            .clone()
1778            .retain(&emitter, |handler| handler(self));
1779    }
1780
1781    fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
1782        self.event_listeners
1783            .clone()
1784            .retain(&emitter, |(stored_type, handler)| {
1785                if *stored_type == event_type {
1786                    handler(event, self)
1787                } else {
1788                    true
1789                }
1790            });
1791    }
1792
1793    fn apply_refresh_effect(&mut self) {
1794        for window in self.windows.values_mut() {
1795            if let Some(window) = window.as_deref_mut() {
1796                window.refreshing = true;
1797                window.invalidator.set_dirty(true);
1798            }
1799        }
1800    }
1801
1802    fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
1803        self.pending_global_notifications.remove(&type_id);
1804        self.global_observers
1805            .clone()
1806            .retain(&type_id, |observer| observer(self));
1807    }
1808
1809    fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
1810        callback(self);
1811    }
1812
1813    fn apply_entity_created_effect(
1814        &mut self,
1815        entity: AnyEntity,
1816        tid: TypeId,
1817        window: Option<WindowId>,
1818    ) {
1819        // Seed the entity's current window from its creation context so
1820        // `with_window` resolves correctly before the entity has ever been
1821        // rendered.
1822        if let Some(id) = window {
1823            self.current_window_by_entity.insert(entity.entity_id(), id);
1824        }
1825
1826        self.new_entity_observers.clone().retain(&tid, |observer| {
1827            if let Some(id) = window {
1828                self.update_window_id(id, {
1829                    let entity = entity.clone();
1830                    |_, window, cx| (observer)(entity, &mut Some(window), cx)
1831                })
1832                .expect("All windows should be off the stack when flushing effects");
1833            } else {
1834                (observer)(entity.clone(), &mut None, self)
1835            }
1836            true
1837        });
1838    }
1839
1840    /// Run `f` against the entity's *current* window — the most recently
1841    /// rendered window that referenced the entity, or its creation window if
1842    /// it has yet to be rendered. Returns `None` if the entity has no
1843    /// current window, or if that window has been closed, or if it is
1844    /// already on the update stack.
1845    pub fn with_window<R>(
1846        &mut self,
1847        entity_id: EntityId,
1848        f: impl FnOnce(&mut Window, &mut App) -> R,
1849    ) -> Option<R> {
1850        let window_id = *self.current_window_by_entity.get(&entity_id)?;
1851        self.update_window_id(window_id, |_, window, cx| f(window, cx))
1852            .ok()
1853    }
1854
1855    fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
1856        self.current_window_by_entity
1857            .entry(entity_id)
1858            .or_insert(window);
1859    }
1860
1861    pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
1862    where
1863        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1864    {
1865        self.update(|cx| {
1866            let mut window = cx.windows.get_mut(id)?.take()?;
1867
1868            let root_view = window.root.clone().unwrap();
1869
1870            cx.window_update_stack.push(window.handle.id);
1871            let result = update(root_view, &mut window, cx);
1872            fn trail(id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
1873                cx.window_update_stack.pop();
1874
1875                if window.removed {
1876                    cx.end_platform_drag(id);
1877                    cx.window_handles.remove(&id);
1878                    cx.windows.remove(id);
1879                    if let Some(tracked) = cx.tracked_entities.remove(&id) {
1880                        for entity_id in tracked {
1881                            if let Some(windows) =
1882                                cx.window_invalidators_by_entity.get_mut(&entity_id)
1883                            {
1884                                windows.remove(&id);
1885                            }
1886                            if cx.current_window_by_entity.get(&entity_id) == Some(&id) {
1887                                cx.current_window_by_entity.remove(&entity_id);
1888                            }
1889                        }
1890                    }
1891
1892                    cx.window_closed_observers.clone().retain(&(), |callback| {
1893                        callback(cx, id);
1894                        true
1895                    });
1896
1897                    let quit_on_empty = match cx.quit_mode {
1898                        QuitMode::Explicit => false,
1899                        QuitMode::LastWindowClosed => true,
1900                        QuitMode::Default => cfg!(not(target_os = "macos")),
1901                    };
1902
1903                    if quit_on_empty && cx.windows.is_empty() {
1904                        cx.quit();
1905                    }
1906                } else {
1907                    cx.windows.get_mut(id)?.replace(window);
1908                }
1909                Some(())
1910            }
1911            trail(id, window, cx)?;
1912
1913            Some(result)
1914        })
1915        .context("window not found")
1916    }
1917
1918    /// Creates an `AsyncApp`, which can be cloned and has a static lifetime
1919    /// so it can be held across `await` points.
1920    pub fn to_async(&self) -> AsyncApp {
1921        AsyncApp {
1922            app: self.this.clone(),
1923            background_executor: self.background_executor.clone(),
1924            foreground_executor: self.foreground_executor.clone(),
1925        }
1926    }
1927
1928    /// Obtains a reference to the executor, which can be used to spawn futures.
1929    pub fn background_executor(&self) -> &BackgroundExecutor {
1930        &self.background_executor
1931    }
1932
1933    /// Obtains a reference to the executor, which can be used to spawn futures.
1934    pub fn foreground_executor(&self) -> &ForegroundExecutor {
1935        if self.quitting {
1936            panic!("Can't spawn on main thread after on_app_quit")
1937        };
1938        &self.foreground_executor
1939    }
1940
1941    /// Spawns the future returned by the given function on the main thread. The closure will be invoked
1942    /// with [AsyncApp], which allows the application state to be accessed across await points.
1943    #[track_caller]
1944    pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
1945    where
1946        AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1947        R: 'static,
1948    {
1949        if self.quitting {
1950            debug_panic!("Can't spawn on main thread after on_app_quit")
1951        };
1952
1953        let mut cx = self.to_async();
1954
1955        self.foreground_executor
1956            .spawn(async move { f(&mut cx).await }.boxed_local())
1957    }
1958
1959    /// Spawns the future returned by the given function on the main thread with
1960    /// the given priority. The closure will be invoked with [AsyncApp], which
1961    /// allows the application state to be accessed across await points.
1962    pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
1963    where
1964        AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1965        R: 'static,
1966    {
1967        if self.quitting {
1968            debug_panic!("Can't spawn on main thread after on_app_quit")
1969        };
1970
1971        let mut cx = self.to_async();
1972
1973        self.foreground_executor
1974            .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
1975    }
1976
1977    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1978    /// that are currently on the stack to be returned to the app.
1979    pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
1980        self.push_effect(Effect::Defer {
1981            callback: Box::new(f),
1982        });
1983    }
1984
1985    /// Accessor for the application's asset source, which is provided when constructing the `App`.
1986    pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
1987        &self.asset_source
1988    }
1989
1990    /// Accessor for the text system.
1991    pub fn text_system(&self) -> &Arc<TextSystem> {
1992        &self.text_system
1993    }
1994
1995    /// Check whether a global of the given type has been assigned.
1996    pub fn has_global<G: Global>(&self) -> bool {
1997        self.globals_by_type.contains_key(&TypeId::of::<G>())
1998    }
1999
2000    /// Access the global of the given type. Panics if a global for that type has not been assigned.
2001    #[track_caller]
2002    pub fn global<G: Global>(&self) -> &G {
2003        self.globals_by_type
2004            .get(&TypeId::of::<G>())
2005            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2006            .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2007    }
2008
2009    /// Access the global of the given type if a value has been assigned.
2010    pub fn try_global<G: Global>(&self) -> Option<&G> {
2011        self.globals_by_type
2012            .get(&TypeId::of::<G>())
2013            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2014    }
2015
2016    /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
2017    #[track_caller]
2018    pub fn global_mut<G: Global>(&mut self) -> &mut G {
2019        let global_type = TypeId::of::<G>();
2020        self.push_effect(Effect::NotifyGlobalObservers { global_type });
2021        self.globals_by_type
2022            .get_mut(&global_type)
2023            .and_then(|any_state| any_state.downcast_mut::<G>())
2024            .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2025    }
2026
2027    /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
2028    /// yet been assigned.
2029    pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
2030        let global_type = TypeId::of::<G>();
2031        self.push_effect(Effect::NotifyGlobalObservers { global_type });
2032        self.globals_by_type
2033            .entry(global_type)
2034            .or_insert_with(|| Box::<G>::default())
2035            .downcast_mut::<G>()
2036            .unwrap()
2037    }
2038
2039    /// Sets the value of the global of the given type.
2040    pub fn set_global<G: Global>(&mut self, global: G) {
2041        let global_type = TypeId::of::<G>();
2042        self.push_effect(Effect::NotifyGlobalObservers { global_type });
2043        self.globals_by_type.insert(global_type, Box::new(global));
2044    }
2045
2046    /// Clear all stored globals. Does not notify global observers.
2047    #[cfg(any(test, feature = "test-support"))]
2048    pub fn clear_globals(&mut self) {
2049        self.globals_by_type.drain();
2050    }
2051
2052    /// Remove the global of the given type from the app context. Does not notify global observers.
2053    pub fn remove_global<G: Global>(&mut self) -> G {
2054        let global_type = TypeId::of::<G>();
2055        self.push_effect(Effect::NotifyGlobalObservers { global_type });
2056        *self
2057            .globals_by_type
2058            .remove(&global_type)
2059            .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2060            .downcast()
2061            .unwrap()
2062    }
2063
2064    /// Register a callback to be invoked when a global of the given type is updated.
2065    pub fn observe_global<G: Global>(
2066        &mut self,
2067        mut f: impl FnMut(&mut Self) + 'static,
2068    ) -> Subscription {
2069        let (subscription, activate) = self.global_observers.insert(
2070            TypeId::of::<G>(),
2071            Box::new(move |cx| {
2072                f(cx);
2073                true
2074            }),
2075        );
2076        self.defer(move |_| activate());
2077        subscription
2078    }
2079
2080    /// Move the global of the given type to the stack.
2081    #[track_caller]
2082    pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2083        GlobalLease::new(
2084            self.globals_by_type
2085                .remove(&TypeId::of::<G>())
2086                .with_context(|| format!("no global registered of type {}", type_name::<G>()))
2087                .unwrap(),
2088        )
2089    }
2090
2091    /// Restore the global of the given type after it is moved to the stack.
2092    pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2093        let global_type = TypeId::of::<G>();
2094
2095        self.push_effect(Effect::NotifyGlobalObservers { global_type });
2096        self.globals_by_type.insert(global_type, lease.global);
2097    }
2098
2099    pub(crate) fn new_entity_observer(
2100        &self,
2101        key: TypeId,
2102        value: NewEntityListener,
2103    ) -> Subscription {
2104        let (subscription, activate) = self.new_entity_observers.insert(key, value);
2105        activate();
2106        subscription
2107    }
2108
2109    /// Arrange for the given function to be invoked whenever a view of the specified type is created.
2110    /// The function will be passed a mutable reference to the view along with an appropriate context.
2111    pub fn observe_new<T: 'static>(
2112        &self,
2113        on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2114    ) -> Subscription {
2115        self.new_entity_observer(
2116            TypeId::of::<T>(),
2117            Box::new(
2118                move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2119                    any_entity
2120                        .downcast::<T>()
2121                        .unwrap()
2122                        .update(cx, |entity_state, cx| {
2123                            on_new(entity_state, window.as_deref_mut(), cx)
2124                        })
2125                },
2126            ),
2127        )
2128    }
2129
2130    /// Observe the release of a entity. The callback is invoked after the entity
2131    /// has no more strong references but before it has been dropped.
2132    pub fn observe_release<T>(
2133        &self,
2134        handle: &Entity<T>,
2135        on_release: impl FnOnce(&mut T, &mut App) + 'static,
2136    ) -> Subscription
2137    where
2138        T: 'static,
2139    {
2140        let (subscription, activate) = self.release_listeners.insert(
2141            handle.entity_id(),
2142            Box::new(move |entity, cx| {
2143                let entity = entity.downcast_mut().expect("invalid entity type");
2144                on_release(entity, cx)
2145            }),
2146        );
2147        activate();
2148        subscription
2149    }
2150
2151    /// Observe the release of a entity. The callback is invoked after the entity
2152    /// has no more strong references but before it has been dropped.
2153    pub fn observe_release_in<T>(
2154        &self,
2155        handle: &Entity<T>,
2156        window: &Window,
2157        on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2158    ) -> Subscription
2159    where
2160        T: 'static,
2161    {
2162        let window_handle = window.handle;
2163        self.observe_release(handle, move |entity, cx| {
2164            let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2165        })
2166    }
2167
2168    /// Register a callback to be invoked when a keystroke is received by the application
2169    /// in any window. Note that this fires after all other action and event mechanisms have resolved
2170    /// and that this API will not be invoked if the event's propagation is stopped.
2171    pub fn observe_keystrokes(
2172        &mut self,
2173        mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2174    ) -> Subscription {
2175        fn inner(
2176            keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
2177            handler: KeystrokeObserver,
2178        ) -> Subscription {
2179            let (subscription, activate) = keystroke_observers.insert((), handler);
2180            activate();
2181            subscription
2182        }
2183
2184        inner(
2185            &self.keystroke_observers,
2186            Box::new(move |event, window, cx| {
2187                f(event, window, cx);
2188                true
2189            }),
2190        )
2191    }
2192
2193    /// Register a callback to be invoked when a keystroke is received by the application
2194    /// in any window. Note that this fires _before_ all other action and event mechanisms have resolved
2195    /// unlike [`App::observe_keystrokes`] which fires after. This means that `cx.stop_propagation` calls
2196    /// within interceptors will prevent action dispatch
2197    pub fn intercept_keystrokes(
2198        &mut self,
2199        mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2200    ) -> Subscription {
2201        fn inner(
2202            keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
2203            handler: KeystrokeObserver,
2204        ) -> Subscription {
2205            let (subscription, activate) = keystroke_interceptors.insert((), handler);
2206            activate();
2207            subscription
2208        }
2209
2210        inner(
2211            &self.keystroke_interceptors,
2212            Box::new(move |event, window, cx| {
2213                f(event, window, cx);
2214                true
2215            }),
2216        )
2217    }
2218
2219    /// Register key bindings.
2220    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2221        self.keymap.borrow_mut().add_bindings(bindings);
2222        self.pending_effects.push_back(Effect::RefreshWindows);
2223    }
2224
2225    /// Clear all key bindings in the app.
2226    pub fn clear_key_bindings(&mut self) {
2227        self.keymap.borrow_mut().clear();
2228        self.pending_effects.push_back(Effect::RefreshWindows);
2229    }
2230
2231    /// Get all key bindings in the app.
2232    pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2233        self.keymap.clone()
2234    }
2235
2236    /// Register a global handler for actions invoked via the keyboard. These handlers are run at
2237    /// the end of the bubble phase for actions, and so will only be invoked if there are no other
2238    /// handlers or if they called `cx.propagate()`.
2239    pub fn on_action<A: Action>(
2240        &mut self,
2241        listener: impl Fn(&A, &mut Self) + 'static,
2242    ) -> &mut Self {
2243        self.global_action_listeners
2244            .entry(TypeId::of::<A>())
2245            .or_default()
2246            .push(Rc::new(move |action, phase, cx| {
2247                if phase == DispatchPhase::Bubble {
2248                    let action = action.downcast_ref().unwrap();
2249                    listener(action, cx)
2250                }
2251            }));
2252        self
2253    }
2254
2255    /// Event handlers propagate events by default. Call this method to stop dispatching to
2256    /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
2257    /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
2258    /// calling this method before effects are flushed.
2259    pub fn stop_propagation(&mut self) {
2260        self.propagate_event = false;
2261    }
2262
2263    /// Action handlers stop propagation by default during the bubble phase of action dispatch
2264    /// dispatching to action handlers higher in the element tree. This is the opposite of
2265    /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
2266    /// this method before effects are flushed.
2267    pub fn propagate(&mut self) {
2268        self.propagate_event = true;
2269    }
2270
2271    /// Build an action from some arbitrary data, typically a keymap entry.
2272    pub fn build_action(
2273        &self,
2274        name: &str,
2275        data: Option<serde_json::Value>,
2276    ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2277        self.actions.build_action(name, data)
2278    }
2279
2280    /// Get all action names that have been registered. Note that registration only allows for
2281    /// actions to be built dynamically, and is unrelated to binding actions in the element tree.
2282    pub fn all_action_names(&self) -> &[&'static str] {
2283        self.actions.all_action_names()
2284    }
2285
2286    /// Returns key bindings that invoke the given action on the currently focused element, without
2287    /// checking context. Bindings are returned in the order they were added. For display, the last
2288    /// binding should take precedence.
2289    pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2290        RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2291    }
2292
2293    /// Get all non-internal actions that have been registered, along with their schemas.
2294    pub fn action_schemas(
2295        &self,
2296        generator: &mut schemars::SchemaGenerator,
2297    ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2298        self.actions.action_schemas(generator)
2299    }
2300
2301    /// Get the schema for a specific action by name.
2302    /// Returns `None` if the action is not found.
2303    /// Returns `Some(None)` if the action exists but has no schema.
2304    /// Returns `Some(Some(schema))` if the action exists and has a schema.
2305    pub fn action_schema_by_name(
2306        &self,
2307        name: &str,
2308        generator: &mut schemars::SchemaGenerator,
2309    ) -> Option<Option<schemars::Schema>> {
2310        self.actions.action_schema_by_name(name, generator)
2311    }
2312
2313    /// Get a map from a deprecated action name to the canonical name.
2314    pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2315        self.actions.deprecated_aliases()
2316    }
2317
2318    /// Get a map from an action name to the deprecation messages.
2319    pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2320        self.actions.deprecation_messages()
2321    }
2322
2323    /// Get a map from an action name to the documentation.
2324    pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2325        self.actions.documentation()
2326    }
2327
2328    /// Register a callback to be invoked when the application is about to quit.
2329    /// It is not possible to cancel the quit event at this point.
2330    pub fn on_app_quit<Fut>(
2331        &self,
2332        mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2333    ) -> Subscription
2334    where
2335        Fut: 'static + Future<Output = ()>,
2336    {
2337        let (subscription, activate) = self.quit_observers.insert(
2338            (),
2339            Box::new(move |cx| {
2340                let future = on_quit(cx);
2341                future.boxed_local()
2342            }),
2343        );
2344        activate();
2345        subscription
2346    }
2347
2348    /// Register a callback to be invoked when the application is about to restart.
2349    ///
2350    /// These callbacks are called before any `on_app_quit` callbacks.
2351    pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2352        let (subscription, activate) = self.restart_observers.insert(
2353            (),
2354            Box::new(move |cx| {
2355                on_restart(cx);
2356                true
2357            }),
2358        );
2359        activate();
2360        subscription
2361    }
2362
2363    /// Register a callback to be invoked when a window is closed
2364    /// The window is no longer accessible at the point this callback is invoked.
2365    pub fn on_window_closed(
2366        &self,
2367        mut on_closed: impl FnMut(&mut App, WindowId) + 'static,
2368    ) -> Subscription {
2369        let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
2370        activate();
2371        subscription
2372    }
2373
2374    pub(crate) fn clear_pending_keystrokes(&mut self) {
2375        for window in self.windows() {
2376            window
2377                .update(self, |_, window, cx| {
2378                    if window.pending_input_keystrokes().is_some() {
2379                        window.clear_pending_keystrokes();
2380                        window.pending_input_changed(cx);
2381                    }
2382                })
2383                .ok();
2384        }
2385    }
2386
2387    /// Checks if the given action is bound in the current context, as defined by the app's current focus,
2388    /// the bindings in the element tree, and any global action listeners.
2389    pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2390        let mut action_available = false;
2391        if let Some(window) = self.active_window()
2392            && let Ok(window_action_available) =
2393                window.update(self, |_, window, cx| window.is_action_available(action, cx))
2394        {
2395            action_available = window_action_available;
2396        }
2397
2398        action_available
2399            || self
2400                .global_action_listeners
2401                .contains_key(&action.as_any().type_id())
2402    }
2403
2404    /// Sets the menu bar for this application. This will replace any existing menu bar.
2405    pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2406        let menus: Vec<Menu> = menus.into_iter().collect();
2407        self.platform.set_menus(menus, &self.keymap.borrow());
2408    }
2409
2410    /// Gets the menu bar for this application.
2411    pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2412        self.platform.get_menus()
2413    }
2414
2415    /// Sets the right click menu for the app icon in the dock
2416    pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2417        self.platform.set_dock_menu(menus, &self.keymap.borrow())
2418    }
2419
2420    /// Performs the action associated with the given dock menu item, only used on Windows for now.
2421    pub fn perform_dock_menu_action(&self, action: usize) {
2422        self.platform.perform_dock_menu_action(action);
2423    }
2424
2425    /// Adds given path to the bottom of the list of recent paths for the application.
2426    /// The list is usually shown on the application icon's context menu in the dock,
2427    /// and allows to open the recent files via that context menu.
2428    /// If the path is already in the list, it will be moved to the bottom of the list.
2429    pub fn add_recent_document(&self, path: &Path) {
2430        self.platform.add_recent_document(path);
2431    }
2432
2433    /// Updates the jump list with the updated list of recent paths for the application, only used on Windows for now.
2434    /// Note that this also sets the dock menu on Windows.
2435    pub fn update_jump_list(
2436        &self,
2437        menus: Vec<MenuItem>,
2438        entries: Vec<SmallVec<[PathBuf; 2]>>,
2439    ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2440        self.platform.update_jump_list(menus, entries)
2441    }
2442
2443    /// Dispatch an action to the currently active window or global action handler
2444    /// See [`crate::Action`] for more information on how actions work
2445    pub fn dispatch_action(&mut self, action: &dyn Action) {
2446        if let Some(active_window) = self.active_window() {
2447            active_window
2448                .update(self, |_, window, cx| {
2449                    window.dispatch_action(action.boxed_clone(), cx)
2450                })
2451                .log_err();
2452        } else {
2453            self.dispatch_global_action(action);
2454        }
2455    }
2456
2457    fn dispatch_global_action(&mut self, action: &dyn Action) {
2458        self.propagate_event = true;
2459
2460        if let Some(mut global_listeners) = self
2461            .global_action_listeners
2462            .remove(&action.as_any().type_id())
2463        {
2464            for listener in &global_listeners {
2465                listener(action.as_any(), DispatchPhase::Capture, self);
2466                if !self.propagate_event {
2467                    break;
2468                }
2469            }
2470
2471            global_listeners.extend(
2472                self.global_action_listeners
2473                    .remove(&action.as_any().type_id())
2474                    .unwrap_or_default(),
2475            );
2476
2477            self.global_action_listeners
2478                .insert(action.as_any().type_id(), global_listeners);
2479        }
2480
2481        if self.propagate_event
2482            && let Some(mut global_listeners) = self
2483                .global_action_listeners
2484                .remove(&action.as_any().type_id())
2485        {
2486            for listener in global_listeners.iter().rev() {
2487                listener(action.as_any(), DispatchPhase::Bubble, self);
2488                if !self.propagate_event {
2489                    break;
2490                }
2491            }
2492
2493            global_listeners.extend(
2494                self.global_action_listeners
2495                    .remove(&action.as_any().type_id())
2496                    .unwrap_or_default(),
2497            );
2498
2499            self.global_action_listeners
2500                .insert(action.as_any().type_id(), global_listeners);
2501        }
2502    }
2503
2504    /// Is there currently something being dragged?
2505    pub fn has_active_drag(&self) -> bool {
2506        self.active_drag.is_some()
2507    }
2508
2509    /// Gets the cursor style of the currently active drag operation.
2510    pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
2511        self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
2512    }
2513
2514    /// Stops active drag and clears any related effects.
2515    pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
2516        if self.active_drag.is_some() {
2517            self.active_drag = None;
2518            if self.platform_owned_drag.as_ref().is_some_and(|drag| {
2519                drag.source_window == window.window_handle().window_id()
2520                    && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2521            }) {
2522                self.platform_owned_drag = None;
2523            }
2524            window.refresh();
2525            true
2526        } else {
2527            false
2528        }
2529    }
2530
2531    pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2532        let Some(drag) = self.active_drag.take() else {
2533            return false;
2534        };
2535        self.platform_owned_drag = Some(PlatformOwnedDrag {
2536            source_window,
2537            state: PlatformOwnedDragState::Suspended(drag),
2538        });
2539        true
2540    }
2541
2542    pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
2543        let Some(platform_drag) = self
2544            .platform_owned_drag
2545            .as_mut()
2546            .filter(|drag| drag.source_window == source_window)
2547        else {
2548            return false;
2549        };
2550        let state = std::mem::replace(
2551            &mut platform_drag.state,
2552            PlatformOwnedDragState::RestoredInSourceWindow,
2553        );
2554        let PlatformOwnedDragState::Suspended(drag) = state else {
2555            return false;
2556        };
2557        self.active_drag = Some(drag);
2558        true
2559    }
2560
2561    pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2562        let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
2563            drag.source_window == source_window
2564                && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2565        }) else {
2566            return false;
2567        };
2568        let Some(drag) = self.active_drag.take() else {
2569            return false;
2570        };
2571        platform_drag.state = PlatformOwnedDragState::Suspended(drag);
2572        true
2573    }
2574
2575    pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
2576        if !self
2577            .platform_owned_drag
2578            .as_ref()
2579            .is_some_and(|drag| drag.source_window == source_window)
2580        {
2581            return false;
2582        }
2583        self.platform_owned_drag = None;
2584        self.active_drag = None;
2585        true
2586    }
2587
2588    /// Sets the cursor style for the currently active drag operation.
2589    pub fn set_active_drag_cursor_style(
2590        &mut self,
2591        cursor_style: CursorStyle,
2592        window: &mut Window,
2593    ) -> bool {
2594        if let Some(ref mut drag) = self.active_drag {
2595            drag.cursor_style = Some(cursor_style);
2596            window.refresh();
2597            true
2598        } else {
2599            false
2600        }
2601    }
2602
2603    /// Set the prompt renderer for GPUI. This will replace the default or platform specific
2604    /// prompts with this custom implementation.
2605    pub fn set_prompt_builder(
2606        &mut self,
2607        renderer: impl Fn(
2608            PromptLevel,
2609            &str,
2610            Option<&str>,
2611            &[PromptButton],
2612            PromptHandle,
2613            &mut Window,
2614            &mut App,
2615        ) -> RenderablePromptHandle
2616        + 'static,
2617    ) {
2618        self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
2619    }
2620
2621    /// Reset the prompt builder to the default implementation.
2622    pub fn reset_prompt_builder(&mut self) {
2623        self.prompt_builder = Some(PromptBuilder::Default);
2624    }
2625
2626    /// Remove an asset from GPUI's cache
2627    pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
2628        let asset_id = (TypeId::of::<A>(), hash(source));
2629        self.loading_assets.remove(&asset_id);
2630    }
2631
2632    /// Check whether an asset is present in GPUI's cache (loading or loaded),
2633    /// without fetching it.
2634    #[cfg(any(test, feature = "test-support"))]
2635    pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
2636        let asset_id = (TypeId::of::<A>(), hash(source));
2637        self.loading_assets.contains_key(&asset_id)
2638    }
2639
2640    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
2641    ///
2642    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2643    /// time, and the results of this call will be cached
2644    pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
2645        let asset_id = (TypeId::of::<A>(), hash(source));
2646        let mut is_first = false;
2647        let task = self
2648            .loading_assets
2649            .remove(&asset_id)
2650            .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
2651            .unwrap_or_else(|| {
2652                is_first = true;
2653                let future = A::load(source.clone(), self);
2654
2655                self.background_executor().spawn(future).shared()
2656            });
2657
2658        self.loading_assets.insert(asset_id, Box::new(task.clone()));
2659
2660        (task, is_first)
2661    }
2662
2663    /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
2664    /// for elements rendered within this window.
2665    #[track_caller]
2666    pub fn focus_handle(&self) -> FocusHandle {
2667        FocusHandle::new(&self.focus_handles)
2668    }
2669
2670    /// Tell GPUI that an entity has changed and observers of it should be notified.
2671    pub fn notify(&mut self, entity_id: EntityId) {
2672        let window_invalidators = mem::take(
2673            self.window_invalidators_by_entity
2674                .entry(entity_id)
2675                .or_default(),
2676        );
2677
2678        // `window_invalidators_by_entity` is monotonic, so an entry alone
2679        // doesn't mean the window is currently rendering the entity. Filter
2680        // through `tracked_entities` to keep invalidation tight to windows
2681        // that actually display this entity right now.
2682        let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
2683            .iter()
2684            .filter(|(window_id, _)| {
2685                self.tracked_entities
2686                    .get(window_id)
2687                    .is_some_and(|set| set.contains(&entity_id))
2688            })
2689            .map(|(_, invalidator)| invalidator.clone())
2690            .collect();
2691
2692        if live_invalidators.is_empty() {
2693            if self.pending_notifications.insert(entity_id) {
2694                self.pending_effects
2695                    .push_back(Effect::Notify { emitter: entity_id });
2696            }
2697        } else {
2698            for invalidator in &live_invalidators {
2699                invalidator.invalidate_view(entity_id, self);
2700            }
2701        }
2702
2703        self.window_invalidators_by_entity
2704            .insert(entity_id, window_invalidators);
2705    }
2706
2707    /// Returns the name for this [`App`].
2708    #[cfg(any(test, feature = "test-support", debug_assertions))]
2709    pub fn get_name(&self) -> Option<&'static str> {
2710        self.name
2711    }
2712
2713    /// Returns `true` if the platform file picker supports selecting a mix of files and directories.
2714    pub fn can_select_mixed_files_and_dirs(&self) -> bool {
2715        self.platform.can_select_mixed_files_and_dirs()
2716    }
2717
2718    /// Removes an image from the sprite atlas on all windows.
2719    ///
2720    /// If the current window is being updated, it will be removed from `App.windows`, you can use `current_window` to specify the current window.
2721    /// This is a no-op if the image is not in the sprite atlas.
2722    pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
2723        // remove the texture from all other windows
2724        for window in self.windows.values_mut().flatten() {
2725            _ = window.drop_image(image.clone());
2726        }
2727
2728        // remove the texture from the current window
2729        if let Some(window) = current_window {
2730            _ = window.drop_image(image);
2731        }
2732    }
2733
2734    /// Sets the renderer for the inspector.
2735    #[cfg(any(feature = "inspector", debug_assertions))]
2736    pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
2737        self.inspector_renderer = Some(f);
2738    }
2739
2740    /// Registers a renderer specific to an inspector state.
2741    #[cfg(any(feature = "inspector", debug_assertions))]
2742    pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
2743        &mut self,
2744        f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
2745    ) {
2746        self.inspector_element_registry.register(f);
2747    }
2748
2749    /// Initializes gpui's default colors for the application.
2750    ///
2751    /// These colors can be accessed through `cx.default_colors()`.
2752    pub fn init_colors(&mut self) {
2753        self.set_global(GlobalColors(Arc::new(Colors::default())));
2754    }
2755}
2756
2757impl AppContext for App {
2758    /// Builds an entity that is owned by the application.
2759    ///
2760    /// The given function will be invoked with a [`Context`] and must return an object representing the entity. An
2761    /// [`Entity`] handle will be returned, which can be used to access the entity in a context.
2762    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
2763        self.update(|cx| {
2764            let slot = cx.entities.reserve();
2765            let handle = slot.clone();
2766            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2767
2768            cx.push_effect(Effect::EntityCreated {
2769                entity: handle.into_any(),
2770                tid: TypeId::of::<T>(),
2771                window: cx.window_update_stack.last().cloned(),
2772            });
2773
2774            cx.entities.insert(slot, entity)
2775        })
2776    }
2777
2778    fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
2779        Reservation(self.entities.reserve())
2780    }
2781
2782    fn insert_entity<T: 'static>(
2783        &mut self,
2784        reservation: Reservation<T>,
2785        build_entity: impl FnOnce(&mut Context<T>) -> T,
2786    ) -> Entity<T> {
2787        self.update(|cx| {
2788            let slot = reservation.0;
2789            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2790            cx.entities.insert(slot, entity)
2791        })
2792    }
2793
2794    /// Updates the entity referenced by the given handle. The function is passed a mutable reference to the
2795    /// entity along with a `Context` for the entity.
2796    fn update_entity<T: 'static, R>(
2797        &mut self,
2798        handle: &Entity<T>,
2799        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
2800    ) -> R {
2801        self.update(|cx| {
2802            let mut entity = cx.entities.lease(handle);
2803            let result = update(
2804                &mut entity,
2805                &mut Context::new_context(cx, handle.downgrade()),
2806            );
2807            cx.entities.end_lease(entity);
2808            result
2809        })
2810    }
2811
2812    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
2813    where
2814        T: 'static,
2815    {
2816        GpuiBorrow::new(handle.clone(), self)
2817    }
2818
2819    fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
2820    where
2821        T: 'static,
2822    {
2823        let entity = self.entities.read(handle);
2824        read(entity, self)
2825    }
2826
2827    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
2828    where
2829        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2830    {
2831        self.update_window_id(handle.id, update)
2832    }
2833
2834    fn with_window<R>(
2835        &mut self,
2836        entity_id: EntityId,
2837        f: impl FnOnce(&mut Window, &mut App) -> R,
2838    ) -> Option<R> {
2839        App::with_window(self, entity_id, f)
2840    }
2841
2842    fn read_window<T, R>(
2843        &self,
2844        window: &WindowHandle<T>,
2845        read: impl FnOnce(Entity<T>, &App) -> R,
2846    ) -> Result<R>
2847    where
2848        T: 'static,
2849    {
2850        let window = self
2851            .windows
2852            .get(window.id)
2853            .context("window not found")?
2854            .as_deref()
2855            .expect("attempted to read a window that is already on the stack");
2856
2857        let root_view = window.root.clone().unwrap();
2858        let view = root_view
2859            .downcast::<T>()
2860            .map_err(|_| anyhow!("root view's type has changed"))?;
2861
2862        Ok(read(view, self))
2863    }
2864
2865    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
2866    where
2867        R: Send + 'static,
2868    {
2869        self.background_executor.spawn(future)
2870    }
2871
2872    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
2873    where
2874        G: Global,
2875    {
2876        let mut g = self.global::<G>();
2877        callback(g, self)
2878    }
2879}
2880
2881/// These effects are processed at the end of each application update cycle.
2882pub(crate) enum Effect {
2883    Notify {
2884        emitter: EntityId,
2885    },
2886    Emit {
2887        emitter: EntityId,
2888        event_type: TypeId,
2889        event: ArenaBox<dyn Any>,
2890    },
2891    RefreshWindows,
2892    NotifyGlobalObservers {
2893        global_type: TypeId,
2894    },
2895    Defer {
2896        callback: Box<dyn FnOnce(&mut App) + 'static>,
2897    },
2898    EntityCreated {
2899        entity: AnyEntity,
2900        tid: TypeId,
2901        window: Option<WindowId>,
2902    },
2903}
2904
2905impl std::fmt::Debug for Effect {
2906    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2907        match self {
2908            Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
2909            Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
2910            Effect::RefreshWindows => write!(f, "RefreshWindows"),
2911            Effect::NotifyGlobalObservers { global_type } => {
2912                write!(f, "NotifyGlobalObservers({:?})", global_type)
2913            }
2914            Effect::Defer { .. } => write!(f, "Defer(..)"),
2915            Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
2916        }
2917    }
2918}
2919
2920/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
2921pub(crate) struct GlobalLease<G: Global> {
2922    global: Box<dyn Any>,
2923    global_type: PhantomData<G>,
2924}
2925
2926impl<G: Global> GlobalLease<G> {
2927    fn new(global: Box<dyn Any>) -> Self {
2928        GlobalLease {
2929            global,
2930            global_type: PhantomData,
2931        }
2932    }
2933}
2934
2935impl<G: Global> Deref for GlobalLease<G> {
2936    type Target = G;
2937
2938    fn deref(&self) -> &Self::Target {
2939        self.global.downcast_ref().unwrap()
2940    }
2941}
2942
2943impl<G: Global> DerefMut for GlobalLease<G> {
2944    fn deref_mut(&mut self) -> &mut Self::Target {
2945        self.global.downcast_mut().unwrap()
2946    }
2947}
2948
2949/// Contains state associated with an active drag operation, started by dragging an element
2950/// within the window or by dragging into the app from the underlying platform.
2951pub struct AnyDrag {
2952    /// The view used to render this drag
2953    pub view: AnyView,
2954
2955    /// The value of the dragged item, to be dropped
2956    pub value: Arc<dyn Any>,
2957
2958    /// This is used to render the dragged item in the same place
2959    /// on the original element that the drag was initiated
2960    pub cursor_offset: Point<Pixels>,
2961
2962    /// The cursor style to use while dragging
2963    pub cursor_style: Option<CursorStyle>,
2964
2965    /// Resolves the payload to offer the platform if the drag leaves the window.
2966    /// Invoked at most once per drag gesture, at promotion time.
2967    pub external_payload_source: Option<ExternalDragPayloadSource>,
2968}
2969
2970/// Lazily resolves the payload handed to the platform when an internal drag is
2971/// promoted to a native drag session.
2972pub type ExternalDragPayloadSource =
2973    Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
2974
2975/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
2976/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip](crate::Interactivity::tooltip).
2977#[derive(Clone)]
2978pub struct AnyTooltip {
2979    /// The view used to display the tooltip
2980    pub view: AnyView,
2981
2982    /// The absolute position of the mouse when the tooltip was deployed.
2983    pub mouse_position: Point<Pixels>,
2984
2985    /// Given the bounds of the tooltip, checks whether the tooltip should still be visible and
2986    /// updates its state accordingly. This is needed atop the hovered element's mouse move handler
2987    /// to handle the case where the element is not painted (e.g. via use of `visible_on_hover`).
2988    pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
2989}
2990
2991/// A keystroke event, and potentially the associated action
2992#[derive(Debug)]
2993pub struct KeystrokeEvent {
2994    /// The keystroke that occurred
2995    pub keystroke: Keystroke,
2996
2997    /// The action that was resolved for the keystroke, if any
2998    pub action: Option<Box<dyn Action>>,
2999
3000    /// The context stack at the time
3001    pub context_stack: Vec<KeyContext>,
3002}
3003
3004struct NullHttpClient;
3005
3006impl HttpClient for NullHttpClient {
3007    fn send(
3008        &self,
3009        _req: http_client::Request<http_client::AsyncBody>,
3010    ) -> futures::future::BoxFuture<
3011        'static,
3012        anyhow::Result<http_client::Response<http_client::AsyncBody>>,
3013    > {
3014        async move {
3015            anyhow::bail!("No HttpClient available");
3016        }
3017        .boxed()
3018    }
3019
3020    fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
3021        None
3022    }
3023
3024    fn proxy(&self) -> Option<&Url> {
3025        None
3026    }
3027}
3028
3029/// A mutable reference to an entity owned by GPUI
3030pub struct GpuiBorrow<'a, T> {
3031    inner: Option<Lease<T>>,
3032    app: &'a mut App,
3033}
3034
3035impl<'a, T: 'static> GpuiBorrow<'a, T> {
3036    fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3037        app.start_update();
3038        let lease = app.entities.lease(&inner);
3039        Self {
3040            inner: Some(lease),
3041            app,
3042        }
3043    }
3044}
3045
3046impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3047    fn borrow(&self) -> &T {
3048        self.inner.as_ref().unwrap().borrow()
3049    }
3050}
3051
3052impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3053    fn borrow_mut(&mut self) -> &mut T {
3054        self.inner.as_mut().unwrap().borrow_mut()
3055    }
3056}
3057
3058impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3059    type Target = T;
3060
3061    fn deref(&self) -> &Self::Target {
3062        self.inner.as_ref().unwrap()
3063    }
3064}
3065
3066impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3067    fn deref_mut(&mut self) -> &mut T {
3068        self.inner.as_mut().unwrap()
3069    }
3070}
3071
3072impl<'a, T> Drop for GpuiBorrow<'a, T> {
3073    fn drop(&mut self) {
3074        let lease = self.inner.take().unwrap();
3075        self.app.notify(lease.id);
3076        self.app.entities.end_lease(lease);
3077        self.app.finish_update();
3078    }
3079}
3080
3081#[cfg(test)]
3082mod test {
3083    use std::{cell::RefCell, rc::Rc};
3084
3085    use crate::{AppContext, TestAppContext};
3086
3087    #[test]
3088    fn test_gpui_borrow() {
3089        let cx = TestAppContext::single();
3090        let observation_count = Rc::new(RefCell::new(0));
3091
3092        let state = cx.update(|cx| {
3093            let state = cx.new(|_| false);
3094            cx.observe(&state, {
3095                let observation_count = observation_count.clone();
3096                move |_, _| {
3097                    let mut count = observation_count.borrow_mut();
3098                    *count += 1;
3099                }
3100            })
3101            .detach();
3102
3103            state
3104        });
3105
3106        cx.update(|cx| {
3107            // Calling this like this so that we don't clobber the borrow_mut above
3108            *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3109        });
3110
3111        cx.update(|cx| {
3112            state.write(cx, false);
3113        });
3114
3115        assert_eq!(*observation_count.borrow(), 2);
3116    }
3117}
3118
3119#[cfg(test)]
3120mod system_window_tab_tests {
3121    use super::*;
3122
3123    fn tab(cx: &mut TestAppContext, title: &'static str) -> SystemWindowTab {
3124        let handle = cx.add_window(|_, _| crate::Empty);
3125        SystemWindowTab::new(title.into(), handle.into())
3126    }
3127
3128    #[crate::test]
3129    fn replacing_removed_groups_preserves_other_windows(cx: &mut TestAppContext) {
3130        let tabs: Vec<_> = ["a", "b", "c", "d"].map(|name| tab(cx, name)).into();
3131        cx.update(|cx| {
3132            for tab in &tabs[..3] {
3133                SystemWindowTabController::add_tab(cx, tab.id, vec![tab.clone()]);
3134            }
3135            SystemWindowTabController::remove_tab(cx, tabs[1].id);
3136            SystemWindowTabController::add_tab(cx, tabs[3].id, vec![tabs[3].clone()]);
3137            let controller = cx.global::<SystemWindowTabController>();
3138            assert!(controller.tabs(tabs[0].id).is_some());
3139            assert!(controller.tabs(tabs[2].id).is_some());
3140            assert!(controller.tabs(tabs[3].id).is_some());
3141            assert_eq!(controller.tab_groups.len(), 3);
3142        });
3143    }
3144
3145    #[crate::test]
3146    fn native_tab_snapshots_are_idempotent_and_preserve_native_order(cx: &mut TestAppContext) {
3147        let a = tab(cx, "a");
3148        let b = tab(cx, "b");
3149        let c = tab(cx, "c");
3150        cx.update(|cx| {
3151            SystemWindowTabController::add_tab(cx, a.id, vec![a.clone()]);
3152            SystemWindowTabController::add_tab(cx, b.id, vec![b.clone(), a.clone()]);
3153            SystemWindowTabController::add_tab(cx, b.id, vec![b.clone(), a.clone()]);
3154            let controller = cx.global::<SystemWindowTabController>();
3155            assert_eq!(controller.tab_groups.len(), 1);
3156            assert_eq!(
3157                controller
3158                    .tabs(a.id)
3159                    .unwrap()
3160                    .iter()
3161                    .map(|tab| tab.id)
3162                    .collect::<Vec<_>>(),
3163                vec![b.id, a.id]
3164            );
3165            let previous_activity = controller.tabs(a.id).unwrap()[1].last_active_at;
3166            let mut refreshed_a = a.clone();
3167            refreshed_a.last_active_at += std::time::Duration::from_secs(1);
3168            SystemWindowTabController::add_tab(cx, c.id, vec![refreshed_a, c.clone(), c.clone()]);
3169            let controller = cx.global::<SystemWindowTabController>();
3170            assert_eq!(controller.tabs(b.id).unwrap().len(), 1);
3171            assert_eq!(
3172                controller.tabs(a.id).unwrap()[0].last_active_at,
3173                previous_activity
3174            );
3175            assert_eq!(
3176                controller
3177                    .tabs(a.id)
3178                    .unwrap()
3179                    .iter()
3180                    .map(|tab| tab.id)
3181                    .collect::<Vec<_>>(),
3182                vec![a.id, c.id]
3183            );
3184        });
3185    }
3186
3187    #[crate::test]
3188    fn group_navigation_and_merge_follow_stable_group_order(cx: &mut TestAppContext) {
3189        let tabs: Vec<_> = ["a", "b", "c", "d"].map(|name| tab(cx, name)).into();
3190        cx.update(|cx| {
3191            for tab in &tabs {
3192                SystemWindowTabController::add_tab(cx, tab.id, vec![tab.clone()]);
3193            }
3194            for index in 0..tabs.len() {
3195                assert_eq!(
3196                    SystemWindowTabController::get_next_tab_group_window(cx, tabs[index].id)
3197                        .unwrap()
3198                        .window_id(),
3199                    tabs[(index + 1) % tabs.len()].id
3200                );
3201                assert_eq!(
3202                    SystemWindowTabController::get_prev_tab_group_window(cx, tabs[index].id)
3203                        .unwrap()
3204                        .window_id(),
3205                    tabs[(index + tabs.len() - 1) % tabs.len()].id
3206                );
3207            }
3208            SystemWindowTabController::merge_all_windows(cx, tabs[2].id);
3209            assert_eq!(
3210                cx.global::<SystemWindowTabController>()
3211                    .tabs(tabs[2].id)
3212                    .unwrap()
3213                    .iter()
3214                    .map(|tab| tab.id)
3215                    .collect::<Vec<_>>(),
3216                vec![tabs[2].id, tabs[0].id, tabs[1].id, tabs[3].id]
3217            );
3218        });
3219    }
3220}