app.rs

   1use std::{
   2    any::{type_name, TypeId},
   3    cell::{Ref, RefCell, RefMut},
   4    marker::PhantomData,
   5    ops::{Deref, DerefMut},
   6    path::{Path, PathBuf},
   7    rc::{Rc, Weak},
   8    sync::{atomic::Ordering::SeqCst, Arc},
   9    time::Duration,
  10};
  11
  12use anyhow::{anyhow, Result};
  13use derive_more::{Deref, DerefMut};
  14use futures::{
  15    channel::oneshot,
  16    future::{LocalBoxFuture, Shared},
  17    Future, FutureExt,
  18};
  19use slotmap::SlotMap;
  20
  21pub use async_context::*;
  22use collections::{FxHashMap, FxHashSet, VecDeque};
  23pub use entity_map::*;
  24use http_client::HttpClient;
  25pub use model_context::*;
  26#[cfg(any(test, feature = "test-support"))]
  27pub use test_context::*;
  28use util::ResultExt;
  29
  30use crate::{
  31    current_platform, hash, init_app_menus, Action, ActionRegistry, Any, AnyView, AnyWindowHandle,
  32    Asset, AssetSource, BackgroundExecutor, ClipboardItem, Context, DispatchPhase, DisplayId,
  33    Entity, EventEmitter, ForegroundExecutor, Global, KeyBinding, Keymap, Keystroke, LayoutId,
  34    Menu, MenuItem, OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay, Point,
  35    PromptBuilder, PromptHandle, PromptLevel, Render, RenderablePromptHandle, Reservation,
  36    ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer, Task, TextSystem,
  37    View, ViewContext, Window, WindowAppearance, WindowContext, WindowHandle, WindowId,
  38};
  39
  40mod async_context;
  41mod entity_map;
  42mod model_context;
  43#[cfg(any(test, feature = "test-support"))]
  44mod test_context;
  45
  46/// The duration for which futures returned from [AppContext::on_app_context] or [ModelContext::on_app_quit] can run before the application fully quits.
  47pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(100);
  48
  49/// Temporary(?) wrapper around [`RefCell<AppContext>`] to help us debug any double borrows.
  50/// Strongly consider removing after stabilization.
  51#[doc(hidden)]
  52pub struct AppCell {
  53    app: RefCell<AppContext>,
  54}
  55
  56impl AppCell {
  57    #[doc(hidden)]
  58    #[track_caller]
  59    pub fn borrow(&self) -> AppRef {
  60        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  61            let thread_id = std::thread::current().id();
  62            eprintln!("borrowed {thread_id:?}");
  63        }
  64        AppRef(self.app.borrow())
  65    }
  66
  67    #[doc(hidden)]
  68    #[track_caller]
  69    pub fn borrow_mut(&self) -> AppRefMut {
  70        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  71            let thread_id = std::thread::current().id();
  72            eprintln!("borrowed {thread_id:?}");
  73        }
  74        AppRefMut(self.app.borrow_mut())
  75    }
  76}
  77
  78#[doc(hidden)]
  79#[derive(Deref, DerefMut)]
  80pub struct AppRef<'a>(Ref<'a, AppContext>);
  81
  82impl<'a> Drop for AppRef<'a> {
  83    fn drop(&mut self) {
  84        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  85            let thread_id = std::thread::current().id();
  86            eprintln!("dropped borrow from {thread_id:?}");
  87        }
  88    }
  89}
  90
  91#[doc(hidden)]
  92#[derive(Deref, DerefMut)]
  93pub struct AppRefMut<'a>(RefMut<'a, AppContext>);
  94
  95impl<'a> Drop for AppRefMut<'a> {
  96    fn drop(&mut self) {
  97        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  98            let thread_id = std::thread::current().id();
  99            eprintln!("dropped {thread_id:?}");
 100        }
 101    }
 102}
 103
 104/// A reference to a GPUI application, typically constructed in the `main` function of your app.
 105/// You won't interact with this type much outside of initial configuration and startup.
 106pub struct App(Rc<AppCell>);
 107
 108/// Represents an application before it is fully launched. Once your app is
 109/// configured, you'll start the app with `App::run`.
 110impl App {
 111    /// Builds an app with the given asset source.
 112    #[allow(clippy::new_without_default)]
 113    pub fn new() -> Self {
 114        #[cfg(any(test, feature = "test-support"))]
 115        log::info!("GPUI was compiled in test mode");
 116
 117        Self(AppContext::new(
 118            current_platform(false),
 119            Arc::new(()),
 120            Arc::new(NullHttpClient),
 121        ))
 122    }
 123
 124    /// Build an app in headless mode. This prevents opening windows,
 125    /// but makes it possible to run an application in an context like
 126    /// SSH, where GUI applications are not allowed.
 127    pub fn headless() -> Self {
 128        Self(AppContext::new(
 129            current_platform(true),
 130            Arc::new(()),
 131            Arc::new(NullHttpClient),
 132        ))
 133    }
 134
 135    /// Assign
 136    pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
 137        let mut context_lock = self.0.borrow_mut();
 138        let asset_source = Arc::new(asset_source);
 139        context_lock.asset_source = asset_source.clone();
 140        context_lock.svg_renderer = SvgRenderer::new(asset_source);
 141        drop(context_lock);
 142        self
 143    }
 144
 145    /// Set the http client for the application
 146    pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
 147        let mut context_lock = self.0.borrow_mut();
 148        context_lock.http_client = http_client;
 149        drop(context_lock);
 150        self
 151    }
 152
 153    /// Start the application. The provided callback will be called once the
 154    /// app is fully launched.
 155    pub fn run<F>(self, on_finish_launching: F)
 156    where
 157        F: 'static + FnOnce(&mut AppContext),
 158    {
 159        let this = self.0.clone();
 160        let platform = self.0.borrow().platform.clone();
 161        platform.run(Box::new(move || {
 162            let cx = &mut *this.borrow_mut();
 163            on_finish_launching(cx);
 164        }));
 165    }
 166
 167    /// Register a handler to be invoked when the platform instructs the application
 168    /// to open one or more URLs.
 169    pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
 170    where
 171        F: 'static + FnMut(Vec<String>),
 172    {
 173        self.0.borrow().platform.on_open_urls(Box::new(callback));
 174        self
 175    }
 176
 177    /// Invokes a handler when an already-running application is launched.
 178    /// On macOS, this can occur when the application icon is double-clicked or the app is launched via the dock.
 179    pub fn on_reopen<F>(&self, mut callback: F) -> &Self
 180    where
 181        F: 'static + FnMut(&mut AppContext),
 182    {
 183        let this = Rc::downgrade(&self.0);
 184        self.0.borrow_mut().platform.on_reopen(Box::new(move || {
 185            if let Some(app) = this.upgrade() {
 186                callback(&mut app.borrow_mut());
 187            }
 188        }));
 189        self
 190    }
 191
 192    /// Returns a handle to the [`BackgroundExecutor`] associated with this app, which can be used to spawn futures in the background.
 193    pub fn background_executor(&self) -> BackgroundExecutor {
 194        self.0.borrow().background_executor.clone()
 195    }
 196
 197    /// Returns a handle to the [`ForegroundExecutor`] associated with this app, which can be used to spawn futures in the foreground.
 198    pub fn foreground_executor(&self) -> ForegroundExecutor {
 199        self.0.borrow().foreground_executor.clone()
 200    }
 201
 202    /// Returns a reference to the [`TextSystem`] associated with this app.
 203    pub fn text_system(&self) -> Arc<TextSystem> {
 204        self.0.borrow().text_system.clone()
 205    }
 206
 207    /// Returns the file URL of the executable with the specified name in the application bundle
 208    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 209        self.0.borrow().path_for_auxiliary_executable(name)
 210    }
 211}
 212
 213type Handler = Box<dyn FnMut(&mut AppContext) -> bool + 'static>;
 214type Listener = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool + 'static>;
 215pub(crate) type KeystrokeObserver =
 216    Box<dyn FnMut(&KeystrokeEvent, &mut WindowContext) -> bool + 'static>;
 217type QuitHandler = Box<dyn FnOnce(&mut AppContext) -> LocalBoxFuture<'static, ()> + 'static>;
 218type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut AppContext) + 'static>;
 219type NewViewListener = Box<dyn FnMut(AnyView, &mut WindowContext) + 'static>;
 220type NewModelListener = Box<dyn FnMut(AnyModel, &mut AppContext) + 'static>;
 221
 222/// Contains the state of the full application, and passed as a reference to a variety of callbacks.
 223/// Other contexts such as [ModelContext], [WindowContext], and [ViewContext] deref to this type, making it the most general context type.
 224/// You need a reference to an `AppContext` to access the state of a [Model].
 225pub struct AppContext {
 226    pub(crate) this: Weak<AppCell>,
 227    pub(crate) platform: Rc<dyn Platform>,
 228    text_system: Arc<TextSystem>,
 229    flushing_effects: bool,
 230    pending_updates: usize,
 231    pub(crate) actions: Rc<ActionRegistry>,
 232    pub(crate) active_drag: Option<AnyDrag>,
 233    pub(crate) background_executor: BackgroundExecutor,
 234    pub(crate) foreground_executor: ForegroundExecutor,
 235    pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
 236    asset_source: Arc<dyn AssetSource>,
 237    pub(crate) svg_renderer: SvgRenderer,
 238    http_client: Arc<dyn HttpClient>,
 239    pub(crate) globals_by_type: FxHashMap<TypeId, Box<dyn Any>>,
 240    pub(crate) entities: EntityMap,
 241    pub(crate) new_model_observers: SubscriberSet<TypeId, NewModelListener>,
 242    pub(crate) new_view_observers: SubscriberSet<TypeId, NewViewListener>,
 243    pub(crate) windows: SlotMap<WindowId, Option<Window>>,
 244    pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
 245    pub(crate) keymap: Rc<RefCell<Keymap>>,
 246    pub(crate) keyboard_layout: SharedString,
 247    pub(crate) global_action_listeners:
 248        FxHashMap<TypeId, Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
 249    pending_effects: VecDeque<Effect>,
 250    pub(crate) pending_notifications: FxHashSet<EntityId>,
 251    pub(crate) pending_global_notifications: FxHashSet<TypeId>,
 252    pub(crate) observers: SubscriberSet<EntityId, Handler>,
 253    // TypeId is the type of the event that the listener callback expects
 254    pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
 255    pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
 256    pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
 257    pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
 258    pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
 259    pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
 260    pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
 261    pub(crate) propagate_event: bool,
 262    pub(crate) prompt_builder: Option<PromptBuilder>,
 263
 264    #[cfg(any(test, feature = "test-support", debug_assertions))]
 265    pub(crate) name: Option<&'static str>,
 266}
 267
 268impl AppContext {
 269    #[allow(clippy::new_ret_no_self)]
 270    pub(crate) fn new(
 271        platform: Rc<dyn Platform>,
 272        asset_source: Arc<dyn AssetSource>,
 273        http_client: Arc<dyn HttpClient>,
 274    ) -> Rc<AppCell> {
 275        let executor = platform.background_executor();
 276        let foreground_executor = platform.foreground_executor();
 277        assert!(
 278            executor.is_main_thread(),
 279            "must construct App on main thread"
 280        );
 281
 282        let text_system = Arc::new(TextSystem::new(platform.text_system()));
 283        let entities = EntityMap::new();
 284        let keyboard_layout = SharedString::from(platform.keyboard_layout());
 285
 286        let app = Rc::new_cyclic(|this| AppCell {
 287            app: RefCell::new(AppContext {
 288                this: this.clone(),
 289                platform: platform.clone(),
 290                text_system,
 291                actions: Rc::new(ActionRegistry::default()),
 292                flushing_effects: false,
 293                pending_updates: 0,
 294                active_drag: None,
 295                background_executor: executor,
 296                foreground_executor,
 297                svg_renderer: SvgRenderer::new(asset_source.clone()),
 298                loading_assets: Default::default(),
 299                asset_source,
 300                http_client,
 301                globals_by_type: FxHashMap::default(),
 302                entities,
 303                new_view_observers: SubscriberSet::new(),
 304                new_model_observers: SubscriberSet::new(),
 305                window_handles: FxHashMap::default(),
 306                windows: SlotMap::with_key(),
 307                keymap: Rc::new(RefCell::new(Keymap::default())),
 308                keyboard_layout,
 309                global_action_listeners: FxHashMap::default(),
 310                pending_effects: VecDeque::new(),
 311                pending_notifications: FxHashSet::default(),
 312                pending_global_notifications: FxHashSet::default(),
 313                observers: SubscriberSet::new(),
 314                event_listeners: SubscriberSet::new(),
 315                release_listeners: SubscriberSet::new(),
 316                keystroke_observers: SubscriberSet::new(),
 317                keyboard_layout_observers: SubscriberSet::new(),
 318                global_observers: SubscriberSet::new(),
 319                quit_observers: SubscriberSet::new(),
 320                layout_id_buffer: Default::default(),
 321                propagate_event: true,
 322                prompt_builder: Some(PromptBuilder::Default),
 323
 324                #[cfg(any(test, feature = "test-support", debug_assertions))]
 325                name: None,
 326            }),
 327        });
 328
 329        init_app_menus(platform.as_ref(), &mut app.borrow_mut());
 330
 331        platform.on_keyboard_layout_change(Box::new({
 332            let app = Rc::downgrade(&app);
 333            move || {
 334                if let Some(app) = app.upgrade() {
 335                    let cx = &mut app.borrow_mut();
 336                    cx.keyboard_layout = SharedString::from(cx.platform.keyboard_layout());
 337                    cx.keyboard_layout_observers
 338                        .clone()
 339                        .retain(&(), move |callback| (callback)(cx));
 340                }
 341            }
 342        }));
 343
 344        platform.on_quit(Box::new({
 345            let cx = app.clone();
 346            move || {
 347                cx.borrow_mut().shutdown();
 348            }
 349        }));
 350
 351        app
 352    }
 353
 354    /// Quit the application gracefully. Handlers registered with [`ModelContext::on_app_quit`]
 355    /// will be given 100ms to complete before exiting.
 356    pub fn shutdown(&mut self) {
 357        let mut futures = Vec::new();
 358
 359        for observer in self.quit_observers.remove(&()) {
 360            futures.push(observer(self));
 361        }
 362
 363        self.windows.clear();
 364        self.window_handles.clear();
 365        self.flush_effects();
 366
 367        let futures = futures::future::join_all(futures);
 368        if self
 369            .background_executor
 370            .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
 371            .is_err()
 372        {
 373            log::error!("timed out waiting on app_will_quit");
 374        }
 375    }
 376
 377    /// Get the id of the current keyboard layout
 378    pub fn keyboard_layout(&self) -> &SharedString {
 379        &self.keyboard_layout
 380    }
 381
 382    /// Invokes a handler when the current keyboard layout changes
 383    pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
 384    where
 385        F: 'static + FnMut(&mut AppContext),
 386    {
 387        let (subscription, activate) = self.keyboard_layout_observers.insert(
 388            (),
 389            Box::new(move |cx| {
 390                callback(cx);
 391                true
 392            }),
 393        );
 394        activate();
 395        subscription
 396    }
 397
 398    /// Gracefully quit the application via the platform's standard routine.
 399    pub fn quit(&self) {
 400        self.platform.quit();
 401    }
 402
 403    /// Schedules all windows in the application to be redrawn. This can be called
 404    /// multiple times in an update cycle and still result in a single redraw.
 405    pub fn refresh(&mut self) {
 406        self.pending_effects.push_back(Effect::Refresh);
 407    }
 408
 409    pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
 410        self.pending_updates += 1;
 411        let result = update(self);
 412        if !self.flushing_effects && self.pending_updates == 1 {
 413            self.flushing_effects = true;
 414            self.flush_effects();
 415            self.flushing_effects = false;
 416        }
 417        self.pending_updates -= 1;
 418        result
 419    }
 420
 421    /// Arrange a callback to be invoked when the given model or view calls `notify` on its respective context.
 422    pub fn observe<W, E>(
 423        &mut self,
 424        entity: &E,
 425        mut on_notify: impl FnMut(E, &mut AppContext) + 'static,
 426    ) -> Subscription
 427    where
 428        W: 'static,
 429        E: Entity<W>,
 430    {
 431        self.observe_internal(entity, move |e, cx| {
 432            on_notify(e, cx);
 433            true
 434        })
 435    }
 436
 437    pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
 438        let (subscription, activate) = self.observers.insert(key, value);
 439        self.defer(move |_| activate());
 440        subscription
 441    }
 442    pub(crate) fn observe_internal<W, E>(
 443        &mut self,
 444        entity: &E,
 445        mut on_notify: impl FnMut(E, &mut AppContext) -> bool + 'static,
 446    ) -> Subscription
 447    where
 448        W: 'static,
 449        E: Entity<W>,
 450    {
 451        let entity_id = entity.entity_id();
 452        let handle = entity.downgrade();
 453        self.new_observer(
 454            entity_id,
 455            Box::new(move |cx| {
 456                if let Some(handle) = E::upgrade_from(&handle) {
 457                    on_notify(handle, cx)
 458                } else {
 459                    false
 460                }
 461            }),
 462        )
 463    }
 464
 465    /// Arrange for the given callback to be invoked whenever the given model or view emits an event of a given type.
 466    /// The callback is provided a handle to the emitting entity and a reference to the emitted event.
 467    pub fn subscribe<T, E, Event>(
 468        &mut self,
 469        entity: &E,
 470        mut on_event: impl FnMut(E, &Event, &mut AppContext) + 'static,
 471    ) -> Subscription
 472    where
 473        T: 'static + EventEmitter<Event>,
 474        E: Entity<T>,
 475        Event: 'static,
 476    {
 477        self.subscribe_internal(entity, move |entity, event, cx| {
 478            on_event(entity, event, cx);
 479            true
 480        })
 481    }
 482
 483    pub(crate) fn new_subscription(
 484        &mut self,
 485        key: EntityId,
 486        value: (TypeId, Listener),
 487    ) -> Subscription {
 488        let (subscription, activate) = self.event_listeners.insert(key, value);
 489        self.defer(move |_| activate());
 490        subscription
 491    }
 492    pub(crate) fn subscribe_internal<T, E, Evt>(
 493        &mut self,
 494        entity: &E,
 495        mut on_event: impl FnMut(E, &Evt, &mut AppContext) -> bool + 'static,
 496    ) -> Subscription
 497    where
 498        T: 'static + EventEmitter<Evt>,
 499        E: Entity<T>,
 500        Evt: 'static,
 501    {
 502        let entity_id = entity.entity_id();
 503        let entity = entity.downgrade();
 504        self.new_subscription(
 505            entity_id,
 506            (
 507                TypeId::of::<Evt>(),
 508                Box::new(move |event, cx| {
 509                    let event: &Evt = event.downcast_ref().expect("invalid event type");
 510                    if let Some(handle) = E::upgrade_from(&entity) {
 511                        on_event(handle, event, cx)
 512                    } else {
 513                        false
 514                    }
 515                }),
 516            ),
 517        )
 518    }
 519
 520    /// Returns handles to all open windows in the application.
 521    /// Each handle could be downcast to a handle typed for the root view of that window.
 522    /// To find all windows of a given type, you could filter on
 523    pub fn windows(&self) -> Vec<AnyWindowHandle> {
 524        self.windows
 525            .keys()
 526            .flat_map(|window_id| self.window_handles.get(&window_id).copied())
 527            .collect()
 528    }
 529
 530    /// Returns the window handles ordered by their appearance on screen, front to back.
 531    ///
 532    /// The first window in the returned list is the active/topmost window of the application.
 533    ///
 534    /// This method returns None if the platform doesn't implement the method yet.
 535    pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
 536        self.platform.window_stack()
 537    }
 538
 539    /// Returns a handle to the window that is currently focused at the platform level, if one exists.
 540    pub fn active_window(&self) -> Option<AnyWindowHandle> {
 541        self.platform.active_window()
 542    }
 543
 544    /// Opens a new window with the given option and the root view returned by the given function.
 545    /// The function is invoked with a `WindowContext`, which can be used to interact with window-specific
 546    /// functionality.
 547    pub fn open_window<V: 'static + Render>(
 548        &mut self,
 549        options: crate::WindowOptions,
 550        build_root_view: impl FnOnce(&mut WindowContext) -> View<V>,
 551    ) -> anyhow::Result<WindowHandle<V>> {
 552        self.update(|cx| {
 553            let id = cx.windows.insert(None);
 554            let handle = WindowHandle::new(id);
 555            match Window::new(handle.into(), options, cx) {
 556                Ok(mut window) => {
 557                    let root_view = build_root_view(&mut WindowContext::new(cx, &mut window));
 558                    window.root_view.replace(root_view.into());
 559                    WindowContext::new(cx, &mut window).defer(|cx| cx.appearance_changed());
 560                    cx.window_handles.insert(id, window.handle);
 561                    cx.windows.get_mut(id).unwrap().replace(window);
 562                    Ok(handle)
 563                }
 564                Err(e) => {
 565                    cx.windows.remove(id);
 566                    Err(e)
 567                }
 568            }
 569        })
 570    }
 571
 572    /// Instructs the platform to activate the application by bringing it to the foreground.
 573    pub fn activate(&self, ignoring_other_apps: bool) {
 574        self.platform.activate(ignoring_other_apps);
 575    }
 576
 577    /// Hide the application at the platform level.
 578    pub fn hide(&self) {
 579        self.platform.hide();
 580    }
 581
 582    /// Hide other applications at the platform level.
 583    pub fn hide_other_apps(&self) {
 584        self.platform.hide_other_apps();
 585    }
 586
 587    /// Unhide other applications at the platform level.
 588    pub fn unhide_other_apps(&self) {
 589        self.platform.unhide_other_apps();
 590    }
 591
 592    /// Returns the list of currently active displays.
 593    pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 594        self.platform.displays()
 595    }
 596
 597    /// Returns the primary display that will be used for new windows.
 598    pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 599        self.platform.primary_display()
 600    }
 601
 602    /// Returns a list of available screen capture sources.
 603    pub fn screen_capture_sources(
 604        &self,
 605    ) -> oneshot::Receiver<Result<Vec<Box<dyn ScreenCaptureSource>>>> {
 606        self.platform.screen_capture_sources()
 607    }
 608
 609    /// Returns the display with the given ID, if one exists.
 610    pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
 611        self.displays()
 612            .iter()
 613            .find(|display| display.id() == id)
 614            .cloned()
 615    }
 616
 617    /// Returns the appearance of the application's windows.
 618    pub fn window_appearance(&self) -> WindowAppearance {
 619        self.platform.window_appearance()
 620    }
 621
 622    /// Writes data to the primary selection buffer.
 623    /// Only available on Linux.
 624    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 625    pub fn write_to_primary(&self, item: ClipboardItem) {
 626        self.platform.write_to_primary(item)
 627    }
 628
 629    /// Writes data to the platform clipboard.
 630    pub fn write_to_clipboard(&self, item: ClipboardItem) {
 631        self.platform.write_to_clipboard(item)
 632    }
 633
 634    /// Reads data from the primary selection buffer.
 635    /// Only available on Linux.
 636    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 637    pub fn read_from_primary(&self) -> Option<ClipboardItem> {
 638        self.platform.read_from_primary()
 639    }
 640
 641    /// Reads data from the platform clipboard.
 642    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
 643        self.platform.read_from_clipboard()
 644    }
 645
 646    /// Writes credentials to the platform keychain.
 647    pub fn write_credentials(
 648        &self,
 649        url: &str,
 650        username: &str,
 651        password: &[u8],
 652    ) -> Task<Result<()>> {
 653        self.platform.write_credentials(url, username, password)
 654    }
 655
 656    /// Reads credentials from the platform keychain.
 657    pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
 658        self.platform.read_credentials(url)
 659    }
 660
 661    /// Deletes credentials from the platform keychain.
 662    pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
 663        self.platform.delete_credentials(url)
 664    }
 665
 666    /// Directs the platform's default browser to open the given URL.
 667    pub fn open_url(&self, url: &str) {
 668        self.platform.open_url(url);
 669    }
 670
 671    /// register_url_scheme requests that the given scheme (e.g. `zed` for `zed://` urls)
 672    /// is opened by the current app.
 673    /// On some platforms (e.g. macOS) you may be able to register URL schemes as part of app
 674    /// distribution, but this method exists to let you register schemes at runtime.
 675    pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
 676        self.platform.register_url_scheme(scheme)
 677    }
 678
 679    /// Returns the full pathname of the current app bundle.
 680    /// If the app is not being run from a bundle, returns an error.
 681    pub fn app_path(&self) -> Result<PathBuf> {
 682        self.platform.app_path()
 683    }
 684
 685    /// On Linux, returns the name of the compositor in use.
 686    /// Is blank on other platforms.
 687    pub fn compositor_name(&self) -> &'static str {
 688        self.platform.compositor_name()
 689    }
 690
 691    /// Returns the file URL of the executable with the specified name in the application bundle
 692    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 693        self.platform.path_for_auxiliary_executable(name)
 694    }
 695
 696    /// Displays a platform modal for selecting paths.
 697    /// When one or more paths are selected, they'll be relayed asynchronously via the returned oneshot channel.
 698    /// If cancelled, a `None` will be relayed instead.
 699    /// May return an error on Linux if the file picker couldn't be opened.
 700    pub fn prompt_for_paths(
 701        &self,
 702        options: PathPromptOptions,
 703    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
 704        self.platform.prompt_for_paths(options)
 705    }
 706
 707    /// Displays a platform modal for selecting a new path where a file can be saved.
 708    /// The provided directory will be used to set the initial location.
 709    /// When a path is selected, it is relayed asynchronously via the returned oneshot channel.
 710    /// If cancelled, a `None` will be relayed instead.
 711    /// May return an error on Linux if the file picker couldn't be opened.
 712    pub fn prompt_for_new_path(
 713        &self,
 714        directory: &Path,
 715    ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
 716        self.platform.prompt_for_new_path(directory)
 717    }
 718
 719    /// Reveals the specified path at the platform level, such as in Finder on macOS.
 720    pub fn reveal_path(&self, path: &Path) {
 721        self.platform.reveal_path(path)
 722    }
 723
 724    /// Opens the specified path with the system's default application.
 725    pub fn open_with_system(&self, path: &Path) {
 726        self.platform.open_with_system(path)
 727    }
 728
 729    /// Returns whether the user has configured scrollbars to auto-hide at the platform level.
 730    pub fn should_auto_hide_scrollbars(&self) -> bool {
 731        self.platform.should_auto_hide_scrollbars()
 732    }
 733
 734    /// Restart the application.
 735    pub fn restart(&self, binary_path: Option<PathBuf>) {
 736        self.platform.restart(binary_path)
 737    }
 738
 739    /// Updates the http client assigned to GPUI
 740    pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
 741        self.http_client = new_client;
 742    }
 743
 744    /// Returns the http client assigned to GPUI
 745    pub fn http_client(&self) -> Arc<dyn HttpClient> {
 746        self.http_client.clone()
 747    }
 748
 749    /// Returns the SVG renderer GPUI uses
 750    pub fn svg_renderer(&self) -> SvgRenderer {
 751        self.svg_renderer.clone()
 752    }
 753
 754    pub(crate) fn push_effect(&mut self, effect: Effect) {
 755        match &effect {
 756            Effect::Notify { emitter } => {
 757                if !self.pending_notifications.insert(*emitter) {
 758                    return;
 759                }
 760            }
 761            Effect::NotifyGlobalObservers { global_type } => {
 762                if !self.pending_global_notifications.insert(*global_type) {
 763                    return;
 764                }
 765            }
 766            _ => {}
 767        };
 768
 769        self.pending_effects.push_back(effect);
 770    }
 771
 772    /// Called at the end of [`AppContext::update`] to complete any side effects
 773    /// such as notifying observers, emitting events, etc. Effects can themselves
 774    /// cause effects, so we continue looping until all effects are processed.
 775    fn flush_effects(&mut self) {
 776        loop {
 777            self.release_dropped_entities();
 778            self.release_dropped_focus_handles();
 779
 780            if let Some(effect) = self.pending_effects.pop_front() {
 781                match effect {
 782                    Effect::Notify { emitter } => {
 783                        self.apply_notify_effect(emitter);
 784                    }
 785
 786                    Effect::Emit {
 787                        emitter,
 788                        event_type,
 789                        event,
 790                    } => self.apply_emit_effect(emitter, event_type, event),
 791
 792                    Effect::Refresh => {
 793                        self.apply_refresh_effect();
 794                    }
 795
 796                    Effect::NotifyGlobalObservers { global_type } => {
 797                        self.apply_notify_global_observers_effect(global_type);
 798                    }
 799
 800                    Effect::Defer { callback } => {
 801                        self.apply_defer_effect(callback);
 802                    }
 803                }
 804            } else {
 805                #[cfg(any(test, feature = "test-support"))]
 806                for window in self
 807                    .windows
 808                    .values()
 809                    .filter_map(|window| {
 810                        let window = window.as_ref()?;
 811                        window.dirty.get().then_some(window.handle)
 812                    })
 813                    .collect::<Vec<_>>()
 814                {
 815                    self.update_window(window, |_, cx| cx.draw()).unwrap();
 816                }
 817
 818                if self.pending_effects.is_empty() {
 819                    break;
 820                }
 821            }
 822        }
 823    }
 824
 825    /// Repeatedly called during `flush_effects` to release any entities whose
 826    /// reference count has become zero. We invoke any release observers before dropping
 827    /// each entity.
 828    fn release_dropped_entities(&mut self) {
 829        loop {
 830            let dropped = self.entities.take_dropped();
 831            if dropped.is_empty() {
 832                break;
 833            }
 834
 835            for (entity_id, mut entity) in dropped {
 836                self.observers.remove(&entity_id);
 837                self.event_listeners.remove(&entity_id);
 838                for release_callback in self.release_listeners.remove(&entity_id) {
 839                    release_callback(entity.as_mut(), self);
 840                }
 841            }
 842        }
 843    }
 844
 845    /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
 846    fn release_dropped_focus_handles(&mut self) {
 847        for window_handle in self.windows() {
 848            window_handle
 849                .update(self, |_, cx| {
 850                    let mut blur_window = false;
 851                    let focus = cx.window.focus;
 852                    cx.window.focus_handles.write().retain(|handle_id, count| {
 853                        if count.load(SeqCst) == 0 {
 854                            if focus == Some(handle_id) {
 855                                blur_window = true;
 856                            }
 857                            false
 858                        } else {
 859                            true
 860                        }
 861                    });
 862
 863                    if blur_window {
 864                        cx.blur();
 865                    }
 866                })
 867                .unwrap();
 868        }
 869    }
 870
 871    fn apply_notify_effect(&mut self, emitter: EntityId) {
 872        self.pending_notifications.remove(&emitter);
 873
 874        self.observers
 875            .clone()
 876            .retain(&emitter, |handler| handler(self));
 877    }
 878
 879    fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
 880        self.event_listeners
 881            .clone()
 882            .retain(&emitter, |(stored_type, handler)| {
 883                if *stored_type == event_type {
 884                    handler(event.as_ref(), self)
 885                } else {
 886                    true
 887                }
 888            });
 889    }
 890
 891    fn apply_refresh_effect(&mut self) {
 892        for window in self.windows.values_mut() {
 893            if let Some(window) = window.as_mut() {
 894                window.dirty.set(true);
 895            }
 896        }
 897    }
 898
 899    fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
 900        self.pending_global_notifications.remove(&type_id);
 901        self.global_observers
 902            .clone()
 903            .retain(&type_id, |observer| observer(self));
 904    }
 905
 906    fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
 907        callback(self);
 908    }
 909
 910    /// Creates an `AsyncAppContext`, which can be cloned and has a static lifetime
 911    /// so it can be held across `await` points.
 912    pub fn to_async(&self) -> AsyncAppContext {
 913        AsyncAppContext {
 914            app: self.this.clone(),
 915            background_executor: self.background_executor.clone(),
 916            foreground_executor: self.foreground_executor.clone(),
 917        }
 918    }
 919
 920    /// Obtains a reference to the executor, which can be used to spawn futures.
 921    pub fn background_executor(&self) -> &BackgroundExecutor {
 922        &self.background_executor
 923    }
 924
 925    /// Obtains a reference to the executor, which can be used to spawn futures.
 926    pub fn foreground_executor(&self) -> &ForegroundExecutor {
 927        &self.foreground_executor
 928    }
 929
 930    /// Spawns the future returned by the given function on the thread pool. The closure will be invoked
 931    /// with [AsyncAppContext], which allows the application state to be accessed across await points.
 932    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
 933    where
 934        Fut: Future<Output = R> + 'static,
 935        R: 'static,
 936    {
 937        self.foreground_executor.spawn(f(self.to_async()))
 938    }
 939
 940    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
 941    /// that are currently on the stack to be returned to the app.
 942    pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static) {
 943        self.push_effect(Effect::Defer {
 944            callback: Box::new(f),
 945        });
 946    }
 947
 948    /// Accessor for the application's asset source, which is provided when constructing the `App`.
 949    pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
 950        &self.asset_source
 951    }
 952
 953    /// Accessor for the text system.
 954    pub fn text_system(&self) -> &Arc<TextSystem> {
 955        &self.text_system
 956    }
 957
 958    /// Check whether a global of the given type has been assigned.
 959    pub fn has_global<G: Global>(&self) -> bool {
 960        self.globals_by_type.contains_key(&TypeId::of::<G>())
 961    }
 962
 963    /// Access the global of the given type. Panics if a global for that type has not been assigned.
 964    #[track_caller]
 965    pub fn global<G: Global>(&self) -> &G {
 966        self.globals_by_type
 967            .get(&TypeId::of::<G>())
 968            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
 969            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
 970            .unwrap()
 971    }
 972
 973    /// Access the global of the given type if a value has been assigned.
 974    pub fn try_global<G: Global>(&self) -> Option<&G> {
 975        self.globals_by_type
 976            .get(&TypeId::of::<G>())
 977            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
 978    }
 979
 980    /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
 981    #[track_caller]
 982    pub fn global_mut<G: Global>(&mut self) -> &mut G {
 983        let global_type = TypeId::of::<G>();
 984        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 985        self.globals_by_type
 986            .get_mut(&global_type)
 987            .and_then(|any_state| any_state.downcast_mut::<G>())
 988            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
 989            .unwrap()
 990    }
 991
 992    /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
 993    /// yet been assigned.
 994    pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
 995        let global_type = TypeId::of::<G>();
 996        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 997        self.globals_by_type
 998            .entry(global_type)
 999            .or_insert_with(|| Box::<G>::default())
1000            .downcast_mut::<G>()
1001            .unwrap()
1002    }
1003
1004    /// Sets the value of the global of the given type.
1005    pub fn set_global<G: Global>(&mut self, global: G) {
1006        let global_type = TypeId::of::<G>();
1007        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1008        self.globals_by_type.insert(global_type, Box::new(global));
1009    }
1010
1011    /// Clear all stored globals. Does not notify global observers.
1012    #[cfg(any(test, feature = "test-support"))]
1013    pub fn clear_globals(&mut self) {
1014        self.globals_by_type.drain();
1015    }
1016
1017    /// Remove the global of the given type from the app context. Does not notify global observers.
1018    pub fn remove_global<G: Global>(&mut self) -> G {
1019        let global_type = TypeId::of::<G>();
1020        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1021        *self
1022            .globals_by_type
1023            .remove(&global_type)
1024            .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
1025            .downcast()
1026            .unwrap()
1027    }
1028
1029    /// Register a callback to be invoked when a global of the given type is updated.
1030    pub fn observe_global<G: Global>(
1031        &mut self,
1032        mut f: impl FnMut(&mut Self) + 'static,
1033    ) -> Subscription {
1034        let (subscription, activate) = self.global_observers.insert(
1035            TypeId::of::<G>(),
1036            Box::new(move |cx| {
1037                f(cx);
1038                true
1039            }),
1040        );
1041        self.defer(move |_| activate());
1042        subscription
1043    }
1044
1045    /// Move the global of the given type to the stack.
1046    #[track_caller]
1047    pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
1048        GlobalLease::new(
1049            self.globals_by_type
1050                .remove(&TypeId::of::<G>())
1051                .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
1052                .unwrap(),
1053        )
1054    }
1055
1056    /// Restore the global of the given type after it is moved to the stack.
1057    pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
1058        let global_type = TypeId::of::<G>();
1059        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1060        self.globals_by_type.insert(global_type, lease.global);
1061    }
1062
1063    pub(crate) fn new_view_observer(&self, key: TypeId, value: NewViewListener) -> Subscription {
1064        let (subscription, activate) = self.new_view_observers.insert(key, value);
1065        activate();
1066        subscription
1067    }
1068
1069    /// Arrange for the given function to be invoked whenever a view of the specified type is created.
1070    /// The function will be passed a mutable reference to the view along with an appropriate context.
1071    pub fn observe_new_views<V: 'static>(
1072        &self,
1073        on_new: impl 'static + Fn(&mut V, &mut ViewContext<V>),
1074    ) -> Subscription {
1075        self.new_view_observer(
1076            TypeId::of::<V>(),
1077            Box::new(move |any_view: AnyView, cx: &mut WindowContext| {
1078                any_view
1079                    .downcast::<V>()
1080                    .unwrap()
1081                    .update(cx, |view_state, cx| {
1082                        on_new(view_state, cx);
1083                    })
1084            }),
1085        )
1086    }
1087
1088    pub(crate) fn new_model_observer(&self, key: TypeId, value: NewModelListener) -> Subscription {
1089        let (subscription, activate) = self.new_model_observers.insert(key, value);
1090        activate();
1091        subscription
1092    }
1093
1094    /// Arrange for the given function to be invoked whenever a view of the specified type is created.
1095    /// The function will be passed a mutable reference to the view along with an appropriate context.
1096    pub fn observe_new_models<T: 'static>(
1097        &self,
1098        on_new: impl 'static + Fn(&mut T, &mut ModelContext<T>),
1099    ) -> Subscription {
1100        self.new_model_observer(
1101            TypeId::of::<T>(),
1102            Box::new(move |any_model: AnyModel, cx: &mut AppContext| {
1103                any_model
1104                    .downcast::<T>()
1105                    .unwrap()
1106                    .update(cx, |model_state, cx| {
1107                        on_new(model_state, cx);
1108                    })
1109            }),
1110        )
1111    }
1112
1113    /// Observe the release of a model or view. The callback is invoked after the model or view
1114    /// has no more strong references but before it has been dropped.
1115    pub fn observe_release<E, T>(
1116        &self,
1117        handle: &E,
1118        on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
1119    ) -> Subscription
1120    where
1121        E: Entity<T>,
1122        T: 'static,
1123    {
1124        let (subscription, activate) = self.release_listeners.insert(
1125            handle.entity_id(),
1126            Box::new(move |entity, cx| {
1127                let entity = entity.downcast_mut().expect("invalid entity type");
1128                on_release(entity, cx)
1129            }),
1130        );
1131        activate();
1132        subscription
1133    }
1134
1135    /// Register a callback to be invoked when a keystroke is received by the application
1136    /// in any window. Note that this fires after all other action and event mechanisms have resolved
1137    /// and that this API will not be invoked if the event's propagation is stopped.
1138    pub fn observe_keystrokes(
1139        &mut self,
1140        mut f: impl FnMut(&KeystrokeEvent, &mut WindowContext) + 'static,
1141    ) -> Subscription {
1142        fn inner(
1143            keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
1144            handler: KeystrokeObserver,
1145        ) -> Subscription {
1146            let (subscription, activate) = keystroke_observers.insert((), handler);
1147            activate();
1148            subscription
1149        }
1150
1151        inner(
1152            &mut self.keystroke_observers,
1153            Box::new(move |event, cx| {
1154                f(event, cx);
1155                true
1156            }),
1157        )
1158    }
1159
1160    /// Register key bindings.
1161    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1162        self.keymap.borrow_mut().add_bindings(bindings);
1163        self.pending_effects.push_back(Effect::Refresh);
1164    }
1165
1166    /// Clear all key bindings in the app.
1167    pub fn clear_key_bindings(&mut self) {
1168        self.keymap.borrow_mut().clear();
1169        self.pending_effects.push_back(Effect::Refresh);
1170    }
1171
1172    /// Register a global listener for actions invoked via the keyboard.
1173    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
1174        self.global_action_listeners
1175            .entry(TypeId::of::<A>())
1176            .or_default()
1177            .push(Rc::new(move |action, phase, cx| {
1178                if phase == DispatchPhase::Bubble {
1179                    let action = action.downcast_ref().unwrap();
1180                    listener(action, cx)
1181                }
1182            }));
1183    }
1184
1185    /// Event handlers propagate events by default. Call this method to stop dispatching to
1186    /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1187    /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1188    /// calling this method before effects are flushed.
1189    pub fn stop_propagation(&mut self) {
1190        self.propagate_event = false;
1191    }
1192
1193    /// Action handlers stop propagation by default during the bubble phase of action dispatch
1194    /// dispatching to action handlers higher in the element tree. This is the opposite of
1195    /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1196    /// this method before effects are flushed.
1197    pub fn propagate(&mut self) {
1198        self.propagate_event = true;
1199    }
1200
1201    /// Build an action from some arbitrary data, typically a keymap entry.
1202    pub fn build_action(
1203        &self,
1204        name: &str,
1205        data: Option<serde_json::Value>,
1206    ) -> Result<Box<dyn Action>> {
1207        self.actions.build_action(name, data)
1208    }
1209
1210    /// Get a list of all action names that have been registered.
1211    /// in the application. Note that registration only allows for
1212    /// actions to be built dynamically, and is unrelated to binding
1213    /// actions in the element tree.
1214    pub fn all_action_names(&self) -> &[SharedString] {
1215        self.actions.all_action_names()
1216    }
1217
1218    /// Register a callback to be invoked when the application is about to quit.
1219    /// It is not possible to cancel the quit event at this point.
1220    pub fn on_app_quit<Fut>(
1221        &self,
1222        mut on_quit: impl FnMut(&mut AppContext) -> Fut + 'static,
1223    ) -> Subscription
1224    where
1225        Fut: 'static + Future<Output = ()>,
1226    {
1227        let (subscription, activate) = self.quit_observers.insert(
1228            (),
1229            Box::new(move |cx| {
1230                let future = on_quit(cx);
1231                future.boxed_local()
1232            }),
1233        );
1234        activate();
1235        subscription
1236    }
1237
1238    pub(crate) fn clear_pending_keystrokes(&mut self) {
1239        for window in self.windows() {
1240            window
1241                .update(self, |_, cx| {
1242                    cx.clear_pending_keystrokes();
1243                })
1244                .ok();
1245        }
1246    }
1247
1248    /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1249    /// the bindings in the element tree, and any global action listeners.
1250    pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1251        let mut action_available = false;
1252        if let Some(window) = self.active_window() {
1253            if let Ok(window_action_available) =
1254                window.update(self, |_, cx| cx.is_action_available(action))
1255            {
1256                action_available = window_action_available;
1257            }
1258        }
1259
1260        action_available
1261            || self
1262                .global_action_listeners
1263                .contains_key(&action.as_any().type_id())
1264    }
1265
1266    /// Sets the menu bar for this application. This will replace any existing menu bar.
1267    pub fn set_menus(&self, menus: Vec<Menu>) {
1268        self.platform.set_menus(menus, &self.keymap.borrow());
1269    }
1270
1271    /// Gets the menu bar for this application.
1272    pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
1273        self.platform.get_menus()
1274    }
1275
1276    /// Sets the right click menu for the app icon in the dock
1277    pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
1278        self.platform.set_dock_menu(menus, &self.keymap.borrow());
1279    }
1280
1281    /// Adds given path to the bottom of the list of recent paths for the application.
1282    /// The list is usually shown on the application icon's context menu in the dock,
1283    /// and allows to open the recent files via that context menu.
1284    /// If the path is already in the list, it will be moved to the bottom of the list.
1285    pub fn add_recent_document(&self, path: &Path) {
1286        self.platform.add_recent_document(path);
1287    }
1288
1289    /// Dispatch an action to the currently active window or global action handler
1290    /// See [action::Action] for more information on how actions work
1291    pub fn dispatch_action(&mut self, action: &dyn Action) {
1292        if let Some(active_window) = self.active_window() {
1293            active_window
1294                .update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
1295                .log_err();
1296        } else {
1297            self.dispatch_global_action(action);
1298        }
1299    }
1300
1301    fn dispatch_global_action(&mut self, action: &dyn Action) {
1302        self.propagate_event = true;
1303
1304        if let Some(mut global_listeners) = self
1305            .global_action_listeners
1306            .remove(&action.as_any().type_id())
1307        {
1308            for listener in &global_listeners {
1309                listener(action.as_any(), DispatchPhase::Capture, self);
1310                if !self.propagate_event {
1311                    break;
1312                }
1313            }
1314
1315            global_listeners.extend(
1316                self.global_action_listeners
1317                    .remove(&action.as_any().type_id())
1318                    .unwrap_or_default(),
1319            );
1320
1321            self.global_action_listeners
1322                .insert(action.as_any().type_id(), global_listeners);
1323        }
1324
1325        if self.propagate_event {
1326            if let Some(mut global_listeners) = self
1327                .global_action_listeners
1328                .remove(&action.as_any().type_id())
1329            {
1330                for listener in global_listeners.iter().rev() {
1331                    listener(action.as_any(), DispatchPhase::Bubble, self);
1332                    if !self.propagate_event {
1333                        break;
1334                    }
1335                }
1336
1337                global_listeners.extend(
1338                    self.global_action_listeners
1339                        .remove(&action.as_any().type_id())
1340                        .unwrap_or_default(),
1341                );
1342
1343                self.global_action_listeners
1344                    .insert(action.as_any().type_id(), global_listeners);
1345            }
1346        }
1347    }
1348
1349    /// Is there currently something being dragged?
1350    pub fn has_active_drag(&self) -> bool {
1351        self.active_drag.is_some()
1352    }
1353
1354    /// Set the prompt renderer for GPUI. This will replace the default or platform specific
1355    /// prompts with this custom implementation.
1356    pub fn set_prompt_builder(
1357        &mut self,
1358        renderer: impl Fn(
1359                PromptLevel,
1360                &str,
1361                Option<&str>,
1362                &[&str],
1363                PromptHandle,
1364                &mut WindowContext,
1365            ) -> RenderablePromptHandle
1366            + 'static,
1367    ) {
1368        self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)))
1369    }
1370
1371    /// Remove an asset from GPUI's cache
1372    pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
1373        let asset_id = (TypeId::of::<A>(), hash(source));
1374        self.loading_assets.remove(&asset_id);
1375    }
1376
1377    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1378    ///
1379    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
1380    /// time, and the results of this call will be cached
1381    pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
1382        let asset_id = (TypeId::of::<A>(), hash(source));
1383        let mut is_first = false;
1384        let task = self
1385            .loading_assets
1386            .remove(&asset_id)
1387            .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
1388            .unwrap_or_else(|| {
1389                is_first = true;
1390                let future = A::load(source.clone(), self);
1391                let task = self.background_executor().spawn(future).shared();
1392                task
1393            });
1394
1395        self.loading_assets.insert(asset_id, Box::new(task.clone()));
1396
1397        (task, is_first)
1398    }
1399
1400    /// Get the name for this App.
1401    #[cfg(any(test, feature = "test-support", debug_assertions))]
1402    pub fn get_name(&self) -> &'static str {
1403        self.name.as_ref().unwrap()
1404    }
1405}
1406
1407impl Context for AppContext {
1408    type Result<T> = T;
1409
1410    /// Build an entity that is owned by the application. The given function will be invoked with
1411    /// a `ModelContext` and must return an object representing the entity. A `Model` handle will be returned,
1412    /// which can be used to access the entity in a context.
1413    fn new_model<T: 'static>(
1414        &mut self,
1415        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1416    ) -> Model<T> {
1417        self.update(|cx| {
1418            let slot = cx.entities.reserve();
1419            let model = slot.clone();
1420            let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
1421            cx.entities.insert(slot, entity);
1422
1423            // Non-generic part to avoid leaking SubscriberSet to invokers of `new_view`.
1424            fn notify_observers(cx: &mut AppContext, tid: TypeId, model: AnyModel) {
1425                cx.new_model_observers.clone().retain(&tid, |observer| {
1426                    let any_model = model.clone();
1427                    (observer)(any_model, cx);
1428                    true
1429                });
1430            }
1431            notify_observers(cx, TypeId::of::<T>(), AnyModel::from(model.clone()));
1432
1433            model
1434        })
1435    }
1436
1437    fn reserve_model<T: 'static>(&mut self) -> Self::Result<Reservation<T>> {
1438        Reservation(self.entities.reserve())
1439    }
1440
1441    fn insert_model<T: 'static>(
1442        &mut self,
1443        reservation: Reservation<T>,
1444        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1445    ) -> Self::Result<Model<T>> {
1446        self.update(|cx| {
1447            let slot = reservation.0;
1448            let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
1449            cx.entities.insert(slot, entity)
1450        })
1451    }
1452
1453    /// Updates the entity referenced by the given model. The function is passed a mutable reference to the
1454    /// entity along with a `ModelContext` for the entity.
1455    fn update_model<T: 'static, R>(
1456        &mut self,
1457        model: &Model<T>,
1458        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1459    ) -> R {
1460        self.update(|cx| {
1461            let mut entity = cx.entities.lease(model);
1462            let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
1463            cx.entities.end_lease(entity);
1464            result
1465        })
1466    }
1467
1468    fn read_model<T, R>(
1469        &self,
1470        handle: &Model<T>,
1471        read: impl FnOnce(&T, &AppContext) -> R,
1472    ) -> Self::Result<R>
1473    where
1474        T: 'static,
1475    {
1476        let entity = self.entities.read(handle);
1477        read(entity, self)
1478    }
1479
1480    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
1481    where
1482        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1483    {
1484        self.update(|cx| {
1485            let mut window = cx
1486                .windows
1487                .get_mut(handle.id)
1488                .ok_or_else(|| anyhow!("window not found"))?
1489                .take()
1490                .ok_or_else(|| anyhow!("window not found"))?;
1491
1492            let root_view = window.root_view.clone().unwrap();
1493            let result = update(root_view, &mut WindowContext::new(cx, &mut window));
1494
1495            if window.removed {
1496                cx.window_handles.remove(&handle.id);
1497                cx.windows.remove(handle.id);
1498            } else {
1499                cx.windows
1500                    .get_mut(handle.id)
1501                    .ok_or_else(|| anyhow!("window not found"))?
1502                    .replace(window);
1503            }
1504
1505            Ok(result)
1506        })
1507    }
1508
1509    fn read_window<T, R>(
1510        &self,
1511        window: &WindowHandle<T>,
1512        read: impl FnOnce(View<T>, &AppContext) -> R,
1513    ) -> Result<R>
1514    where
1515        T: 'static,
1516    {
1517        let window = self
1518            .windows
1519            .get(window.id)
1520            .ok_or_else(|| anyhow!("window not found"))?
1521            .as_ref()
1522            .unwrap();
1523
1524        let root_view = window.root_view.clone().unwrap();
1525        let view = root_view
1526            .downcast::<T>()
1527            .map_err(|_| anyhow!("root view's type has changed"))?;
1528
1529        Ok(read(view, self))
1530    }
1531}
1532
1533/// These effects are processed at the end of each application update cycle.
1534pub(crate) enum Effect {
1535    Notify {
1536        emitter: EntityId,
1537    },
1538    Emit {
1539        emitter: EntityId,
1540        event_type: TypeId,
1541        event: Box<dyn Any>,
1542    },
1543    Refresh,
1544    NotifyGlobalObservers {
1545        global_type: TypeId,
1546    },
1547    Defer {
1548        callback: Box<dyn FnOnce(&mut AppContext) + 'static>,
1549    },
1550}
1551
1552/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
1553pub(crate) struct GlobalLease<G: Global> {
1554    global: Box<dyn Any>,
1555    global_type: PhantomData<G>,
1556}
1557
1558impl<G: Global> GlobalLease<G> {
1559    fn new(global: Box<dyn Any>) -> Self {
1560        GlobalLease {
1561            global,
1562            global_type: PhantomData,
1563        }
1564    }
1565}
1566
1567impl<G: Global> Deref for GlobalLease<G> {
1568    type Target = G;
1569
1570    fn deref(&self) -> &Self::Target {
1571        self.global.downcast_ref().unwrap()
1572    }
1573}
1574
1575impl<G: Global> DerefMut for GlobalLease<G> {
1576    fn deref_mut(&mut self) -> &mut Self::Target {
1577        self.global.downcast_mut().unwrap()
1578    }
1579}
1580
1581/// Contains state associated with an active drag operation, started by dragging an element
1582/// within the window or by dragging into the app from the underlying platform.
1583pub struct AnyDrag {
1584    /// The view used to render this drag
1585    pub view: AnyView,
1586
1587    /// The value of the dragged item, to be dropped
1588    pub value: Arc<dyn Any>,
1589
1590    /// This is used to render the dragged item in the same place
1591    /// on the original element that the drag was initiated
1592    pub cursor_offset: Point<Pixels>,
1593}
1594
1595/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
1596/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip].
1597#[derive(Clone)]
1598pub struct AnyTooltip {
1599    /// The view used to display the tooltip
1600    pub view: AnyView,
1601
1602    /// The absolute position of the mouse when the tooltip was deployed.
1603    pub mouse_position: Point<Pixels>,
1604}
1605
1606/// A keystroke event, and potentially the associated action
1607#[derive(Debug)]
1608pub struct KeystrokeEvent {
1609    /// The keystroke that occurred
1610    pub keystroke: Keystroke,
1611
1612    /// The action that was resolved for the keystroke, if any
1613    pub action: Option<Box<dyn Action>>,
1614}
1615
1616struct NullHttpClient;
1617
1618impl HttpClient for NullHttpClient {
1619    fn send(
1620        &self,
1621        _req: http_client::Request<http_client::AsyncBody>,
1622    ) -> futures::future::BoxFuture<
1623        'static,
1624        Result<http_client::Response<http_client::AsyncBody>, anyhow::Error>,
1625    > {
1626        async move { Err(anyhow!("No HttpClient available")) }.boxed()
1627    }
1628
1629    fn proxy(&self) -> Option<&http_client::Uri> {
1630        None
1631    }
1632
1633    fn type_name(&self) -> &'static str {
1634        type_name::<Self>()
1635    }
1636}