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 fn restart(&self) {
 524        self.platform.restart()
 525    }
 526
 527    pub(crate) fn push_effect(&mut self, effect: Effect) {
 528        match &effect {
 529            Effect::Notify { emitter } => {
 530                if !self.pending_notifications.insert(*emitter) {
 531                    return;
 532                }
 533            }
 534            Effect::NotifyGlobalObservers { global_type } => {
 535                if !self.pending_global_notifications.insert(*global_type) {
 536                    return;
 537                }
 538            }
 539            _ => {}
 540        };
 541
 542        self.pending_effects.push_back(effect);
 543    }
 544
 545    /// Called at the end of AppContext::update to complete any side effects
 546    /// such as notifying observers, emitting events, etc. Effects can themselves
 547    /// cause effects, so we continue looping until all effects are processed.
 548    fn flush_effects(&mut self) {
 549        loop {
 550            self.release_dropped_entities();
 551            self.release_dropped_focus_handles();
 552            if let Some(effect) = self.pending_effects.pop_front() {
 553                match effect {
 554                    Effect::Notify { emitter } => {
 555                        self.apply_notify_effect(emitter);
 556                    }
 557                    Effect::Emit {
 558                        emitter,
 559                        event_type,
 560                        event,
 561                    } => self.apply_emit_effect(emitter, event_type, event),
 562                    Effect::FocusChanged {
 563                        window_handle,
 564                        focused,
 565                    } => {
 566                        self.apply_focus_changed_effect(window_handle, focused);
 567                    }
 568                    Effect::Refresh => {
 569                        self.apply_refresh_effect();
 570                    }
 571                    Effect::NotifyGlobalObservers { global_type } => {
 572                        self.apply_notify_global_observers_effect(global_type);
 573                    }
 574                    Effect::Defer { callback } => {
 575                        self.apply_defer_effect(callback);
 576                    }
 577                }
 578            } else {
 579                break;
 580            }
 581        }
 582
 583        let dirty_window_ids = self
 584            .windows
 585            .iter()
 586            .filter_map(|(_, window)| {
 587                let window = window.as_ref()?;
 588                if window.dirty {
 589                    Some(window.handle.clone())
 590                } else {
 591                    None
 592                }
 593            })
 594            .collect::<SmallVec<[_; 8]>>();
 595
 596        for dirty_window_handle in dirty_window_ids {
 597            dirty_window_handle.update(self, |_, cx| cx.draw()).unwrap();
 598        }
 599    }
 600
 601    /// Repeatedly called during `flush_effects` to release any entities whose
 602    /// reference count has become zero. We invoke any release observers before dropping
 603    /// each entity.
 604    fn release_dropped_entities(&mut self) {
 605        loop {
 606            let dropped = self.entities.take_dropped();
 607            if dropped.is_empty() {
 608                break;
 609            }
 610
 611            for (entity_id, mut entity) in dropped {
 612                self.observers.remove(&entity_id);
 613                self.event_listeners.remove(&entity_id);
 614                for release_callback in self.release_listeners.remove(&entity_id) {
 615                    release_callback(entity.as_mut(), self);
 616                }
 617            }
 618        }
 619    }
 620
 621    /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
 622    /// For now, we simply blur the window if this happens, but we may want to support invoking
 623    /// a window blur handler to restore focus to some logical element.
 624    fn release_dropped_focus_handles(&mut self) {
 625        for window_handle in self.windows() {
 626            window_handle
 627                .update(self, |_, cx| {
 628                    let mut blur_window = false;
 629                    let focus = cx.window.focus;
 630                    cx.window.focus_handles.write().retain(|handle_id, count| {
 631                        if count.load(SeqCst) == 0 {
 632                            if focus == Some(handle_id) {
 633                                blur_window = true;
 634                            }
 635                            false
 636                        } else {
 637                            true
 638                        }
 639                    });
 640
 641                    if blur_window {
 642                        cx.blur();
 643                    }
 644                })
 645                .unwrap();
 646        }
 647    }
 648
 649    fn apply_notify_effect(&mut self, emitter: EntityId) {
 650        self.pending_notifications.remove(&emitter);
 651
 652        self.observers
 653            .clone()
 654            .retain(&emitter, |handler| handler(self));
 655    }
 656
 657    fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
 658        self.event_listeners
 659            .clone()
 660            .retain(&emitter, |(stored_type, handler)| {
 661                if *stored_type == event_type {
 662                    handler(event.as_ref(), self)
 663                } else {
 664                    true
 665                }
 666            });
 667    }
 668
 669    fn apply_focus_changed_effect(
 670        &mut self,
 671        window_handle: AnyWindowHandle,
 672        focused: Option<FocusId>,
 673    ) {
 674        window_handle
 675            .update(self, |_, cx| {
 676                // The window might change focus multiple times in an effect cycle.
 677                // We only honor effects for the most recently focused handle.
 678                if cx.window.focus == focused {
 679                    // if someone calls focus multiple times in one frame with the same handle
 680                    // the first apply_focus_changed_effect will have taken the last blur already
 681                    // and run the rest of this, so we can return.
 682                    let Some(last_blur) = cx.window.last_blur.take() else {
 683                        return;
 684                    };
 685
 686                    let focused = focused
 687                        .map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());
 688
 689                    let blurred =
 690                        last_blur.and_then(|id| FocusHandle::for_id(id, &cx.window.focus_handles));
 691
 692                    let focus_changed = focused.is_some() || blurred.is_some();
 693                    let event = FocusEvent { focused, blurred };
 694
 695                    let mut listeners = mem::take(&mut cx.window.current_frame.focus_listeners);
 696                    if focus_changed {
 697                        for listener in &mut listeners {
 698                            listener(&event, cx);
 699                        }
 700                    }
 701                    listeners.extend(cx.window.current_frame.focus_listeners.drain(..));
 702                    cx.window.current_frame.focus_listeners = listeners;
 703
 704                    if focus_changed {
 705                        cx.window
 706                            .focus_listeners
 707                            .clone()
 708                            .retain(&(), |listener| listener(&event, cx));
 709                    }
 710                }
 711            })
 712            .ok();
 713    }
 714
 715    fn apply_refresh_effect(&mut self) {
 716        for window in self.windows.values_mut() {
 717            if let Some(window) = window.as_mut() {
 718                window.dirty = true;
 719            }
 720        }
 721    }
 722
 723    fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
 724        self.pending_global_notifications.remove(&type_id);
 725        self.global_observers
 726            .clone()
 727            .retain(&type_id, |observer| observer(self));
 728    }
 729
 730    fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
 731        callback(self);
 732    }
 733
 734    /// Creates an `AsyncAppContext`, which can be cloned and has a static lifetime
 735    /// so it can be held across `await` points.
 736    pub fn to_async(&self) -> AsyncAppContext {
 737        AsyncAppContext {
 738            app: unsafe { mem::transmute(self.this.clone()) },
 739            background_executor: self.background_executor.clone(),
 740            foreground_executor: self.foreground_executor.clone(),
 741        }
 742    }
 743
 744    /// Obtains a reference to the executor, which can be used to spawn futures.
 745    pub fn background_executor(&self) -> &BackgroundExecutor {
 746        &self.background_executor
 747    }
 748
 749    /// Obtains a reference to the executor, which can be used to spawn futures.
 750    pub fn foreground_executor(&self) -> &ForegroundExecutor {
 751        &self.foreground_executor
 752    }
 753
 754    /// Spawns the future returned by the given function on the thread pool. The closure will be invoked
 755    /// with AsyncAppContext, which allows the application state to be accessed across await points.
 756    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
 757    where
 758        Fut: Future<Output = R> + 'static,
 759        R: 'static,
 760    {
 761        self.foreground_executor.spawn(f(self.to_async()))
 762    }
 763
 764    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
 765    /// that are currently on the stack to be returned to the app.
 766    pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static) {
 767        self.push_effect(Effect::Defer {
 768            callback: Box::new(f),
 769        });
 770    }
 771
 772    /// Accessor for the application's asset source, which is provided when constructing the `App`.
 773    pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
 774        &self.asset_source
 775    }
 776
 777    /// Accessor for the text system.
 778    pub fn text_system(&self) -> &Arc<TextSystem> {
 779        &self.text_system
 780    }
 781
 782    /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
 783    pub fn text_style(&self) -> TextStyle {
 784        let mut style = TextStyle::default();
 785        for refinement in &self.text_style_stack {
 786            style.refine(refinement);
 787        }
 788        style
 789    }
 790
 791    /// Check whether a global of the given type has been assigned.
 792    pub fn has_global<G: 'static>(&self) -> bool {
 793        self.globals_by_type.contains_key(&TypeId::of::<G>())
 794    }
 795
 796    /// Access the global of the given type. Panics if a global for that type has not been assigned.
 797    #[track_caller]
 798    pub fn global<G: 'static>(&self) -> &G {
 799        self.globals_by_type
 800            .get(&TypeId::of::<G>())
 801            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
 802            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
 803            .unwrap()
 804    }
 805
 806    /// Access the global of the given type if a value has been assigned.
 807    pub fn try_global<G: 'static>(&self) -> Option<&G> {
 808        self.globals_by_type
 809            .get(&TypeId::of::<G>())
 810            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
 811    }
 812
 813    /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
 814    #[track_caller]
 815    pub fn global_mut<G: 'static>(&mut self) -> &mut G {
 816        let global_type = TypeId::of::<G>();
 817        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 818        self.globals_by_type
 819            .get_mut(&global_type)
 820            .and_then(|any_state| any_state.downcast_mut::<G>())
 821            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
 822            .unwrap()
 823    }
 824
 825    /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
 826    /// yet been assigned.
 827    pub fn default_global<G: 'static + Default>(&mut self) -> &mut G {
 828        let global_type = TypeId::of::<G>();
 829        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 830        self.globals_by_type
 831            .entry(global_type)
 832            .or_insert_with(|| Box::new(G::default()))
 833            .downcast_mut::<G>()
 834            .unwrap()
 835    }
 836
 837    /// Set the value of the global of the given type.
 838    pub fn set_global<G: Any>(&mut self, global: G) {
 839        let global_type = TypeId::of::<G>();
 840        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 841        self.globals_by_type.insert(global_type, Box::new(global));
 842    }
 843
 844    /// Clear all stored globals. Does not notify global observers.
 845    #[cfg(any(test, feature = "test-support"))]
 846    pub fn clear_globals(&mut self) {
 847        self.globals_by_type.drain();
 848    }
 849
 850    /// Remove the global of the given type from the app context. Does not notify global observers.
 851    #[cfg(any(test, feature = "test-support"))]
 852    pub fn remove_global<G: Any>(&mut self) -> G {
 853        let global_type = TypeId::of::<G>();
 854        *self
 855            .globals_by_type
 856            .remove(&global_type)
 857            .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
 858            .downcast()
 859            .unwrap()
 860    }
 861
 862    /// Update the global of the given type with a closure. Unlike `global_mut`, this method provides
 863    /// your closure with mutable access to the `AppContext` and the global simultaneously.
 864    pub fn update_global<G: 'static, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R {
 865        let mut global = self.lease_global::<G>();
 866        let result = f(&mut global, self);
 867        self.end_global_lease(global);
 868        result
 869    }
 870
 871    /// Register a callback to be invoked when a global of the given type is updated.
 872    pub fn observe_global<G: 'static>(
 873        &mut self,
 874        mut f: impl FnMut(&mut Self) + 'static,
 875    ) -> Subscription {
 876        self.global_observers.insert(
 877            TypeId::of::<G>(),
 878            Box::new(move |cx| {
 879                f(cx);
 880                true
 881            }),
 882        )
 883    }
 884
 885    /// Move the global of the given type to the stack.
 886    pub(crate) fn lease_global<G: 'static>(&mut self) -> GlobalLease<G> {
 887        GlobalLease::new(
 888            self.globals_by_type
 889                .remove(&TypeId::of::<G>())
 890                .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
 891                .unwrap(),
 892        )
 893    }
 894
 895    /// Restore the global of the given type after it is moved to the stack.
 896    pub(crate) fn end_global_lease<G: 'static>(&mut self, lease: GlobalLease<G>) {
 897        let global_type = TypeId::of::<G>();
 898        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 899        self.globals_by_type.insert(global_type, lease.global);
 900    }
 901
 902    pub fn observe_new_views<V: 'static>(
 903        &mut self,
 904        on_new: impl 'static + Fn(&mut V, &mut ViewContext<V>),
 905    ) -> Subscription {
 906        self.new_view_observers.insert(
 907            TypeId::of::<V>(),
 908            Box::new(move |any_view: AnyView, cx: &mut WindowContext| {
 909                any_view
 910                    .downcast::<V>()
 911                    .unwrap()
 912                    .update(cx, |view_state, cx| {
 913                        on_new(view_state, cx);
 914                    })
 915            }),
 916        )
 917    }
 918
 919    pub fn observe_release<E, T>(
 920        &mut self,
 921        handle: &E,
 922        on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
 923    ) -> Subscription
 924    where
 925        E: Entity<T>,
 926        T: 'static,
 927    {
 928        self.release_listeners.insert(
 929            handle.entity_id(),
 930            Box::new(move |entity, cx| {
 931                let entity = entity.downcast_mut().expect("invalid entity type");
 932                on_release(entity, cx)
 933            }),
 934        )
 935    }
 936
 937    pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
 938        self.text_style_stack.push(text_style);
 939    }
 940
 941    pub(crate) fn pop_text_style(&mut self) {
 942        self.text_style_stack.pop();
 943    }
 944
 945    /// Register key bindings.
 946    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
 947        self.keymap.lock().add_bindings(bindings);
 948        self.pending_effects.push_back(Effect::Refresh);
 949    }
 950
 951    /// Register a global listener for actions invoked via the keyboard.
 952    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
 953        self.global_action_listeners
 954            .entry(TypeId::of::<A>())
 955            .or_default()
 956            .push(Box::new(move |action, phase, cx| {
 957                if phase == DispatchPhase::Bubble {
 958                    let action = action.as_any().downcast_ref().unwrap();
 959                    listener(action, cx)
 960                }
 961            }));
 962    }
 963
 964    /// Event handlers propagate events by default. Call this method to stop dispatching to
 965    /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
 966    /// the opposite of [propagate]. It's also possible to cancel a call to [propagate] by
 967    /// calling this method before effects are flushed.
 968    pub fn stop_propagation(&mut self) {
 969        self.propagate_event = false;
 970    }
 971
 972    /// Action handlers stop propagation by default during the bubble phase of action dispatch
 973    /// dispatching to action handlers higher in the element tree. This is the opposite of
 974    /// [stop_propagation]. It's also possible to cancel a call to [stop_propagate] by calling
 975    /// this method before effects are flushed.
 976    pub fn propagate(&mut self) {
 977        self.propagate_event = true;
 978    }
 979
 980    pub fn build_action(
 981        &self,
 982        name: &str,
 983        data: Option<serde_json::Value>,
 984    ) -> Result<Box<dyn Action>> {
 985        self.actions.build_action(name, data)
 986    }
 987
 988    pub fn all_action_names(&self) -> &[SharedString] {
 989        self.actions.all_action_names()
 990    }
 991
 992    pub fn on_app_quit<Fut>(
 993        &mut self,
 994        mut on_quit: impl FnMut(&mut AppContext) -> Fut + 'static,
 995    ) -> Subscription
 996    where
 997        Fut: 'static + Future<Output = ()>,
 998    {
 999        self.quit_observers.insert(
1000            (),
1001            Box::new(move |cx| {
1002                let future = on_quit(cx);
1003                async move { future.await }.boxed_local()
1004            }),
1005        )
1006    }
1007}
1008
1009impl Context for AppContext {
1010    type Result<T> = T;
1011
1012    /// Build an entity that is owned by the application. The given function will be invoked with
1013    /// a `ModelContext` and must return an object representing the entity. A `Model` will be returned
1014    /// which can be used to access the entity in a context.
1015    fn build_model<T: 'static>(
1016        &mut self,
1017        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1018    ) -> Model<T> {
1019        self.update(|cx| {
1020            let slot = cx.entities.reserve();
1021            let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
1022            cx.entities.insert(slot, entity)
1023        })
1024    }
1025
1026    /// Update the entity referenced by the given model. The function is passed a mutable reference to the
1027    /// entity along with a `ModelContext` for the entity.
1028    fn update_model<T: 'static, R>(
1029        &mut self,
1030        model: &Model<T>,
1031        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1032    ) -> R {
1033        self.update(|cx| {
1034            let mut entity = cx.entities.lease(model);
1035            let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
1036            cx.entities.end_lease(entity);
1037            result
1038        })
1039    }
1040
1041    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
1042    where
1043        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1044    {
1045        self.update(|cx| {
1046            let mut window = cx
1047                .windows
1048                .get_mut(handle.id)
1049                .ok_or_else(|| anyhow!("window not found"))?
1050                .take()
1051                .unwrap();
1052
1053            let root_view = window.root_view.clone().unwrap();
1054            let result = update(root_view, &mut WindowContext::new(cx, &mut window));
1055
1056            if window.removed {
1057                cx.windows.remove(handle.id);
1058            } else {
1059                cx.windows
1060                    .get_mut(handle.id)
1061                    .ok_or_else(|| anyhow!("window not found"))?
1062                    .replace(window);
1063            }
1064
1065            Ok(result)
1066        })
1067    }
1068
1069    fn read_model<T, R>(
1070        &self,
1071        handle: &Model<T>,
1072        read: impl FnOnce(&T, &AppContext) -> R,
1073    ) -> Self::Result<R>
1074    where
1075        T: 'static,
1076    {
1077        let entity = self.entities.read(handle);
1078        read(entity, self)
1079    }
1080
1081    fn read_window<T, R>(
1082        &self,
1083        window: &WindowHandle<T>,
1084        read: impl FnOnce(View<T>, &AppContext) -> R,
1085    ) -> Result<R>
1086    where
1087        T: 'static,
1088    {
1089        let window = self
1090            .windows
1091            .get(window.id)
1092            .ok_or_else(|| anyhow!("window not found"))?
1093            .as_ref()
1094            .unwrap();
1095
1096        let root_view = window.root_view.clone().unwrap();
1097        let view = root_view
1098            .downcast::<T>()
1099            .map_err(|_| anyhow!("root view's type has changed"))?;
1100
1101        Ok(read(view, self))
1102    }
1103}
1104
1105/// These effects are processed at the end of each application update cycle.
1106pub(crate) enum Effect {
1107    Notify {
1108        emitter: EntityId,
1109    },
1110    Emit {
1111        emitter: EntityId,
1112        event_type: TypeId,
1113        event: Box<dyn Any>,
1114    },
1115    FocusChanged {
1116        window_handle: AnyWindowHandle,
1117        focused: Option<FocusId>,
1118    },
1119    Refresh,
1120    NotifyGlobalObservers {
1121        global_type: TypeId,
1122    },
1123    Defer {
1124        callback: Box<dyn FnOnce(&mut AppContext) + 'static>,
1125    },
1126}
1127
1128/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
1129pub(crate) struct GlobalLease<G: 'static> {
1130    global: Box<dyn Any>,
1131    global_type: PhantomData<G>,
1132}
1133
1134impl<G: 'static> GlobalLease<G> {
1135    fn new(global: Box<dyn Any>) -> Self {
1136        GlobalLease {
1137            global,
1138            global_type: PhantomData,
1139        }
1140    }
1141}
1142
1143impl<G: 'static> Deref for GlobalLease<G> {
1144    type Target = G;
1145
1146    fn deref(&self) -> &Self::Target {
1147        self.global.downcast_ref().unwrap()
1148    }
1149}
1150
1151impl<G: 'static> DerefMut for GlobalLease<G> {
1152    fn deref_mut(&mut self) -> &mut Self::Target {
1153        self.global.downcast_mut().unwrap()
1154    }
1155}
1156
1157/// Contains state associated with an active drag operation, started by dragging an element
1158/// within the window or by dragging into the app from the underlying platform.
1159pub struct AnyDrag {
1160    pub view: AnyView,
1161    pub cursor_offset: Point<Pixels>,
1162}
1163
1164#[derive(Clone)]
1165pub(crate) struct AnyTooltip {
1166    pub view: AnyView,
1167    pub cursor_offset: Point<Pixels>,
1168}