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