app.rs

   1mod async_context;
   2mod entity_map;
   3mod model_context;
   4#[cfg(any(test, feature = "test-support"))]
   5mod test_context;
   6
   7pub use async_context::*;
   8use derive_more::{Deref, DerefMut};
   9pub use entity_map::*;
  10pub use model_context::*;
  11use refineable::Refineable;
  12use smallvec::SmallVec;
  13#[cfg(any(test, feature = "test-support"))]
  14pub use test_context::*;
  15
  16use crate::{
  17    current_platform, image_cache::ImageCache, Action, ActionRegistry, AnyBox, AnyView,
  18    AnyWindowHandle, AppMetadata, AssetSource, BackgroundExecutor, ClipboardItem, Context,
  19    DispatchPhase, DisplayId, Entity, EventEmitter, FocusEvent, FocusHandle, FocusId,
  20    ForegroundExecutor, KeyBinding, Keymap, LayoutId, PathPromptOptions, Pixels, Platform,
  21    PlatformDisplay, Point, Render, SharedString, SubscriberSet, Subscription, SvgRenderer, Task,
  22    TextStyle, TextStyleRefinement, TextSystem, View, ViewContext, Window, WindowContext,
  23    WindowHandle, WindowId,
  24};
  25use anyhow::{anyhow, Result};
  26use collections::{HashMap, HashSet, VecDeque};
  27use futures::{channel::oneshot, future::LocalBoxFuture, Future};
  28use parking_lot::Mutex;
  29use slotmap::SlotMap;
  30use std::{
  31    any::{type_name, Any, TypeId},
  32    cell::{Ref, RefCell, RefMut},
  33    marker::PhantomData,
  34    mem,
  35    ops::{Deref, DerefMut},
  36    path::{Path, PathBuf},
  37    rc::{Rc, Weak},
  38    sync::{atomic::Ordering::SeqCst, Arc},
  39    time::Duration,
  40};
  41use util::http::{self, HttpClient};
  42
  43/// Temporary(?) wrapper around RefCell<AppContext> to help us debug any double borrows.
  44/// Strongly consider removing after stabilization.
  45pub struct AppCell {
  46    app: RefCell<AppContext>,
  47}
  48
  49impl AppCell {
  50    #[track_caller]
  51    pub fn borrow(&self) -> AppRef {
  52        if let Some(_) = option_env!("TRACK_THREAD_BORROWS") {
  53            let thread_id = std::thread::current().id();
  54            eprintln!("borrowed {thread_id:?}");
  55        }
  56        AppRef(self.app.borrow())
  57    }
  58
  59    #[track_caller]
  60    pub fn borrow_mut(&self) -> AppRefMut {
  61        if let Some(_) = option_env!("TRACK_THREAD_BORROWS") {
  62            let thread_id = std::thread::current().id();
  63            eprintln!("borrowed {thread_id:?}");
  64        }
  65        AppRefMut(self.app.borrow_mut())
  66    }
  67}
  68
  69#[derive(Deref, DerefMut)]
  70pub struct AppRef<'a>(Ref<'a, AppContext>);
  71
  72impl<'a> Drop for AppRef<'a> {
  73    fn drop(&mut self) {
  74        if let Some(_) = option_env!("TRACK_THREAD_BORROWS") {
  75            let thread_id = std::thread::current().id();
  76            eprintln!("dropped borrow from {thread_id:?}");
  77        }
  78    }
  79}
  80
  81#[derive(Deref, DerefMut)]
  82pub struct AppRefMut<'a>(RefMut<'a, AppContext>);
  83
  84impl<'a> Drop for AppRefMut<'a> {
  85    fn drop(&mut self) {
  86        if let Some(_) = option_env!("TRACK_THREAD_BORROWS") {
  87            let thread_id = std::thread::current().id();
  88            eprintln!("dropped {thread_id:?}");
  89        }
  90    }
  91}
  92
  93pub struct App(Rc<AppCell>);
  94
  95/// Represents an application before it is fully launched. Once your app is
  96/// configured, you'll start the app with `App::run`.
  97impl App {
  98    /// Builds an app with the given asset source.
  99    pub fn production(asset_source: Arc<dyn AssetSource>) -> Self {
 100        Self(AppContext::new(
 101            current_platform(),
 102            asset_source,
 103            http::client(),
 104        ))
 105    }
 106
 107    /// Start the application. The provided callback will be called once the
 108    /// app is fully launched.
 109    pub fn run<F>(self, on_finish_launching: F)
 110    where
 111        F: 'static + FnOnce(&mut AppContext),
 112    {
 113        let this = self.0.clone();
 114        let platform = self.0.borrow().platform.clone();
 115        platform.run(Box::new(move || {
 116            let cx = &mut *this.borrow_mut();
 117            on_finish_launching(cx);
 118        }));
 119    }
 120
 121    /// Register a handler to be invoked when the platform instructs the application
 122    /// to open one or more URLs.
 123    pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
 124    where
 125        F: 'static + FnMut(Vec<String>, &mut AppContext),
 126    {
 127        let this = Rc::downgrade(&self.0);
 128        self.0.borrow().platform.on_open_urls(Box::new(move |urls| {
 129            if let Some(app) = this.upgrade() {
 130                callback(urls, &mut *app.borrow_mut());
 131            }
 132        }));
 133        self
 134    }
 135
 136    pub fn on_reopen<F>(&self, mut callback: F) -> &Self
 137    where
 138        F: 'static + FnMut(&mut AppContext),
 139    {
 140        let this = Rc::downgrade(&self.0);
 141        self.0.borrow_mut().platform.on_reopen(Box::new(move || {
 142            if let Some(app) = this.upgrade() {
 143                callback(&mut app.borrow_mut());
 144            }
 145        }));
 146        self
 147    }
 148
 149    pub fn metadata(&self) -> AppMetadata {
 150        self.0.borrow().app_metadata.clone()
 151    }
 152
 153    pub fn background_executor(&self) -> BackgroundExecutor {
 154        self.0.borrow().background_executor.clone()
 155    }
 156
 157    pub fn foreground_executor(&self) -> ForegroundExecutor {
 158        self.0.borrow().foreground_executor.clone()
 159    }
 160
 161    pub fn text_system(&self) -> Arc<TextSystem> {
 162        self.0.borrow().text_system.clone()
 163    }
 164}
 165
 166pub(crate) type FrameCallback = Box<dyn FnOnce(&mut AppContext)>;
 167type Handler = Box<dyn FnMut(&mut AppContext) -> bool + 'static>;
 168type Listener = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool + 'static>;
 169type QuitHandler = Box<dyn FnOnce(&mut AppContext) -> LocalBoxFuture<'static, ()> + 'static>;
 170type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut AppContext) + 'static>;
 171type NewViewListener = Box<dyn FnMut(AnyView, &mut WindowContext) + 'static>;
 172
 173// struct FrameConsumer {
 174//     next_frame_callbacks: Vec<FrameCallback>,
 175//     task: Task<()>,
 176//     display_linker
 177// }
 178
 179pub struct AppContext {
 180    pub(crate) this: Weak<AppCell>,
 181    pub(crate) platform: Rc<dyn Platform>,
 182    app_metadata: AppMetadata,
 183    text_system: Arc<TextSystem>,
 184    flushing_effects: bool,
 185    pending_updates: usize,
 186    pub(crate) actions: Rc<ActionRegistry>,
 187    pub(crate) active_drag: Option<AnyDrag>,
 188    pub(crate) active_tooltip: Option<AnyTooltip>,
 189    pub(crate) next_frame_callbacks: HashMap<DisplayId, Vec<FrameCallback>>,
 190    pub(crate) frame_consumers: HashMap<DisplayId, Task<()>>,
 191    pub(crate) background_executor: BackgroundExecutor,
 192    pub(crate) foreground_executor: ForegroundExecutor,
 193    pub(crate) svg_renderer: SvgRenderer,
 194    asset_source: Arc<dyn AssetSource>,
 195    pub(crate) image_cache: ImageCache,
 196    pub(crate) text_style_stack: Vec<TextStyleRefinement>,
 197    pub(crate) globals_by_type: HashMap<TypeId, AnyBox>,
 198    pub(crate) entities: EntityMap,
 199    pub(crate) new_view_observers: SubscriberSet<TypeId, NewViewListener>,
 200    pub(crate) windows: SlotMap<WindowId, Option<Window>>,
 201    pub(crate) keymap: Arc<Mutex<Keymap>>,
 202    pub(crate) global_action_listeners:
 203        HashMap<TypeId, Vec<Box<dyn Fn(&dyn Action, DispatchPhase, &mut Self)>>>,
 204    pending_effects: VecDeque<Effect>,
 205    pub(crate) pending_notifications: HashSet<EntityId>,
 206    pub(crate) pending_global_notifications: HashSet<TypeId>,
 207    pub(crate) observers: SubscriberSet<EntityId, Handler>,
 208    // TypeId is the type of the event that the listener callback expects
 209    pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
 210    pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
 211    pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
 212    pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
 213    pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
 214    pub(crate) propagate_event: bool,
 215}
 216
 217impl AppContext {
 218    pub(crate) fn new(
 219        platform: Rc<dyn Platform>,
 220        asset_source: Arc<dyn AssetSource>,
 221        http_client: Arc<dyn HttpClient>,
 222    ) -> Rc<AppCell> {
 223        let executor = platform.background_executor();
 224        let foreground_executor = platform.foreground_executor();
 225        assert!(
 226            executor.is_main_thread(),
 227            "must construct App on main thread"
 228        );
 229
 230        let text_system = Arc::new(TextSystem::new(platform.text_system()));
 231        let entities = EntityMap::new();
 232
 233        let app_metadata = AppMetadata {
 234            os_name: platform.os_name(),
 235            os_version: platform.os_version().ok(),
 236            app_version: platform.app_version().ok(),
 237        };
 238
 239        let app = Rc::new_cyclic(|this| AppCell {
 240            app: RefCell::new(AppContext {
 241                this: this.clone(),
 242                platform: platform.clone(),
 243                app_metadata,
 244                text_system,
 245                actions: Rc::new(ActionRegistry::default()),
 246                flushing_effects: false,
 247                pending_updates: 0,
 248                active_drag: None,
 249                active_tooltip: None,
 250                next_frame_callbacks: HashMap::default(),
 251                frame_consumers: HashMap::default(),
 252                background_executor: executor,
 253                foreground_executor,
 254                svg_renderer: SvgRenderer::new(asset_source.clone()),
 255                asset_source,
 256                image_cache: ImageCache::new(http_client),
 257                text_style_stack: Vec::new(),
 258                globals_by_type: HashMap::default(),
 259                entities,
 260                new_view_observers: SubscriberSet::new(),
 261                windows: SlotMap::with_key(),
 262                keymap: Arc::new(Mutex::new(Keymap::default())),
 263                global_action_listeners: HashMap::default(),
 264                pending_effects: VecDeque::new(),
 265                pending_notifications: HashSet::default(),
 266                pending_global_notifications: HashSet::default(),
 267                observers: SubscriberSet::new(),
 268                event_listeners: SubscriberSet::new(),
 269                release_listeners: SubscriberSet::new(),
 270                global_observers: SubscriberSet::new(),
 271                quit_observers: SubscriberSet::new(),
 272                layout_id_buffer: Default::default(),
 273                propagate_event: true,
 274            }),
 275        });
 276
 277        platform.on_quit(Box::new({
 278            let cx = app.clone();
 279            move || {
 280                cx.borrow_mut().shutdown();
 281            }
 282        }));
 283
 284        app
 285    }
 286
 287    /// Quit the application gracefully. Handlers registered with `ModelContext::on_app_quit`
 288    /// will be given 100ms to complete before exiting.
 289    pub fn shutdown(&mut self) {
 290        let mut futures = Vec::new();
 291
 292        for observer in self.quit_observers.remove(&()) {
 293            futures.push(observer(self));
 294        }
 295
 296        self.windows.clear();
 297        self.flush_effects();
 298
 299        let futures = futures::future::join_all(futures);
 300        if self
 301            .background_executor
 302            .block_with_timeout(Duration::from_millis(100), futures)
 303            .is_err()
 304        {
 305            log::error!("timed out waiting on app_will_quit");
 306        }
 307    }
 308
 309    pub fn quit(&mut self) {
 310        self.platform.quit();
 311    }
 312
 313    pub fn app_metadata(&self) -> AppMetadata {
 314        self.app_metadata.clone()
 315    }
 316
 317    /// Schedules all windows in the application to be redrawn. This can be called
 318    /// multiple times in an update cycle and still result in a single redraw.
 319    pub fn refresh(&mut self) {
 320        self.pending_effects.push_back(Effect::Refresh);
 321    }
 322    pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
 323        self.pending_updates += 1;
 324        let result = update(self);
 325        if !self.flushing_effects && self.pending_updates == 1 {
 326            self.flushing_effects = true;
 327            self.flush_effects();
 328            self.flushing_effects = false;
 329        }
 330        self.pending_updates -= 1;
 331        result
 332    }
 333
 334    pub fn observe<W, E>(
 335        &mut self,
 336        entity: &E,
 337        mut on_notify: impl FnMut(E, &mut AppContext) + 'static,
 338    ) -> Subscription
 339    where
 340        W: 'static,
 341        E: Entity<W>,
 342    {
 343        self.observe_internal(entity, move |e, cx| {
 344            on_notify(e, cx);
 345            true
 346        })
 347    }
 348
 349    pub fn observe_internal<W, E>(
 350        &mut self,
 351        entity: &E,
 352        mut on_notify: impl FnMut(E, &mut AppContext) -> bool + 'static,
 353    ) -> Subscription
 354    where
 355        W: 'static,
 356        E: Entity<W>,
 357    {
 358        let entity_id = entity.entity_id();
 359        let handle = entity.downgrade();
 360        self.observers.insert(
 361            entity_id,
 362            Box::new(move |cx| {
 363                if let Some(handle) = E::upgrade_from(&handle) {
 364                    on_notify(handle, cx)
 365                } else {
 366                    false
 367                }
 368            }),
 369        )
 370    }
 371
 372    pub fn subscribe<T, E, Evt>(
 373        &mut self,
 374        entity: &E,
 375        mut on_event: impl FnMut(E, &Evt, &mut AppContext) + 'static,
 376    ) -> Subscription
 377    where
 378        T: 'static + EventEmitter<Evt>,
 379        E: Entity<T>,
 380        Evt: 'static,
 381    {
 382        self.subscribe_internal(entity, move |entity, event, cx| {
 383            on_event(entity, event, cx);
 384            true
 385        })
 386    }
 387
 388    pub(crate) fn subscribe_internal<T, E, Evt>(
 389        &mut self,
 390        entity: &E,
 391        mut on_event: impl FnMut(E, &Evt, &mut AppContext) -> bool + 'static,
 392    ) -> Subscription
 393    where
 394        T: 'static + EventEmitter<Evt>,
 395        E: Entity<T>,
 396        Evt: 'static,
 397    {
 398        let entity_id = entity.entity_id();
 399        let entity = entity.downgrade();
 400
 401        self.event_listeners.insert(
 402            entity_id,
 403            (
 404                TypeId::of::<Evt>(),
 405                Box::new(move |event, cx| {
 406                    let event: &Evt = event.downcast_ref().expect("invalid event type");
 407                    if let Some(handle) = E::upgrade_from(&entity) {
 408                        on_event(handle, event, cx)
 409                    } else {
 410                        false
 411                    }
 412                }),
 413            ),
 414        )
 415    }
 416
 417    pub fn windows(&self) -> Vec<AnyWindowHandle> {
 418        self.windows
 419            .values()
 420            .filter_map(|window| Some(window.as_ref()?.handle.clone()))
 421            .collect()
 422    }
 423
 424    /// Opens a new window with the given option and the root view returned by the given function.
 425    /// The function is invoked with a `WindowContext`, which can be used to interact with window-specific
 426    /// functionality.
 427    pub fn open_window<V: Render>(
 428        &mut self,
 429        options: crate::WindowOptions,
 430        build_root_view: impl FnOnce(&mut WindowContext) -> View<V>,
 431    ) -> WindowHandle<V> {
 432        self.update(|cx| {
 433            let id = cx.windows.insert(None);
 434            let handle = WindowHandle::new(id);
 435            let mut window = Window::new(handle.into(), options, cx);
 436            let root_view = build_root_view(&mut WindowContext::new(cx, &mut window));
 437            window.root_view.replace(root_view.into());
 438            cx.windows.get_mut(id).unwrap().replace(window);
 439            handle
 440        })
 441    }
 442
 443    /// Instructs the platform to activate the application by bringing it to the foreground.
 444    pub fn activate(&self, ignoring_other_apps: bool) {
 445        self.platform.activate(ignoring_other_apps);
 446    }
 447
 448    pub fn hide(&self) {
 449        self.platform.hide();
 450    }
 451
 452    pub fn hide_other_apps(&self) {
 453        self.platform.hide_other_apps();
 454    }
 455
 456    pub fn unhide_other_apps(&self) {
 457        self.platform.unhide_other_apps();
 458    }
 459
 460    /// Returns the list of currently active displays.
 461    pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 462        self.platform.displays()
 463    }
 464
 465    /// Writes data to the platform clipboard.
 466    pub fn write_to_clipboard(&self, item: ClipboardItem) {
 467        self.platform.write_to_clipboard(item)
 468    }
 469
 470    /// Reads data from the platform clipboard.
 471    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
 472        self.platform.read_from_clipboard()
 473    }
 474
 475    /// Writes credentials to the platform keychain.
 476    pub fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
 477        self.platform.write_credentials(url, username, password)
 478    }
 479
 480    /// Reads credentials from the platform keychain.
 481    pub fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
 482        self.platform.read_credentials(url)
 483    }
 484
 485    /// Deletes credentials from the platform keychain.
 486    pub fn delete_credentials(&self, url: &str) -> Result<()> {
 487        self.platform.delete_credentials(url)
 488    }
 489
 490    /// Directs the platform's default browser to open the given URL.
 491    pub fn open_url(&self, url: &str) {
 492        self.platform.open_url(url);
 493    }
 494
 495    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 496        self.platform.path_for_auxiliary_executable(name)
 497    }
 498
 499    pub fn prompt_for_paths(
 500        &self,
 501        options: PathPromptOptions,
 502    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 503        self.platform.prompt_for_paths(options)
 504    }
 505
 506    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
 507        self.platform.prompt_for_new_path(directory)
 508    }
 509
 510    pub fn reveal_path(&self, path: &Path) {
 511        self.platform.reveal_path(path)
 512    }
 513
 514    pub fn should_auto_hide_scrollbars(&self) -> bool {
 515        self.platform.should_auto_hide_scrollbars()
 516    }
 517
 518    pub(crate) fn push_effect(&mut self, effect: Effect) {
 519        match &effect {
 520            Effect::Notify { emitter } => {
 521                if !self.pending_notifications.insert(*emitter) {
 522                    return;
 523                }
 524            }
 525            Effect::NotifyGlobalObservers { global_type } => {
 526                if !self.pending_global_notifications.insert(*global_type) {
 527                    return;
 528                }
 529            }
 530            _ => {}
 531        };
 532
 533        self.pending_effects.push_back(effect);
 534    }
 535
 536    /// Called at the end of AppContext::update to complete any side effects
 537    /// such as notifying observers, emitting events, etc. Effects can themselves
 538    /// cause effects, so we continue looping until all effects are processed.
 539    fn flush_effects(&mut self) {
 540        loop {
 541            self.release_dropped_entities();
 542            self.release_dropped_focus_handles();
 543            if let Some(effect) = self.pending_effects.pop_front() {
 544                match effect {
 545                    Effect::Notify { emitter } => {
 546                        self.apply_notify_effect(emitter);
 547                    }
 548                    Effect::Emit {
 549                        emitter,
 550                        event_type,
 551                        event,
 552                    } => self.apply_emit_effect(emitter, event_type, event),
 553                    Effect::FocusChanged {
 554                        window_handle,
 555                        focused,
 556                    } => {
 557                        self.apply_focus_changed_effect(window_handle, focused);
 558                    }
 559                    Effect::Refresh => {
 560                        self.apply_refresh_effect();
 561                    }
 562                    Effect::NotifyGlobalObservers { global_type } => {
 563                        self.apply_notify_global_observers_effect(global_type);
 564                    }
 565                    Effect::Defer { callback } => {
 566                        self.apply_defer_effect(callback);
 567                    }
 568                }
 569            } else {
 570                break;
 571            }
 572        }
 573
 574        let dirty_window_ids = self
 575            .windows
 576            .iter()
 577            .filter_map(|(_, window)| {
 578                let window = window.as_ref().unwrap();
 579                if window.dirty {
 580                    Some(window.handle.clone())
 581                } else {
 582                    None
 583                }
 584            })
 585            .collect::<SmallVec<[_; 8]>>();
 586
 587        for dirty_window_handle in dirty_window_ids {
 588            dirty_window_handle.update(self, |_, cx| cx.draw()).unwrap();
 589        }
 590    }
 591
 592    /// Repeatedly called during `flush_effects` to release any entities whose
 593    /// reference count has become zero. We invoke any release observers before dropping
 594    /// each entity.
 595    fn release_dropped_entities(&mut self) {
 596        loop {
 597            let dropped = self.entities.take_dropped();
 598            if dropped.is_empty() {
 599                break;
 600            }
 601
 602            for (entity_id, mut entity) in dropped {
 603                self.observers.remove(&entity_id);
 604                self.event_listeners.remove(&entity_id);
 605                for release_callback in self.release_listeners.remove(&entity_id) {
 606                    release_callback(entity.as_mut(), self);
 607                }
 608            }
 609        }
 610    }
 611
 612    /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
 613    /// For now, we simply blur the window if this happens, but we may want to support invoking
 614    /// a window blur handler to restore focus to some logical element.
 615    fn release_dropped_focus_handles(&mut self) {
 616        for window_handle in self.windows() {
 617            window_handle
 618                .update(self, |_, cx| {
 619                    let mut blur_window = false;
 620                    let focus = cx.window.focus;
 621                    cx.window.focus_handles.write().retain(|handle_id, count| {
 622                        if count.load(SeqCst) == 0 {
 623                            if focus == Some(handle_id) {
 624                                blur_window = true;
 625                            }
 626                            false
 627                        } else {
 628                            true
 629                        }
 630                    });
 631
 632                    if blur_window {
 633                        cx.blur();
 634                    }
 635                })
 636                .unwrap();
 637        }
 638    }
 639
 640    fn apply_notify_effect(&mut self, emitter: EntityId) {
 641        self.pending_notifications.remove(&emitter);
 642
 643        self.observers
 644            .clone()
 645            .retain(&emitter, |handler| handler(self));
 646    }
 647
 648    fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
 649        self.event_listeners
 650            .clone()
 651            .retain(&emitter, |(stored_type, handler)| {
 652                if *stored_type == event_type {
 653                    handler(event.as_ref(), self)
 654                } else {
 655                    true
 656                }
 657            });
 658    }
 659
 660    fn apply_focus_changed_effect(
 661        &mut self,
 662        window_handle: AnyWindowHandle,
 663        focused: Option<FocusId>,
 664    ) {
 665        window_handle
 666            .update(self, |_, cx| {
 667                // The window might change focus multiple times in an effect cycle.
 668                // We only honor effects for the most recently focused handle.
 669                if cx.window.focus == focused {
 670                    // if someone calls focus multiple times in one frame with the same handle
 671                    // the first apply_focus_changed_effect will have taken the last blur already
 672                    // and run the rest of this, so we can return.
 673                    let Some(last_blur) = cx.window.last_blur.take() else {
 674                        return;
 675                    };
 676
 677                    let focused = focused
 678                        .map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());
 679
 680                    let blurred =
 681                        last_blur.and_then(|id| FocusHandle::for_id(id, &cx.window.focus_handles));
 682
 683                    let focus_changed = focused.is_some() || blurred.is_some();
 684                    let event = FocusEvent { focused, blurred };
 685
 686                    let mut listeners = mem::take(&mut cx.window.current_frame.focus_listeners);
 687                    if focus_changed {
 688                        for listener in &mut listeners {
 689                            listener(&event, cx);
 690                        }
 691                    }
 692                    listeners.extend(cx.window.current_frame.focus_listeners.drain(..));
 693                    cx.window.current_frame.focus_listeners = listeners;
 694
 695                    if focus_changed {
 696                        cx.window
 697                            .focus_listeners
 698                            .clone()
 699                            .retain(&(), |listener| listener(&event, cx));
 700                    }
 701                }
 702            })
 703            .ok();
 704    }
 705
 706    fn apply_refresh_effect(&mut self) {
 707        for window in self.windows.values_mut() {
 708            if let Some(window) = window.as_mut() {
 709                window.dirty = true;
 710            }
 711        }
 712    }
 713
 714    fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
 715        self.pending_global_notifications.remove(&type_id);
 716        self.global_observers
 717            .clone()
 718            .retain(&type_id, |observer| observer(self));
 719    }
 720
 721    fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
 722        callback(self);
 723    }
 724
 725    /// Creates an `AsyncAppContext`, which can be cloned and has a static lifetime
 726    /// so it can be held across `await` points.
 727    pub fn to_async(&self) -> AsyncAppContext {
 728        AsyncAppContext {
 729            app: unsafe { mem::transmute(self.this.clone()) },
 730            background_executor: self.background_executor.clone(),
 731            foreground_executor: self.foreground_executor.clone(),
 732        }
 733    }
 734
 735    /// Obtains a reference to the executor, which can be used to spawn futures.
 736    pub fn background_executor(&self) -> &BackgroundExecutor {
 737        &self.background_executor
 738    }
 739
 740    /// Obtains a reference to the executor, which can be used to spawn futures.
 741    pub fn foreground_executor(&self) -> &ForegroundExecutor {
 742        &self.foreground_executor
 743    }
 744
 745    /// Spawns the future returned by the given function on the thread pool. The closure will be invoked
 746    /// with AsyncAppContext, which allows the application state to be accessed across await points.
 747    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
 748    where
 749        Fut: Future<Output = R> + 'static,
 750        R: 'static,
 751    {
 752        self.foreground_executor.spawn(f(self.to_async()))
 753    }
 754
 755    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
 756    /// that are currently on the stack to be returned to the app.
 757    pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static) {
 758        self.push_effect(Effect::Defer {
 759            callback: Box::new(f),
 760        });
 761    }
 762
 763    /// Accessor for the application's asset source, which is provided when constructing the `App`.
 764    pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
 765        &self.asset_source
 766    }
 767
 768    /// Accessor for the text system.
 769    pub fn text_system(&self) -> &Arc<TextSystem> {
 770        &self.text_system
 771    }
 772
 773    /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
 774    pub fn text_style(&self) -> TextStyle {
 775        let mut style = TextStyle::default();
 776        for refinement in &self.text_style_stack {
 777            style.refine(refinement);
 778        }
 779        style
 780    }
 781
 782    /// Check whether a global of the given type has been assigned.
 783    pub fn has_global<G: 'static>(&self) -> bool {
 784        self.globals_by_type.contains_key(&TypeId::of::<G>())
 785    }
 786
 787    /// Access the global of the given type. Panics if a global for that type has not been assigned.
 788    #[track_caller]
 789    pub fn global<G: 'static>(&self) -> &G {
 790        self.globals_by_type
 791            .get(&TypeId::of::<G>())
 792            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
 793            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
 794            .unwrap()
 795    }
 796
 797    /// Access the global of the given type if a value has been assigned.
 798    pub fn try_global<G: 'static>(&self) -> Option<&G> {
 799        self.globals_by_type
 800            .get(&TypeId::of::<G>())
 801            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
 802    }
 803
 804    /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
 805    #[track_caller]
 806    pub fn global_mut<G: 'static>(&mut self) -> &mut G {
 807        let global_type = TypeId::of::<G>();
 808        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 809        self.globals_by_type
 810            .get_mut(&global_type)
 811            .and_then(|any_state| any_state.downcast_mut::<G>())
 812            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
 813            .unwrap()
 814    }
 815
 816    /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
 817    /// yet been assigned.
 818    pub fn default_global<G: 'static + Default>(&mut self) -> &mut G {
 819        let global_type = TypeId::of::<G>();
 820        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 821        self.globals_by_type
 822            .entry(global_type)
 823            .or_insert_with(|| Box::new(G::default()))
 824            .downcast_mut::<G>()
 825            .unwrap()
 826    }
 827
 828    /// Set the value of the global of the given type.
 829    pub fn set_global<G: Any>(&mut self, global: G) {
 830        let global_type = TypeId::of::<G>();
 831        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 832        self.globals_by_type.insert(global_type, Box::new(global));
 833    }
 834
 835    /// Clear all stored globals. Does not notify global observers.
 836    #[cfg(any(test, feature = "test-support"))]
 837    pub fn clear_globals(&mut self) {
 838        self.globals_by_type.drain();
 839    }
 840
 841    /// Remove the global of the given type from the app context. Does not notify global observers.
 842    #[cfg(any(test, feature = "test-support"))]
 843    pub fn remove_global<G: Any>(&mut self) -> G {
 844        let global_type = TypeId::of::<G>();
 845        *self
 846            .globals_by_type
 847            .remove(&global_type)
 848            .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
 849            .downcast()
 850            .unwrap()
 851    }
 852
 853    /// Update the global of the given type with a closure. Unlike `global_mut`, this method provides
 854    /// your closure with mutable access to the `AppContext` and the global simultaneously.
 855    pub fn update_global<G: 'static, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R {
 856        let mut global = self.lease_global::<G>();
 857        let result = f(&mut global, self);
 858        self.end_global_lease(global);
 859        result
 860    }
 861
 862    /// Register a callback to be invoked when a global of the given type is updated.
 863    pub fn observe_global<G: 'static>(
 864        &mut self,
 865        mut f: impl FnMut(&mut Self) + 'static,
 866    ) -> Subscription {
 867        self.global_observers.insert(
 868            TypeId::of::<G>(),
 869            Box::new(move |cx| {
 870                f(cx);
 871                true
 872            }),
 873        )
 874    }
 875
 876    /// Move the global of the given type to the stack.
 877    pub(crate) fn lease_global<G: 'static>(&mut self) -> GlobalLease<G> {
 878        GlobalLease::new(
 879            self.globals_by_type
 880                .remove(&TypeId::of::<G>())
 881                .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
 882                .unwrap(),
 883        )
 884    }
 885
 886    /// Restore the global of the given type after it is moved to the stack.
 887    pub(crate) fn end_global_lease<G: 'static>(&mut self, lease: GlobalLease<G>) {
 888        let global_type = TypeId::of::<G>();
 889        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 890        self.globals_by_type.insert(global_type, lease.global);
 891    }
 892
 893    pub fn observe_new_views<V: 'static>(
 894        &mut self,
 895        on_new: impl 'static + Fn(&mut V, &mut ViewContext<V>),
 896    ) -> Subscription {
 897        self.new_view_observers.insert(
 898            TypeId::of::<V>(),
 899            Box::new(move |any_view: AnyView, cx: &mut WindowContext| {
 900                any_view
 901                    .downcast::<V>()
 902                    .unwrap()
 903                    .update(cx, |view_state, cx| {
 904                        on_new(view_state, cx);
 905                    })
 906            }),
 907        )
 908    }
 909
 910    pub fn observe_release<E, T>(
 911        &mut self,
 912        handle: &E,
 913        on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
 914    ) -> Subscription
 915    where
 916        E: Entity<T>,
 917        T: 'static,
 918    {
 919        self.release_listeners.insert(
 920            handle.entity_id(),
 921            Box::new(move |entity, cx| {
 922                let entity = entity.downcast_mut().expect("invalid entity type");
 923                on_release(entity, cx)
 924            }),
 925        )
 926    }
 927
 928    pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
 929        self.text_style_stack.push(text_style);
 930    }
 931
 932    pub(crate) fn pop_text_style(&mut self) {
 933        self.text_style_stack.pop();
 934    }
 935
 936    /// Register key bindings.
 937    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
 938        self.keymap.lock().add_bindings(bindings);
 939        self.pending_effects.push_back(Effect::Refresh);
 940    }
 941
 942    /// Register a global listener for actions invoked via the keyboard.
 943    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
 944        self.global_action_listeners
 945            .entry(TypeId::of::<A>())
 946            .or_default()
 947            .push(Box::new(move |action, phase, cx| {
 948                if phase == DispatchPhase::Bubble {
 949                    let action = action.as_any().downcast_ref().unwrap();
 950                    listener(action, cx)
 951                }
 952            }));
 953    }
 954
 955    /// Event handlers propagate events by default. Call this method to stop dispatching to
 956    /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
 957    /// the opposite of [propagate]. It's also possible to cancel a call to [propagate] by
 958    /// calling this method before effects are flushed.
 959    pub fn stop_propagation(&mut self) {
 960        self.propagate_event = false;
 961    }
 962
 963    /// Action handlers stop propagation by default during the bubble phase of action dispatch
 964    /// dispatching to action handlers higher in the element tree. This is the opposite of
 965    /// [stop_propagation]. It's also possible to cancel a call to [stop_propagate] by calling
 966    /// this method before effects are flushed.
 967    pub fn propagate(&mut self) {
 968        self.propagate_event = true;
 969    }
 970
 971    pub fn build_action(
 972        &self,
 973        name: &str,
 974        data: Option<serde_json::Value>,
 975    ) -> Result<Box<dyn Action>> {
 976        self.actions.build_action(name, data)
 977    }
 978
 979    pub fn all_action_names(&self) -> &[SharedString] {
 980        self.actions.all_action_names()
 981    }
 982}
 983
 984impl Context for AppContext {
 985    type Result<T> = T;
 986
 987    /// Build an entity that is owned by the application. The given function will be invoked with
 988    /// a `ModelContext` and must return an object representing the entity. A `Model` will be returned
 989    /// which can be used to access the entity in a context.
 990    fn build_model<T: 'static>(
 991        &mut self,
 992        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
 993    ) -> Model<T> {
 994        self.update(|cx| {
 995            let slot = cx.entities.reserve();
 996            let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
 997            cx.entities.insert(slot, entity)
 998        })
 999    }
1000
1001    /// Update the entity referenced by the given model. The function is passed a mutable reference to the
1002    /// entity along with a `ModelContext` for the entity.
1003    fn update_model<T: 'static, R>(
1004        &mut self,
1005        model: &Model<T>,
1006        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1007    ) -> R {
1008        self.update(|cx| {
1009            let mut entity = cx.entities.lease(model);
1010            let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
1011            cx.entities.end_lease(entity);
1012            result
1013        })
1014    }
1015
1016    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
1017    where
1018        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1019    {
1020        self.update(|cx| {
1021            let mut window = cx
1022                .windows
1023                .get_mut(handle.id)
1024                .ok_or_else(|| anyhow!("window not found"))?
1025                .take()
1026                .unwrap();
1027
1028            let root_view = window.root_view.clone().unwrap();
1029            let result = update(root_view, &mut WindowContext::new(cx, &mut window));
1030
1031            if !window.removed {
1032                cx.windows
1033                    .get_mut(handle.id)
1034                    .ok_or_else(|| anyhow!("window not found"))?
1035                    .replace(window);
1036            }
1037
1038            Ok(result)
1039        })
1040    }
1041
1042    fn read_model<T, R>(
1043        &self,
1044        handle: &Model<T>,
1045        read: impl FnOnce(&T, &AppContext) -> R,
1046    ) -> Self::Result<R>
1047    where
1048        T: 'static,
1049    {
1050        let entity = self.entities.read(handle);
1051        read(entity, self)
1052    }
1053
1054    fn read_window<T, R>(
1055        &self,
1056        window: &WindowHandle<T>,
1057        read: impl FnOnce(View<T>, &AppContext) -> R,
1058    ) -> Result<R>
1059    where
1060        T: 'static,
1061    {
1062        let window = self
1063            .windows
1064            .get(window.id)
1065            .ok_or_else(|| anyhow!("window not found"))?
1066            .as_ref()
1067            .unwrap();
1068
1069        let root_view = window.root_view.clone().unwrap();
1070        let view = root_view
1071            .downcast::<T>()
1072            .map_err(|_| anyhow!("root view's type has changed"))?;
1073
1074        Ok(read(view, self))
1075    }
1076}
1077
1078/// These effects are processed at the end of each application update cycle.
1079pub(crate) enum Effect {
1080    Notify {
1081        emitter: EntityId,
1082    },
1083    Emit {
1084        emitter: EntityId,
1085        event_type: TypeId,
1086        event: Box<dyn Any>,
1087    },
1088    FocusChanged {
1089        window_handle: AnyWindowHandle,
1090        focused: Option<FocusId>,
1091    },
1092    Refresh,
1093    NotifyGlobalObservers {
1094        global_type: TypeId,
1095    },
1096    Defer {
1097        callback: Box<dyn FnOnce(&mut AppContext) + 'static>,
1098    },
1099}
1100
1101/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
1102pub(crate) struct GlobalLease<G: 'static> {
1103    global: AnyBox,
1104    global_type: PhantomData<G>,
1105}
1106
1107impl<G: 'static> GlobalLease<G> {
1108    fn new(global: AnyBox) -> Self {
1109        GlobalLease {
1110            global,
1111            global_type: PhantomData,
1112        }
1113    }
1114}
1115
1116impl<G: 'static> Deref for GlobalLease<G> {
1117    type Target = G;
1118
1119    fn deref(&self) -> &Self::Target {
1120        self.global.downcast_ref().unwrap()
1121    }
1122}
1123
1124impl<G: 'static> DerefMut for GlobalLease<G> {
1125    fn deref_mut(&mut self) -> &mut Self::Target {
1126        self.global.downcast_mut().unwrap()
1127    }
1128}
1129
1130/// Contains state associated with an active drag operation, started by dragging an element
1131/// within the window or by dragging into the app from the underlying platform.
1132pub struct AnyDrag {
1133    pub view: AnyView,
1134    pub cursor_offset: Point<Pixels>,
1135}
1136
1137#[derive(Clone)]
1138pub(crate) struct AnyTooltip {
1139    pub view: AnyView,
1140    pub cursor_offset: Point<Pixels>,
1141}