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