Skip to main content

gpui_authoring/
app.rs

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