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