app.rs

   1pub mod action;
   2mod callback_collection;
   3mod menu;
   4pub(crate) mod ref_counts;
   5#[cfg(any(test, feature = "test-support"))]
   6pub mod test_app_context;
   7pub(crate) mod window;
   8mod window_input_handler;
   9
  10use std::{
  11    any::{type_name, Any, TypeId},
  12    cell::RefCell,
  13    fmt::{self, Debug},
  14    hash::{Hash, Hasher},
  15    marker::PhantomData,
  16    mem,
  17    ops::{Deref, DerefMut, Range},
  18    path::{Path, PathBuf},
  19    pin::Pin,
  20    rc::{self, Rc},
  21    sync::{Arc, Weak},
  22    time::Duration,
  23};
  24
  25use anyhow::{anyhow, Context, Result};
  26use parking_lot::Mutex;
  27use postage::oneshot;
  28use smol::prelude::*;
  29use uuid::Uuid;
  30
  31pub use action::*;
  32use callback_collection::CallbackCollection;
  33use collections::{hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque};
  34pub use menu::*;
  35use platform::Event;
  36#[cfg(any(test, feature = "test-support"))]
  37use ref_counts::LeakDetector;
  38#[cfg(any(test, feature = "test-support"))]
  39pub use test_app_context::{ContextHandle, TestAppContext};
  40use window_input_handler::WindowInputHandler;
  41
  42use crate::{
  43    elements::{AnyRootElement, Element, RootElement},
  44    executor::{self, Task},
  45    keymap_matcher::{self, Binding, KeymapContext, KeymapMatcher, Keystroke, MatchResult},
  46    platform::{
  47        self, FontSystem, KeyDownEvent, KeyUpEvent, ModifiersChangedEvent, MouseButton,
  48        PathPromptOptions, Platform, PromptLevel, WindowBounds, WindowOptions,
  49    },
  50    util::post_inc,
  51    window::{Window, WindowContext},
  52    AssetCache, AssetSource, ClipboardItem, FontCache, MouseRegionId,
  53};
  54
  55use self::ref_counts::RefCounts;
  56
  57pub trait Entity: 'static {
  58    type Event;
  59
  60    fn release(&mut self, _: &mut AppContext) {}
  61    fn app_will_quit(
  62        &mut self,
  63        _: &mut AppContext,
  64    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
  65        None
  66    }
  67}
  68
  69pub trait View: Entity + Sized {
  70    fn ui_name() -> &'static str;
  71    fn render(&mut self, cx: &mut ViewContext<'_, '_, '_, Self>) -> Element<Self>;
  72    fn focus_in(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {}
  73    fn focus_out(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {}
  74    fn key_down(&mut self, _: &KeyDownEvent, _: &mut ViewContext<Self>) -> bool {
  75        false
  76    }
  77    fn key_up(&mut self, _: &KeyUpEvent, _: &mut ViewContext<Self>) -> bool {
  78        false
  79    }
  80    fn modifiers_changed(&mut self, _: &ModifiersChangedEvent, _: &mut ViewContext<Self>) -> bool {
  81        false
  82    }
  83
  84    fn keymap_context(&self, _: &AppContext) -> keymap_matcher::KeymapContext {
  85        Self::default_keymap_context()
  86    }
  87    fn default_keymap_context() -> keymap_matcher::KeymapContext {
  88        let mut cx = keymap_matcher::KeymapContext::default();
  89        cx.add_identifier(Self::ui_name());
  90        cx
  91    }
  92    fn debug_json(&self, _: &AppContext) -> serde_json::Value {
  93        serde_json::Value::Null
  94    }
  95
  96    fn text_for_range(&self, _: Range<usize>, _: &AppContext) -> Option<String> {
  97        None
  98    }
  99    fn selected_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
 100        None
 101    }
 102    fn marked_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
 103        None
 104    }
 105    fn unmark_text(&mut self, _: &mut ViewContext<Self>) {}
 106    fn replace_text_in_range(
 107        &mut self,
 108        _: Option<Range<usize>>,
 109        _: &str,
 110        _: &mut ViewContext<Self>,
 111    ) {
 112    }
 113    fn replace_and_mark_text_in_range(
 114        &mut self,
 115        _: Option<Range<usize>>,
 116        _: &str,
 117        _: Option<Range<usize>>,
 118        _: &mut ViewContext<Self>,
 119    ) {
 120    }
 121}
 122
 123pub trait ReadModel {
 124    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T;
 125}
 126
 127pub trait ReadModelWith {
 128    fn read_model_with<E: Entity, T>(
 129        &self,
 130        handle: &ModelHandle<E>,
 131        read: &mut dyn FnMut(&E, &AppContext) -> T,
 132    ) -> T;
 133}
 134
 135pub trait UpdateModel {
 136    fn update_model<T: Entity, O>(
 137        &mut self,
 138        handle: &ModelHandle<T>,
 139        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
 140    ) -> O;
 141}
 142
 143pub trait UpgradeModelHandle {
 144    fn upgrade_model_handle<T: Entity>(
 145        &self,
 146        handle: &WeakModelHandle<T>,
 147    ) -> Option<ModelHandle<T>>;
 148
 149    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool;
 150
 151    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle>;
 152}
 153
 154pub trait UpgradeViewHandle {
 155    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>>;
 156
 157    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle>;
 158}
 159
 160pub trait ReadView {
 161    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T;
 162}
 163
 164pub trait ReadViewWith {
 165    fn read_view_with<V, T>(
 166        &self,
 167        handle: &ViewHandle<V>,
 168        read: &mut dyn FnMut(&V, &AppContext) -> T,
 169    ) -> T
 170    where
 171        V: View;
 172}
 173
 174pub trait UpdateView {
 175    fn update_view<T, S>(
 176        &mut self,
 177        handle: &ViewHandle<T>,
 178        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 179    ) -> S
 180    where
 181        T: View;
 182}
 183
 184#[derive(Clone)]
 185pub struct App(Rc<RefCell<AppContext>>);
 186
 187#[derive(Clone)]
 188pub struct AsyncAppContext(Rc<RefCell<AppContext>>);
 189
 190impl App {
 191    pub fn new(asset_source: impl AssetSource) -> Result<Self> {
 192        let platform = platform::current::platform();
 193        let foreground = Rc::new(executor::Foreground::platform(platform.dispatcher())?);
 194        let foreground_platform = platform::current::foreground_platform(foreground.clone());
 195        let app = Self(Rc::new(RefCell::new(AppContext::new(
 196            foreground,
 197            Arc::new(executor::Background::new()),
 198            platform.clone(),
 199            foreground_platform.clone(),
 200            Arc::new(FontCache::new(platform.fonts())),
 201            Default::default(),
 202            asset_source,
 203        ))));
 204
 205        foreground_platform.on_quit(Box::new({
 206            let cx = app.0.clone();
 207            move || {
 208                cx.borrow_mut().quit();
 209            }
 210        }));
 211        setup_menu_handlers(foreground_platform.as_ref(), &app);
 212
 213        app.0.borrow_mut().weak_self = Some(Rc::downgrade(&app.0));
 214        Ok(app)
 215    }
 216
 217    pub fn background(&self) -> Arc<executor::Background> {
 218        self.0.borrow().background().clone()
 219    }
 220
 221    pub fn on_become_active<F>(self, mut callback: F) -> Self
 222    where
 223        F: 'static + FnMut(&mut AppContext),
 224    {
 225        let cx = self.0.clone();
 226        self.0
 227            .borrow_mut()
 228            .foreground_platform
 229            .on_become_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 230        self
 231    }
 232
 233    pub fn on_resign_active<F>(self, mut callback: F) -> Self
 234    where
 235        F: 'static + FnMut(&mut AppContext),
 236    {
 237        let cx = self.0.clone();
 238        self.0
 239            .borrow_mut()
 240            .foreground_platform
 241            .on_resign_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 242        self
 243    }
 244
 245    pub fn on_quit<F>(&mut self, mut callback: F) -> &mut Self
 246    where
 247        F: 'static + FnMut(&mut AppContext),
 248    {
 249        let cx = self.0.clone();
 250        self.0
 251            .borrow_mut()
 252            .foreground_platform
 253            .on_quit(Box::new(move || callback(&mut *cx.borrow_mut())));
 254        self
 255    }
 256
 257    /// Handle the application being re-activated when no windows are open.
 258    pub fn on_reopen<F>(&mut self, mut callback: F) -> &mut Self
 259    where
 260        F: 'static + FnMut(&mut AppContext),
 261    {
 262        let cx = self.0.clone();
 263        self.0
 264            .borrow_mut()
 265            .foreground_platform
 266            .on_reopen(Box::new(move || callback(&mut *cx.borrow_mut())));
 267        self
 268    }
 269
 270    pub fn on_event<F>(&mut self, mut callback: F) -> &mut Self
 271    where
 272        F: 'static + FnMut(Event, &mut AppContext) -> bool,
 273    {
 274        let cx = self.0.clone();
 275        self.0
 276            .borrow_mut()
 277            .foreground_platform
 278            .on_event(Box::new(move |event| {
 279                callback(event, &mut *cx.borrow_mut())
 280            }));
 281        self
 282    }
 283
 284    pub fn on_open_urls<F>(&mut self, mut callback: F) -> &mut Self
 285    where
 286        F: 'static + FnMut(Vec<String>, &mut AppContext),
 287    {
 288        let cx = self.0.clone();
 289        self.0
 290            .borrow_mut()
 291            .foreground_platform
 292            .on_open_urls(Box::new(move |urls| callback(urls, &mut *cx.borrow_mut())));
 293        self
 294    }
 295
 296    pub fn run<F>(self, on_finish_launching: F)
 297    where
 298        F: 'static + FnOnce(&mut AppContext),
 299    {
 300        let platform = self.0.borrow().foreground_platform.clone();
 301        platform.run(Box::new(move || {
 302            let mut cx = self.0.borrow_mut();
 303            let cx = &mut *cx;
 304            crate::views::init(cx);
 305            on_finish_launching(cx);
 306        }))
 307    }
 308
 309    pub fn platform(&self) -> Arc<dyn Platform> {
 310        self.0.borrow().platform.clone()
 311    }
 312
 313    pub fn font_cache(&self) -> Arc<FontCache> {
 314        self.0.borrow().font_cache.clone()
 315    }
 316
 317    fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, callback: F) -> T {
 318        let mut state = self.0.borrow_mut();
 319        let result = state.update(callback);
 320        state.pending_notifications.clear();
 321        result
 322    }
 323
 324    fn update_window<T, F: FnOnce(&mut WindowContext) -> T>(
 325        &mut self,
 326        window_id: usize,
 327        callback: F,
 328    ) -> Option<T> {
 329        let mut state = self.0.borrow_mut();
 330        let result = state.update_window(window_id, callback);
 331        state.pending_notifications.clear();
 332        result
 333    }
 334}
 335
 336impl AsyncAppContext {
 337    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
 338    where
 339        F: FnOnce(AsyncAppContext) -> Fut,
 340        Fut: 'static + Future<Output = T>,
 341        T: 'static,
 342    {
 343        self.0.borrow().foreground.spawn(f(self.clone()))
 344    }
 345
 346    pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
 347        callback(&*self.0.borrow())
 348    }
 349
 350    pub fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, callback: F) -> T {
 351        self.0.borrow_mut().update(callback)
 352    }
 353
 354    fn update_window<T, F: FnOnce(&mut WindowContext) -> T>(
 355        &mut self,
 356        window_id: usize,
 357        callback: F,
 358    ) -> Option<T> {
 359        self.0.borrow_mut().update_window(window_id, callback)
 360    }
 361
 362    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 363    where
 364        T: Entity,
 365        F: FnOnce(&mut ModelContext<T>) -> T,
 366    {
 367        self.update(|cx| cx.add_model(build_model))
 368    }
 369
 370    pub fn add_window<T, F>(
 371        &mut self,
 372        window_options: WindowOptions,
 373        build_root_view: F,
 374    ) -> (usize, ViewHandle<T>)
 375    where
 376        T: View,
 377        F: FnOnce(&mut ViewContext<T>) -> T,
 378    {
 379        self.update(|cx| cx.add_window(window_options, build_root_view))
 380    }
 381
 382    pub fn remove_window(&mut self, window_id: usize) {
 383        self.update(|cx| cx.remove_window(window_id))
 384    }
 385
 386    pub fn activate_window(&mut self, window_id: usize) {
 387        self.update_window(window_id, |cx| cx.activate_window());
 388    }
 389
 390    // TODO: Can we eliminate this method and move it to WindowContext then call it with update_window?s
 391    pub fn prompt(
 392        &mut self,
 393        window_id: usize,
 394        level: PromptLevel,
 395        msg: &str,
 396        answers: &[&str],
 397    ) -> Option<oneshot::Receiver<usize>> {
 398        self.update_window(window_id, |cx| cx.prompt(level, msg, answers))
 399    }
 400
 401    pub fn platform(&self) -> Arc<dyn Platform> {
 402        self.0.borrow().platform().clone()
 403    }
 404
 405    pub fn foreground(&self) -> Rc<executor::Foreground> {
 406        self.0.borrow().foreground.clone()
 407    }
 408
 409    pub fn background(&self) -> Arc<executor::Background> {
 410        self.0.borrow().background.clone()
 411    }
 412}
 413
 414impl UpdateModel for AsyncAppContext {
 415    fn update_model<E: Entity, O>(
 416        &mut self,
 417        handle: &ModelHandle<E>,
 418        update: &mut dyn FnMut(&mut E, &mut ModelContext<E>) -> O,
 419    ) -> O {
 420        self.0.borrow_mut().update_model(handle, update)
 421    }
 422}
 423
 424impl UpgradeModelHandle for AsyncAppContext {
 425    fn upgrade_model_handle<T: Entity>(
 426        &self,
 427        handle: &WeakModelHandle<T>,
 428    ) -> Option<ModelHandle<T>> {
 429        self.0.borrow().upgrade_model_handle(handle)
 430    }
 431
 432    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
 433        self.0.borrow().model_handle_is_upgradable(handle)
 434    }
 435
 436    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
 437        self.0.borrow().upgrade_any_model_handle(handle)
 438    }
 439}
 440
 441impl UpgradeViewHandle for AsyncAppContext {
 442    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
 443        self.0.borrow_mut().upgrade_view_handle(handle)
 444    }
 445
 446    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
 447        self.0.borrow_mut().upgrade_any_view_handle(handle)
 448    }
 449}
 450
 451impl ReadModelWith for AsyncAppContext {
 452    fn read_model_with<E: Entity, T>(
 453        &self,
 454        handle: &ModelHandle<E>,
 455        read: &mut dyn FnMut(&E, &AppContext) -> T,
 456    ) -> T {
 457        let cx = self.0.borrow();
 458        let cx = &*cx;
 459        read(handle.read(cx), cx)
 460    }
 461}
 462
 463impl UpdateView for AsyncAppContext {
 464    fn update_view<T, S>(
 465        &mut self,
 466        handle: &ViewHandle<T>,
 467        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 468    ) -> S
 469    where
 470        T: View,
 471    {
 472        self.0.borrow_mut().update_view(handle, update)
 473    }
 474}
 475
 476impl ReadViewWith for AsyncAppContext {
 477    fn read_view_with<V, T>(
 478        &self,
 479        handle: &ViewHandle<V>,
 480        read: &mut dyn FnMut(&V, &AppContext) -> T,
 481    ) -> T
 482    where
 483        V: View,
 484    {
 485        let cx = self.0.borrow();
 486        let cx = &*cx;
 487        read(handle.read(cx), cx)
 488    }
 489}
 490
 491type ActionCallback = dyn FnMut(&mut dyn AnyView, &dyn Action, &mut WindowContext, usize);
 492type GlobalActionCallback = dyn FnMut(&dyn Action, &mut AppContext);
 493
 494type SubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool>;
 495type GlobalSubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut AppContext)>;
 496type ObservationCallback = Box<dyn FnMut(&mut AppContext) -> bool>;
 497type GlobalObservationCallback = Box<dyn FnMut(&mut AppContext)>;
 498type FocusObservationCallback = Box<dyn FnMut(bool, &mut WindowContext) -> bool>;
 499type ReleaseObservationCallback = Box<dyn FnMut(&dyn Any, &mut AppContext)>;
 500type ActionObservationCallback = Box<dyn FnMut(TypeId, &mut AppContext)>;
 501type WindowActivationCallback = Box<dyn FnMut(bool, &mut WindowContext) -> bool>;
 502type WindowFullscreenCallback = Box<dyn FnMut(bool, &mut AppContext) -> bool>;
 503type WindowBoundsCallback = Box<dyn FnMut(WindowBounds, Uuid, &mut AppContext) -> bool>;
 504type KeystrokeCallback =
 505    Box<dyn FnMut(&Keystroke, &MatchResult, Option<&Box<dyn Action>>, &mut AppContext) -> bool>;
 506type ActiveLabeledTasksCallback = Box<dyn FnMut(&mut AppContext) -> bool>;
 507type DeserializeActionCallback = fn(json: &str) -> anyhow::Result<Box<dyn Action>>;
 508type WindowShouldCloseSubscriptionCallback = Box<dyn FnMut(&mut AppContext) -> bool>;
 509
 510pub struct AppContext {
 511    models: HashMap<usize, Box<dyn AnyModel>>,
 512    views: HashMap<(usize, usize), Box<dyn AnyView>>,
 513    pub(crate) parents: HashMap<(usize, usize), ParentId>,
 514    windows: HashMap<usize, Window>,
 515    globals: HashMap<TypeId, Box<dyn Any>>,
 516    element_states: HashMap<ElementStateId, Box<dyn Any>>,
 517    background: Arc<executor::Background>,
 518    ref_counts: Arc<Mutex<RefCounts>>,
 519
 520    weak_self: Option<rc::Weak<RefCell<Self>>>,
 521    platform: Arc<dyn Platform>,
 522    foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 523    pub asset_cache: Arc<AssetCache>,
 524    font_system: Arc<dyn FontSystem>,
 525    pub font_cache: Arc<FontCache>,
 526    action_deserializers: HashMap<&'static str, (TypeId, DeserializeActionCallback)>,
 527    capture_actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 528    // Entity Types -> { Action Types -> Action Handlers }
 529    actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 530    // Action Types -> Action Handlers
 531    global_actions: HashMap<TypeId, Box<GlobalActionCallback>>,
 532    keystroke_matcher: KeymapMatcher,
 533    next_entity_id: usize,
 534    next_window_id: usize,
 535    next_subscription_id: usize,
 536    frame_count: usize,
 537
 538    subscriptions: CallbackCollection<usize, SubscriptionCallback>,
 539    global_subscriptions: CallbackCollection<TypeId, GlobalSubscriptionCallback>,
 540    observations: CallbackCollection<usize, ObservationCallback>,
 541    global_observations: CallbackCollection<TypeId, GlobalObservationCallback>,
 542    focus_observations: CallbackCollection<usize, FocusObservationCallback>,
 543    release_observations: CallbackCollection<usize, ReleaseObservationCallback>,
 544    action_dispatch_observations: CallbackCollection<(), ActionObservationCallback>,
 545    window_activation_observations: CallbackCollection<usize, WindowActivationCallback>,
 546    window_fullscreen_observations: CallbackCollection<usize, WindowFullscreenCallback>,
 547    window_bounds_observations: CallbackCollection<usize, WindowBoundsCallback>,
 548    keystroke_observations: CallbackCollection<usize, KeystrokeCallback>,
 549    active_labeled_task_observations: CallbackCollection<(), ActiveLabeledTasksCallback>,
 550
 551    foreground: Rc<executor::Foreground>,
 552    pending_effects: VecDeque<Effect>,
 553    pending_notifications: HashSet<usize>,
 554    pending_global_notifications: HashSet<TypeId>,
 555    pending_flushes: usize,
 556    flushing_effects: bool,
 557    halt_action_dispatch: bool,
 558    next_labeled_task_id: usize,
 559    active_labeled_tasks: BTreeMap<usize, &'static str>,
 560}
 561
 562impl AppContext {
 563    fn new(
 564        foreground: Rc<executor::Foreground>,
 565        background: Arc<executor::Background>,
 566        platform: Arc<dyn platform::Platform>,
 567        foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 568        font_cache: Arc<FontCache>,
 569        ref_counts: RefCounts,
 570        asset_source: impl AssetSource,
 571    ) -> Self {
 572        Self {
 573            models: Default::default(),
 574            views: Default::default(),
 575            parents: Default::default(),
 576            windows: Default::default(),
 577            globals: Default::default(),
 578            element_states: Default::default(),
 579            ref_counts: Arc::new(Mutex::new(ref_counts)),
 580            background,
 581
 582            weak_self: None,
 583            font_system: platform.fonts(),
 584            platform,
 585            foreground_platform,
 586            font_cache,
 587            asset_cache: Arc::new(AssetCache::new(asset_source)),
 588            action_deserializers: Default::default(),
 589            capture_actions: Default::default(),
 590            actions: Default::default(),
 591            global_actions: Default::default(),
 592            keystroke_matcher: KeymapMatcher::default(),
 593            next_entity_id: 0,
 594            next_window_id: 0,
 595            next_subscription_id: 0,
 596            frame_count: 0,
 597            subscriptions: Default::default(),
 598            global_subscriptions: Default::default(),
 599            observations: Default::default(),
 600            focus_observations: Default::default(),
 601            release_observations: Default::default(),
 602            global_observations: Default::default(),
 603            window_activation_observations: Default::default(),
 604            window_fullscreen_observations: Default::default(),
 605            window_bounds_observations: Default::default(),
 606            keystroke_observations: Default::default(),
 607            action_dispatch_observations: Default::default(),
 608            active_labeled_task_observations: Default::default(),
 609            foreground,
 610            pending_effects: VecDeque::new(),
 611            pending_notifications: Default::default(),
 612            pending_global_notifications: Default::default(),
 613            pending_flushes: 0,
 614            flushing_effects: false,
 615            halt_action_dispatch: false,
 616            next_labeled_task_id: 0,
 617            active_labeled_tasks: Default::default(),
 618        }
 619    }
 620
 621    pub fn background(&self) -> &Arc<executor::Background> {
 622        &self.background
 623    }
 624
 625    pub fn font_cache(&self) -> &Arc<FontCache> {
 626        &self.font_cache
 627    }
 628
 629    pub fn platform(&self) -> &Arc<dyn Platform> {
 630        &self.platform
 631    }
 632
 633    pub fn has_global<T: 'static>(&self) -> bool {
 634        self.globals.contains_key(&TypeId::of::<T>())
 635    }
 636
 637    pub fn global<T: 'static>(&self) -> &T {
 638        if let Some(global) = self.globals.get(&TypeId::of::<T>()) {
 639            global.downcast_ref().unwrap()
 640        } else {
 641            panic!("no global has been added for {}", type_name::<T>());
 642        }
 643    }
 644
 645    pub fn upgrade(&self) -> App {
 646        App(self.weak_self.as_ref().unwrap().upgrade().unwrap())
 647    }
 648
 649    pub fn quit(&mut self) {
 650        let mut futures = Vec::new();
 651
 652        self.update(|cx| {
 653            for model_id in cx.models.keys().copied().collect::<Vec<_>>() {
 654                let mut model = cx.models.remove(&model_id).unwrap();
 655                futures.extend(model.app_will_quit(cx));
 656                cx.models.insert(model_id, model);
 657            }
 658
 659            for view_id in cx.views.keys().copied().collect::<Vec<_>>() {
 660                let mut view = cx.views.remove(&view_id).unwrap();
 661                futures.extend(view.app_will_quit(cx));
 662                cx.views.insert(view_id, view);
 663            }
 664        });
 665
 666        self.remove_all_windows();
 667
 668        let futures = futures::future::join_all(futures);
 669        if self
 670            .background
 671            .block_with_timeout(Duration::from_millis(100), futures)
 672            .is_err()
 673        {
 674            log::error!("timed out waiting on app_will_quit");
 675        }
 676    }
 677
 678    pub fn remove_all_windows(&mut self) {
 679        self.windows.clear();
 680        self.flush_effects();
 681    }
 682
 683    pub fn foreground(&self) -> &Rc<executor::Foreground> {
 684        &self.foreground
 685    }
 686
 687    pub fn deserialize_action(
 688        &self,
 689        name: &str,
 690        argument: Option<&str>,
 691    ) -> Result<Box<dyn Action>> {
 692        let callback = self
 693            .action_deserializers
 694            .get(name)
 695            .ok_or_else(|| anyhow!("unknown action {}", name))?
 696            .1;
 697        callback(argument.unwrap_or("{}"))
 698            .with_context(|| format!("invalid data for action {}", name))
 699    }
 700
 701    pub fn add_action<A, V, F, R>(&mut self, handler: F)
 702    where
 703        A: Action,
 704        V: View,
 705        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> R,
 706    {
 707        self.add_action_internal(handler, false)
 708    }
 709
 710    pub fn capture_action<A, V, F>(&mut self, handler: F)
 711    where
 712        A: Action,
 713        V: View,
 714        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
 715    {
 716        self.add_action_internal(handler, true)
 717    }
 718
 719    fn add_action_internal<A, V, F, R>(&mut self, mut handler: F, capture: bool)
 720    where
 721        A: Action,
 722        V: View,
 723        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> R,
 724    {
 725        let handler = Box::new(
 726            move |view: &mut dyn AnyView,
 727                  action: &dyn Action,
 728                  cx: &mut WindowContext,
 729                  view_id: usize| {
 730                let action = action.as_any().downcast_ref().unwrap();
 731                let mut cx = ViewContext::mutable(cx, view_id);
 732                handler(
 733                    view.as_any_mut()
 734                        .downcast_mut()
 735                        .expect("downcast is type safe"),
 736                    action,
 737                    &mut cx,
 738                );
 739            },
 740        );
 741
 742        self.action_deserializers
 743            .entry(A::qualified_name())
 744            .or_insert((TypeId::of::<A>(), A::from_json_str));
 745
 746        let actions = if capture {
 747            &mut self.capture_actions
 748        } else {
 749            &mut self.actions
 750        };
 751
 752        actions
 753            .entry(TypeId::of::<V>())
 754            .or_default()
 755            .entry(TypeId::of::<A>())
 756            .or_default()
 757            .push(handler);
 758    }
 759
 760    pub fn add_async_action<A, V, F>(&mut self, mut handler: F)
 761    where
 762        A: Action,
 763        V: View,
 764        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> Option<Task<Result<()>>>,
 765    {
 766        self.add_action(move |view, action, cx| {
 767            if let Some(task) = handler(view, action, cx) {
 768                task.detach_and_log_err(cx);
 769            }
 770        })
 771    }
 772
 773    pub fn add_global_action<A, F>(&mut self, mut handler: F)
 774    where
 775        A: Action,
 776        F: 'static + FnMut(&A, &mut AppContext),
 777    {
 778        let handler = Box::new(move |action: &dyn Action, cx: &mut AppContext| {
 779            let action = action.as_any().downcast_ref().unwrap();
 780            handler(action, cx);
 781        });
 782
 783        self.action_deserializers
 784            .entry(A::qualified_name())
 785            .or_insert((TypeId::of::<A>(), A::from_json_str));
 786
 787        if self
 788            .global_actions
 789            .insert(TypeId::of::<A>(), handler)
 790            .is_some()
 791        {
 792            panic!(
 793                "registered multiple global handlers for {}",
 794                type_name::<A>()
 795            );
 796        }
 797    }
 798
 799    pub fn has_window(&self, window_id: usize) -> bool {
 800        self.window_ids()
 801            .find(|window| window == &window_id)
 802            .is_some()
 803    }
 804
 805    pub fn window_is_active(&self, window_id: usize) -> bool {
 806        self.windows.get(&window_id).map_or(false, |w| w.is_active)
 807    }
 808
 809    pub fn root_view(&self, window_id: usize) -> Option<&AnyViewHandle> {
 810        self.windows.get(&window_id).map(|w| w.root_view())
 811    }
 812
 813    pub fn window_ids(&self) -> impl Iterator<Item = usize> + '_ {
 814        self.windows.keys().copied()
 815    }
 816
 817    pub fn view_ui_name(&self, window_id: usize, view_id: usize) -> Option<&'static str> {
 818        Some(self.views.get(&(window_id, view_id))?.ui_name())
 819    }
 820
 821    pub fn view_type_id(&self, window_id: usize, view_id: usize) -> Option<TypeId> {
 822        self.views
 823            .get(&(window_id, view_id))
 824            .map(|view| view.as_any().type_id())
 825    }
 826
 827    pub fn active_labeled_tasks<'a>(
 828        &'a self,
 829    ) -> impl DoubleEndedIterator<Item = &'static str> + 'a {
 830        self.active_labeled_tasks.values().cloned()
 831    }
 832
 833    pub(crate) fn start_frame(&mut self) {
 834        self.frame_count += 1;
 835    }
 836
 837    pub fn update<T, F: FnOnce(&mut Self) -> T>(&mut self, callback: F) -> T {
 838        self.pending_flushes += 1;
 839        let result = callback(self);
 840        self.flush_effects();
 841        result
 842    }
 843
 844    pub fn read_window<T, F: FnOnce(&WindowContext) -> T>(
 845        &self,
 846        window_id: usize,
 847        callback: F,
 848    ) -> Option<T> {
 849        let window = self.windows.get(&window_id)?;
 850        let window_context = WindowContext::immutable(self, &window, window_id);
 851        Some(callback(&window_context))
 852    }
 853
 854    pub fn update_window<T, F: FnOnce(&mut WindowContext) -> T>(
 855        &mut self,
 856        window_id: usize,
 857        callback: F,
 858    ) -> Option<T> {
 859        self.update(|app_context| {
 860            let mut window = app_context.windows.remove(&window_id)?;
 861            let mut window_context = WindowContext::mutable(app_context, &mut window, window_id);
 862            let result = callback(&mut window_context);
 863            app_context.windows.insert(window_id, window);
 864            Some(result)
 865        })
 866    }
 867
 868    pub fn prompt_for_paths(
 869        &self,
 870        options: PathPromptOptions,
 871    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 872        self.foreground_platform.prompt_for_paths(options)
 873    }
 874
 875    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
 876        self.foreground_platform.prompt_for_new_path(directory)
 877    }
 878
 879    pub fn reveal_path(&self, path: &Path) {
 880        self.foreground_platform.reveal_path(path)
 881    }
 882
 883    pub fn emit_global<E: Any>(&mut self, payload: E) {
 884        self.pending_effects.push_back(Effect::GlobalEvent {
 885            payload: Box::new(payload),
 886        });
 887    }
 888
 889    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 890    where
 891        E: Entity,
 892        E::Event: 'static,
 893        H: Handle<E>,
 894        F: 'static + FnMut(H, &E::Event, &mut Self),
 895    {
 896        self.subscribe_internal(handle, move |handle, event, cx| {
 897            callback(handle, event, cx);
 898            true
 899        })
 900    }
 901
 902    pub fn subscribe_global<E, F>(&mut self, mut callback: F) -> Subscription
 903    where
 904        E: Any,
 905        F: 'static + FnMut(&E, &mut Self),
 906    {
 907        let subscription_id = post_inc(&mut self.next_subscription_id);
 908        let type_id = TypeId::of::<E>();
 909        self.pending_effects.push_back(Effect::GlobalSubscription {
 910            type_id,
 911            subscription_id,
 912            callback: Box::new(move |payload, cx| {
 913                let payload = payload.downcast_ref().expect("downcast is type safe");
 914                callback(payload, cx)
 915            }),
 916        });
 917        Subscription::GlobalSubscription(
 918            self.global_subscriptions
 919                .subscribe(type_id, subscription_id),
 920        )
 921    }
 922
 923    pub fn observe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 924    where
 925        E: Entity,
 926        E::Event: 'static,
 927        H: Handle<E>,
 928        F: 'static + FnMut(H, &mut Self),
 929    {
 930        self.observe_internal(handle, move |handle, cx| {
 931            callback(handle, cx);
 932            true
 933        })
 934    }
 935
 936    pub fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 937    where
 938        E: Entity,
 939        E::Event: 'static,
 940        H: Handle<E>,
 941        F: 'static + FnMut(H, &E::Event, &mut Self) -> bool,
 942    {
 943        let subscription_id = post_inc(&mut self.next_subscription_id);
 944        let emitter = handle.downgrade();
 945        self.pending_effects.push_back(Effect::Subscription {
 946            entity_id: handle.id(),
 947            subscription_id,
 948            callback: Box::new(move |payload, cx| {
 949                if let Some(emitter) = H::upgrade_from(&emitter, cx) {
 950                    let payload = payload.downcast_ref().expect("downcast is type safe");
 951                    callback(emitter, payload, cx)
 952                } else {
 953                    false
 954                }
 955            }),
 956        });
 957        Subscription::Subscription(self.subscriptions.subscribe(handle.id(), subscription_id))
 958    }
 959
 960    fn observe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 961    where
 962        E: Entity,
 963        E::Event: 'static,
 964        H: Handle<E>,
 965        F: 'static + FnMut(H, &mut Self) -> bool,
 966    {
 967        let subscription_id = post_inc(&mut self.next_subscription_id);
 968        let observed = handle.downgrade();
 969        let entity_id = handle.id();
 970        self.pending_effects.push_back(Effect::Observation {
 971            entity_id,
 972            subscription_id,
 973            callback: Box::new(move |cx| {
 974                if let Some(observed) = H::upgrade_from(&observed, cx) {
 975                    callback(observed, cx)
 976                } else {
 977                    false
 978                }
 979            }),
 980        });
 981        Subscription::Observation(self.observations.subscribe(entity_id, subscription_id))
 982    }
 983
 984    fn observe_focus<F, V>(&mut self, handle: &ViewHandle<V>, mut callback: F) -> Subscription
 985    where
 986        F: 'static + FnMut(ViewHandle<V>, bool, &mut WindowContext) -> bool,
 987        V: View,
 988    {
 989        let subscription_id = post_inc(&mut self.next_subscription_id);
 990        let observed = handle.downgrade();
 991        let view_id = handle.id();
 992
 993        self.pending_effects.push_back(Effect::FocusObservation {
 994            view_id,
 995            subscription_id,
 996            callback: Box::new(move |focused, cx| {
 997                if let Some(observed) = observed.upgrade(cx) {
 998                    callback(observed, focused, cx)
 999                } else {
1000                    false
1001                }
1002            }),
1003        });
1004        Subscription::FocusObservation(self.focus_observations.subscribe(view_id, subscription_id))
1005    }
1006
1007    pub fn observe_global<G, F>(&mut self, mut observe: F) -> Subscription
1008    where
1009        G: Any,
1010        F: 'static + FnMut(&mut AppContext),
1011    {
1012        let type_id = TypeId::of::<G>();
1013        let id = post_inc(&mut self.next_subscription_id);
1014
1015        self.global_observations.add_callback(
1016            type_id,
1017            id,
1018            Box::new(move |cx: &mut AppContext| observe(cx)),
1019        );
1020        Subscription::GlobalObservation(self.global_observations.subscribe(type_id, id))
1021    }
1022
1023    pub fn observe_default_global<G, F>(&mut self, observe: F) -> Subscription
1024    where
1025        G: Any + Default,
1026        F: 'static + FnMut(&mut AppContext),
1027    {
1028        if !self.has_global::<G>() {
1029            self.set_global(G::default());
1030        }
1031        self.observe_global::<G, F>(observe)
1032    }
1033
1034    pub fn observe_release<E, H, F>(&mut self, handle: &H, callback: F) -> Subscription
1035    where
1036        E: Entity,
1037        E::Event: 'static,
1038        H: Handle<E>,
1039        F: 'static + FnOnce(&E, &mut Self),
1040    {
1041        let id = post_inc(&mut self.next_subscription_id);
1042        let mut callback = Some(callback);
1043        self.release_observations.add_callback(
1044            handle.id(),
1045            id,
1046            Box::new(move |released, cx| {
1047                let released = released.downcast_ref().unwrap();
1048                if let Some(callback) = callback.take() {
1049                    callback(released, cx)
1050                }
1051            }),
1052        );
1053        Subscription::ReleaseObservation(self.release_observations.subscribe(handle.id(), id))
1054    }
1055
1056    pub fn observe_actions<F>(&mut self, callback: F) -> Subscription
1057    where
1058        F: 'static + FnMut(TypeId, &mut AppContext),
1059    {
1060        let subscription_id = post_inc(&mut self.next_subscription_id);
1061        self.action_dispatch_observations
1062            .add_callback((), subscription_id, Box::new(callback));
1063        Subscription::ActionObservation(
1064            self.action_dispatch_observations
1065                .subscribe((), subscription_id),
1066        )
1067    }
1068
1069    fn observe_window_activation<F>(&mut self, window_id: usize, callback: F) -> Subscription
1070    where
1071        F: 'static + FnMut(bool, &mut WindowContext) -> bool,
1072    {
1073        let subscription_id = post_inc(&mut self.next_subscription_id);
1074        self.pending_effects
1075            .push_back(Effect::WindowActivationObservation {
1076                window_id,
1077                subscription_id,
1078                callback: Box::new(callback),
1079            });
1080        Subscription::WindowActivationObservation(
1081            self.window_activation_observations
1082                .subscribe(window_id, subscription_id),
1083        )
1084    }
1085
1086    fn observe_fullscreen<F>(&mut self, window_id: usize, callback: F) -> Subscription
1087    where
1088        F: 'static + FnMut(bool, &mut AppContext) -> bool,
1089    {
1090        let subscription_id = post_inc(&mut self.next_subscription_id);
1091        self.pending_effects
1092            .push_back(Effect::WindowFullscreenObservation {
1093                window_id,
1094                subscription_id,
1095                callback: Box::new(callback),
1096            });
1097        Subscription::WindowActivationObservation(
1098            self.window_activation_observations
1099                .subscribe(window_id, subscription_id),
1100        )
1101    }
1102
1103    fn observe_window_bounds<F>(&mut self, window_id: usize, callback: F) -> Subscription
1104    where
1105        F: 'static + FnMut(WindowBounds, Uuid, &mut AppContext) -> bool,
1106    {
1107        let subscription_id = post_inc(&mut self.next_subscription_id);
1108        self.pending_effects
1109            .push_back(Effect::WindowBoundsObservation {
1110                window_id,
1111                subscription_id,
1112                callback: Box::new(callback),
1113            });
1114        Subscription::WindowBoundsObservation(
1115            self.window_bounds_observations
1116                .subscribe(window_id, subscription_id),
1117        )
1118    }
1119
1120    pub fn observe_keystrokes<F>(&mut self, window_id: usize, callback: F) -> Subscription
1121    where
1122        F: 'static
1123            + FnMut(&Keystroke, &MatchResult, Option<&Box<dyn Action>>, &mut AppContext) -> bool,
1124    {
1125        let subscription_id = post_inc(&mut self.next_subscription_id);
1126        self.keystroke_observations
1127            .add_callback(window_id, subscription_id, Box::new(callback));
1128        Subscription::KeystrokeObservation(
1129            self.keystroke_observations
1130                .subscribe(window_id, subscription_id),
1131        )
1132    }
1133
1134    pub fn observe_active_labeled_tasks<F>(&mut self, callback: F) -> Subscription
1135    where
1136        F: 'static + FnMut(&mut AppContext) -> bool,
1137    {
1138        let subscription_id = post_inc(&mut self.next_subscription_id);
1139        self.active_labeled_task_observations
1140            .add_callback((), subscription_id, Box::new(callback));
1141        Subscription::ActiveLabeledTasksObservation(
1142            self.active_labeled_task_observations
1143                .subscribe((), subscription_id),
1144        )
1145    }
1146
1147    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut AppContext)) {
1148        self.pending_effects.push_back(Effect::Deferred {
1149            callback: Box::new(callback),
1150            after_window_update: false,
1151        })
1152    }
1153
1154    pub fn after_window_update(&mut self, callback: impl 'static + FnOnce(&mut AppContext)) {
1155        self.pending_effects.push_back(Effect::Deferred {
1156            callback: Box::new(callback),
1157            after_window_update: true,
1158        })
1159    }
1160
1161    pub(crate) fn notify_model(&mut self, model_id: usize) {
1162        if self.pending_notifications.insert(model_id) {
1163            self.pending_effects
1164                .push_back(Effect::ModelNotification { model_id });
1165        }
1166    }
1167
1168    pub(crate) fn notify_view(&mut self, window_id: usize, view_id: usize) {
1169        if self.pending_notifications.insert(view_id) {
1170            self.pending_effects
1171                .push_back(Effect::ViewNotification { window_id, view_id });
1172        }
1173    }
1174
1175    pub(crate) fn notify_global(&mut self, type_id: TypeId) {
1176        if self.pending_global_notifications.insert(type_id) {
1177            self.pending_effects
1178                .push_back(Effect::GlobalNotification { type_id });
1179        }
1180    }
1181
1182    pub(crate) fn name_for_view(&self, window_id: usize, view_id: usize) -> Option<&str> {
1183        self.views
1184            .get(&(window_id, view_id))
1185            .map(|view| view.ui_name())
1186    }
1187
1188    pub fn all_action_names<'a>(&'a self) -> impl Iterator<Item = &'static str> + 'a {
1189        self.action_deserializers.keys().copied()
1190    }
1191
1192    pub fn is_action_available(&self, action: &dyn Action) -> bool {
1193        let mut available_in_window = false;
1194        let action_type = action.as_any().type_id();
1195        if let Some(window_id) = self.platform.main_window_id() {
1196            available_in_window = self
1197                .read_window(window_id, |cx| {
1198                    if let Some(focused_view_id) = cx.focused_view_id() {
1199                        for view_id in cx.ancestors(focused_view_id) {
1200                            if let Some(view) = cx.views.get(&(window_id, view_id)) {
1201                                let view_type = view.as_any().type_id();
1202                                if let Some(actions) = cx.actions.get(&view_type) {
1203                                    if actions.contains_key(&action_type) {
1204                                        return true;
1205                                    }
1206                                }
1207                            }
1208                        }
1209                    }
1210                    false
1211                })
1212                .unwrap_or(false);
1213        }
1214        available_in_window || self.global_actions.contains_key(&action_type)
1215    }
1216
1217    fn actions_mut(
1218        &mut self,
1219        capture_phase: bool,
1220    ) -> &mut HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>> {
1221        if capture_phase {
1222            &mut self.capture_actions
1223        } else {
1224            &mut self.actions
1225        }
1226    }
1227
1228    pub fn dispatch_global_action<A: Action>(&mut self, action: A) {
1229        self.dispatch_global_action_any(&action);
1230    }
1231
1232    fn dispatch_global_action_any(&mut self, action: &dyn Action) -> bool {
1233        self.update(|this| {
1234            if let Some((name, mut handler)) = this.global_actions.remove_entry(&action.id()) {
1235                handler(action, this);
1236                this.global_actions.insert(name, handler);
1237                true
1238            } else {
1239                false
1240            }
1241        })
1242    }
1243
1244    pub fn add_bindings<T: IntoIterator<Item = Binding>>(&mut self, bindings: T) {
1245        self.keystroke_matcher.add_bindings(bindings);
1246    }
1247
1248    pub fn clear_bindings(&mut self) {
1249        self.keystroke_matcher.clear_bindings();
1250    }
1251
1252    pub fn default_global<T: 'static + Default>(&mut self) -> &T {
1253        let type_id = TypeId::of::<T>();
1254        self.update(|this| {
1255            if let Entry::Vacant(entry) = this.globals.entry(type_id) {
1256                entry.insert(Box::new(T::default()));
1257                this.notify_global(type_id);
1258            }
1259        });
1260        self.globals.get(&type_id).unwrap().downcast_ref().unwrap()
1261    }
1262
1263    pub fn set_global<T: 'static>(&mut self, state: T) {
1264        self.update(|this| {
1265            let type_id = TypeId::of::<T>();
1266            this.globals.insert(type_id, Box::new(state));
1267            this.notify_global(type_id);
1268        });
1269    }
1270
1271    pub fn update_default_global<T, F, U>(&mut self, update: F) -> U
1272    where
1273        T: 'static + Default,
1274        F: FnOnce(&mut T, &mut AppContext) -> U,
1275    {
1276        self.update(|this| {
1277            let type_id = TypeId::of::<T>();
1278            let mut state = this
1279                .globals
1280                .remove(&type_id)
1281                .unwrap_or_else(|| Box::new(T::default()));
1282            let result = update(state.downcast_mut().unwrap(), this);
1283            this.globals.insert(type_id, state);
1284            this.notify_global(type_id);
1285            result
1286        })
1287    }
1288
1289    pub fn update_global<T, F, U>(&mut self, update: F) -> U
1290    where
1291        T: 'static,
1292        F: FnOnce(&mut T, &mut AppContext) -> U,
1293    {
1294        self.update(|this| {
1295            let type_id = TypeId::of::<T>();
1296            if let Some(mut state) = this.globals.remove(&type_id) {
1297                let result = update(state.downcast_mut().unwrap(), this);
1298                this.globals.insert(type_id, state);
1299                this.notify_global(type_id);
1300                result
1301            } else {
1302                panic!("No global added for {}", std::any::type_name::<T>());
1303            }
1304        })
1305    }
1306
1307    pub fn clear_globals(&mut self) {
1308        self.globals.clear();
1309    }
1310
1311    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
1312    where
1313        T: Entity,
1314        F: FnOnce(&mut ModelContext<T>) -> T,
1315    {
1316        self.update(|this| {
1317            let model_id = post_inc(&mut this.next_entity_id);
1318            let handle = ModelHandle::new(model_id, &this.ref_counts);
1319            let mut cx = ModelContext::new(this, model_id);
1320            let model = build_model(&mut cx);
1321            this.models.insert(model_id, Box::new(model));
1322            handle
1323        })
1324    }
1325
1326    pub fn add_window<V, F>(
1327        &mut self,
1328        window_options: WindowOptions,
1329        build_root_view: F,
1330    ) -> (usize, ViewHandle<V>)
1331    where
1332        V: View,
1333        F: FnOnce(&mut ViewContext<V>) -> V,
1334    {
1335        self.update(|this| {
1336            let window_id = post_inc(&mut this.next_window_id);
1337            let platform_window =
1338                this.platform
1339                    .open_window(window_id, window_options, this.foreground.clone());
1340            let window = this.build_window(window_id, platform_window, build_root_view);
1341            let root_view = window.root_view().clone().downcast::<V>().unwrap();
1342
1343            this.windows.insert(window_id, window);
1344            root_view.update(this, |view, cx| view.focus_in(cx.handle().into_any(), cx));
1345
1346            (window_id, root_view)
1347        })
1348    }
1349
1350    pub fn add_status_bar_item<V, F>(&mut self, build_root_view: F) -> (usize, ViewHandle<V>)
1351    where
1352        V: View,
1353        F: FnOnce(&mut ViewContext<V>) -> V,
1354    {
1355        self.update(|this| {
1356            let window_id = post_inc(&mut this.next_window_id);
1357            let platform_window = this.platform.add_status_item();
1358            let window = this.build_window(window_id, platform_window, build_root_view);
1359            let root_view = window.root_view().clone().downcast::<V>().unwrap();
1360
1361            this.windows.insert(window_id, window);
1362            root_view.update(this, |view, cx| view.focus_in(cx.handle().into_any(), cx));
1363
1364            (window_id, root_view)
1365        })
1366    }
1367
1368    pub fn remove_status_bar_item(&mut self, id: usize) {
1369        self.remove_window(id);
1370    }
1371
1372    pub fn remove_window(&mut self, window_id: usize) {
1373        self.windows.remove(&window_id);
1374        self.flush_effects();
1375    }
1376
1377    pub fn build_window<V, F>(
1378        &mut self,
1379        window_id: usize,
1380        mut platform_window: Box<dyn platform::Window>,
1381        build_root_view: F,
1382    ) -> Window
1383    where
1384        V: View,
1385        F: FnOnce(&mut ViewContext<V>) -> V,
1386    {
1387        {
1388            let mut app = self.upgrade();
1389
1390            platform_window.on_event(Box::new(move |event| {
1391                app.update_window(window_id, |cx| {
1392                    if let Event::KeyDown(KeyDownEvent { keystroke, .. }) = &event {
1393                        if cx.dispatch_keystroke(keystroke) {
1394                            return true;
1395                        }
1396                    }
1397
1398                    cx.dispatch_event(event, false)
1399                })
1400                .unwrap_or(false)
1401            }));
1402        }
1403
1404        {
1405            let mut app = self.upgrade();
1406            platform_window.on_active_status_change(Box::new(move |is_active| {
1407                app.update(|cx| cx.window_changed_active_status(window_id, is_active))
1408            }));
1409        }
1410
1411        {
1412            let mut app = self.upgrade();
1413            platform_window.on_resize(Box::new(move || {
1414                app.update(|cx| cx.window_was_resized(window_id))
1415            }));
1416        }
1417
1418        {
1419            let mut app = self.upgrade();
1420            platform_window.on_moved(Box::new(move || {
1421                app.update(|cx| cx.window_was_moved(window_id))
1422            }));
1423        }
1424
1425        {
1426            let mut app = self.upgrade();
1427            platform_window.on_fullscreen(Box::new(move |is_fullscreen| {
1428                app.update(|cx| cx.window_was_fullscreen_changed(window_id, is_fullscreen))
1429            }));
1430        }
1431
1432        {
1433            let mut app = self.upgrade();
1434            platform_window.on_close(Box::new(move || {
1435                app.update(|cx| cx.remove_window(window_id));
1436            }));
1437        }
1438
1439        {
1440            let mut app = self.upgrade();
1441            platform_window
1442                .on_appearance_changed(Box::new(move || app.update(|cx| cx.refresh_windows())));
1443        }
1444
1445        platform_window.set_input_handler(Box::new(WindowInputHandler {
1446            app: self.upgrade().0,
1447            window_id,
1448        }));
1449
1450        let mut window = Window::new(window_id, platform_window, self, build_root_view);
1451        let scene = WindowContext::mutable(self, &mut window, window_id).build_scene();
1452        window.platform_window.present_scene(scene);
1453        window
1454    }
1455
1456    pub fn replace_root_view<V, F>(
1457        &mut self,
1458        window_id: usize,
1459        build_root_view: F,
1460    ) -> Option<ViewHandle<V>>
1461    where
1462        V: View,
1463        F: FnOnce(&mut ViewContext<V>) -> V,
1464    {
1465        self.update_window(window_id, |cx| cx.replace_root_view(build_root_view))
1466    }
1467
1468    pub fn add_view<S, F>(&mut self, parent: &AnyViewHandle, build_view: F) -> ViewHandle<S>
1469    where
1470        S: View,
1471        F: FnOnce(&mut ViewContext<S>) -> S,
1472    {
1473        self.update_window(parent.window_id, |cx| {
1474            cx.build_and_insert_view(ParentId::View(parent.view_id), |cx| Some(build_view(cx)))
1475                .unwrap()
1476        })
1477        .unwrap()
1478    }
1479
1480    fn remove_dropped_entities(&mut self) {
1481        loop {
1482            let (dropped_models, dropped_views, dropped_element_states) =
1483                self.ref_counts.lock().take_dropped();
1484            if dropped_models.is_empty()
1485                && dropped_views.is_empty()
1486                && dropped_element_states.is_empty()
1487            {
1488                break;
1489            }
1490
1491            for model_id in dropped_models {
1492                self.subscriptions.remove(model_id);
1493                self.observations.remove(model_id);
1494                let mut model = self.models.remove(&model_id).unwrap();
1495                model.release(self);
1496                self.pending_effects
1497                    .push_back(Effect::ModelRelease { model_id, model });
1498            }
1499
1500            for (window_id, view_id) in dropped_views {
1501                self.subscriptions.remove(view_id);
1502                self.observations.remove(view_id);
1503                let mut view = self.views.remove(&(window_id, view_id)).unwrap();
1504                view.release(self);
1505                let change_focus_to = self.windows.get_mut(&window_id).and_then(|window| {
1506                    window
1507                        .invalidation
1508                        .get_or_insert_with(Default::default)
1509                        .removed
1510                        .push(view_id);
1511                    if window.focused_view_id == Some(view_id) {
1512                        Some(window.root_view().id())
1513                    } else {
1514                        None
1515                    }
1516                });
1517                self.parents.remove(&(window_id, view_id));
1518
1519                if let Some(view_id) = change_focus_to {
1520                    self.handle_focus_effect(window_id, Some(view_id));
1521                }
1522
1523                self.pending_effects
1524                    .push_back(Effect::ViewRelease { view_id, view });
1525            }
1526
1527            for key in dropped_element_states {
1528                self.element_states.remove(&key);
1529            }
1530        }
1531    }
1532
1533    fn flush_effects(&mut self) {
1534        self.pending_flushes = self.pending_flushes.saturating_sub(1);
1535        let mut after_window_update_callbacks = Vec::new();
1536
1537        if !self.flushing_effects && self.pending_flushes == 0 {
1538            self.flushing_effects = true;
1539
1540            let mut refreshing = false;
1541            loop {
1542                if let Some(effect) = self.pending_effects.pop_front() {
1543                    match effect {
1544                        Effect::Subscription {
1545                            entity_id,
1546                            subscription_id,
1547                            callback,
1548                        } => self
1549                            .subscriptions
1550                            .add_callback(entity_id, subscription_id, callback),
1551
1552                        Effect::Event { entity_id, payload } => {
1553                            let mut subscriptions = self.subscriptions.clone();
1554                            subscriptions
1555                                .emit(entity_id, |callback| callback(payload.as_ref(), self))
1556                        }
1557
1558                        Effect::GlobalSubscription {
1559                            type_id,
1560                            subscription_id,
1561                            callback,
1562                        } => self.global_subscriptions.add_callback(
1563                            type_id,
1564                            subscription_id,
1565                            callback,
1566                        ),
1567
1568                        Effect::GlobalEvent { payload } => self.emit_global_event(payload),
1569
1570                        Effect::Observation {
1571                            entity_id,
1572                            subscription_id,
1573                            callback,
1574                        } => self
1575                            .observations
1576                            .add_callback(entity_id, subscription_id, callback),
1577
1578                        Effect::ModelNotification { model_id } => {
1579                            let mut observations = self.observations.clone();
1580                            observations.emit(model_id, |callback| callback(self));
1581                        }
1582
1583                        Effect::ViewNotification { window_id, view_id } => {
1584                            self.handle_view_notification_effect(window_id, view_id)
1585                        }
1586
1587                        Effect::GlobalNotification { type_id } => {
1588                            let mut subscriptions = self.global_observations.clone();
1589                            subscriptions.emit(type_id, |callback| {
1590                                callback(self);
1591                                true
1592                            });
1593                        }
1594
1595                        Effect::Deferred {
1596                            callback,
1597                            after_window_update,
1598                        } => {
1599                            if after_window_update {
1600                                after_window_update_callbacks.push(callback);
1601                            } else {
1602                                callback(self)
1603                            }
1604                        }
1605
1606                        Effect::ModelRelease { model_id, model } => {
1607                            self.handle_entity_release_effect(model_id, model.as_any())
1608                        }
1609
1610                        Effect::ViewRelease { view_id, view } => {
1611                            self.handle_entity_release_effect(view_id, view.as_any())
1612                        }
1613
1614                        Effect::Focus { window_id, view_id } => {
1615                            self.handle_focus_effect(window_id, view_id);
1616                        }
1617
1618                        Effect::FocusObservation {
1619                            view_id,
1620                            subscription_id,
1621                            callback,
1622                        } => {
1623                            self.focus_observations.add_callback(
1624                                view_id,
1625                                subscription_id,
1626                                callback,
1627                            );
1628                        }
1629
1630                        Effect::ResizeWindow { window_id } => {
1631                            if let Some(window) = self.windows.get_mut(&window_id) {
1632                                window
1633                                    .invalidation
1634                                    .get_or_insert(WindowInvalidation::default());
1635                            }
1636                            self.handle_window_moved(window_id);
1637                        }
1638
1639                        Effect::MoveWindow { window_id } => {
1640                            self.handle_window_moved(window_id);
1641                        }
1642
1643                        Effect::WindowActivationObservation {
1644                            window_id,
1645                            subscription_id,
1646                            callback,
1647                        } => self.window_activation_observations.add_callback(
1648                            window_id,
1649                            subscription_id,
1650                            callback,
1651                        ),
1652
1653                        Effect::ActivateWindow {
1654                            window_id,
1655                            is_active,
1656                        } => self.handle_window_activation_effect(window_id, is_active),
1657
1658                        Effect::WindowFullscreenObservation {
1659                            window_id,
1660                            subscription_id,
1661                            callback,
1662                        } => self.window_fullscreen_observations.add_callback(
1663                            window_id,
1664                            subscription_id,
1665                            callback,
1666                        ),
1667
1668                        Effect::FullscreenWindow {
1669                            window_id,
1670                            is_fullscreen,
1671                        } => self.handle_fullscreen_effect(window_id, is_fullscreen),
1672
1673                        Effect::WindowBoundsObservation {
1674                            window_id,
1675                            subscription_id,
1676                            callback,
1677                        } => self.window_bounds_observations.add_callback(
1678                            window_id,
1679                            subscription_id,
1680                            callback,
1681                        ),
1682
1683                        Effect::RefreshWindows => {
1684                            refreshing = true;
1685                        }
1686                        Effect::DispatchActionFrom {
1687                            window_id,
1688                            view_id,
1689                            action,
1690                        } => {
1691                            self.handle_dispatch_action_from_effect(
1692                                window_id,
1693                                Some(view_id),
1694                                action.as_ref(),
1695                            );
1696                        }
1697                        Effect::ActionDispatchNotification { action_id } => {
1698                            self.handle_action_dispatch_notification_effect(action_id)
1699                        }
1700                        Effect::WindowShouldCloseSubscription {
1701                            window_id,
1702                            callback,
1703                        } => {
1704                            self.handle_window_should_close_subscription_effect(window_id, callback)
1705                        }
1706                        Effect::Keystroke {
1707                            window_id,
1708                            keystroke,
1709                            handled_by,
1710                            result,
1711                        } => self.handle_keystroke_effect(window_id, keystroke, handled_by, result),
1712                        Effect::ActiveLabeledTasksChanged => {
1713                            self.handle_active_labeled_tasks_changed_effect()
1714                        }
1715                        Effect::ActiveLabeledTasksObservation {
1716                            subscription_id,
1717                            callback,
1718                        } => self.active_labeled_task_observations.add_callback(
1719                            (),
1720                            subscription_id,
1721                            callback,
1722                        ),
1723                    }
1724                    self.pending_notifications.clear();
1725                    self.remove_dropped_entities();
1726                } else {
1727                    self.remove_dropped_entities();
1728
1729                    if refreshing {
1730                        self.perform_window_refresh();
1731                    } else {
1732                        self.update_windows();
1733                    }
1734
1735                    if self.pending_effects.is_empty() {
1736                        for callback in after_window_update_callbacks.drain(..) {
1737                            callback(self);
1738                        }
1739
1740                        if self.pending_effects.is_empty() {
1741                            self.flushing_effects = false;
1742                            self.pending_notifications.clear();
1743                            self.pending_global_notifications.clear();
1744                            break;
1745                        }
1746                    }
1747
1748                    refreshing = false;
1749                }
1750            }
1751        }
1752    }
1753
1754    fn update_windows(&mut self) {
1755        let window_ids = self.windows.keys().cloned().collect::<Vec<_>>();
1756        for window_id in window_ids {
1757            self.update_window(window_id, |cx| {
1758                if let Some(mut invalidation) = cx.window.invalidation.take() {
1759                    let appearance = cx.window.platform_window.appearance();
1760                    cx.invalidate(&mut invalidation, appearance);
1761                    let scene = cx.build_scene();
1762                    cx.window.platform_window.present_scene(scene);
1763                }
1764            });
1765        }
1766    }
1767
1768    fn window_was_resized(&mut self, window_id: usize) {
1769        self.pending_effects
1770            .push_back(Effect::ResizeWindow { window_id });
1771    }
1772
1773    fn window_was_moved(&mut self, window_id: usize) {
1774        self.pending_effects
1775            .push_back(Effect::MoveWindow { window_id });
1776    }
1777
1778    fn window_was_fullscreen_changed(&mut self, window_id: usize, is_fullscreen: bool) {
1779        self.pending_effects.push_back(Effect::FullscreenWindow {
1780            window_id,
1781            is_fullscreen,
1782        });
1783    }
1784
1785    fn window_changed_active_status(&mut self, window_id: usize, is_active: bool) {
1786        self.pending_effects.push_back(Effect::ActivateWindow {
1787            window_id,
1788            is_active,
1789        });
1790    }
1791
1792    fn keystroke(
1793        &mut self,
1794        window_id: usize,
1795        keystroke: Keystroke,
1796        handled_by: Option<Box<dyn Action>>,
1797        result: MatchResult,
1798    ) {
1799        self.pending_effects.push_back(Effect::Keystroke {
1800            window_id,
1801            keystroke,
1802            handled_by,
1803            result,
1804        });
1805    }
1806
1807    pub fn refresh_windows(&mut self) {
1808        self.pending_effects.push_back(Effect::RefreshWindows);
1809    }
1810
1811    pub fn dispatch_action_at(&mut self, window_id: usize, view_id: usize, action: impl Action) {
1812        self.dispatch_any_action_at(window_id, view_id, Box::new(action));
1813    }
1814
1815    pub fn dispatch_any_action_at(
1816        &mut self,
1817        window_id: usize,
1818        view_id: usize,
1819        action: Box<dyn Action>,
1820    ) {
1821        self.pending_effects.push_back(Effect::DispatchActionFrom {
1822            window_id,
1823            view_id,
1824            action,
1825        });
1826    }
1827
1828    fn perform_window_refresh(&mut self) {
1829        let window_ids = self.windows.keys().cloned().collect::<Vec<_>>();
1830        for window_id in window_ids {
1831            self.update_window(window_id, |cx| {
1832                let mut invalidation = cx.window.invalidation.take().unwrap_or_default();
1833                invalidation
1834                    .updated
1835                    .extend(cx.window.rendered_views.keys().copied());
1836                cx.invalidate(&mut invalidation, cx.window.platform_window.appearance());
1837                cx.refreshing = true;
1838                let scene = cx.build_scene();
1839                cx.window.platform_window.present_scene(scene);
1840            });
1841        }
1842    }
1843
1844    fn emit_global_event(&mut self, payload: Box<dyn Any>) {
1845        let type_id = (&*payload).type_id();
1846
1847        let mut subscriptions = self.global_subscriptions.clone();
1848        subscriptions.emit(type_id, |callback| {
1849            callback(payload.as_ref(), self);
1850            true //Always alive
1851        });
1852    }
1853
1854    fn handle_view_notification_effect(
1855        &mut self,
1856        observed_window_id: usize,
1857        observed_view_id: usize,
1858    ) {
1859        if self
1860            .views
1861            .contains_key(&(observed_window_id, observed_view_id))
1862        {
1863            if let Some(window) = self.windows.get_mut(&observed_window_id) {
1864                window
1865                    .invalidation
1866                    .get_or_insert_with(Default::default)
1867                    .updated
1868                    .insert(observed_view_id);
1869            }
1870
1871            let mut observations = self.observations.clone();
1872            observations.emit(observed_view_id, |callback| callback(self));
1873        }
1874    }
1875
1876    fn handle_entity_release_effect(&mut self, entity_id: usize, entity: &dyn Any) {
1877        self.release_observations
1878            .clone()
1879            .emit(entity_id, |callback| {
1880                callback(entity, self);
1881                // Release observations happen one time. So clear the callback by returning false
1882                false
1883            })
1884    }
1885
1886    fn handle_fullscreen_effect(&mut self, window_id: usize, is_fullscreen: bool) {
1887        self.update_window(window_id, |cx| {
1888            cx.window.is_fullscreen = is_fullscreen;
1889
1890            let mut fullscreen_observations = cx.window_fullscreen_observations.clone();
1891            fullscreen_observations.emit(window_id, |callback| callback(is_fullscreen, cx));
1892
1893            if let Some(uuid) = cx.window_display_uuid() {
1894                let bounds = cx.window_bounds();
1895                let mut bounds_observations = cx.window_bounds_observations.clone();
1896                bounds_observations.emit(window_id, |callback| callback(bounds, uuid, cx));
1897            }
1898
1899            Some(())
1900        });
1901    }
1902
1903    fn handle_keystroke_effect(
1904        &mut self,
1905        window_id: usize,
1906        keystroke: Keystroke,
1907        handled_by: Option<Box<dyn Action>>,
1908        result: MatchResult,
1909    ) {
1910        self.update(|this| {
1911            let mut observations = this.keystroke_observations.clone();
1912            observations.emit(window_id, move |callback| {
1913                callback(&keystroke, &result, handled_by.as_ref(), this)
1914            });
1915        });
1916    }
1917
1918    fn handle_window_activation_effect(&mut self, window_id: usize, active: bool) {
1919        self.update_window(window_id, |cx| {
1920            if cx.window.is_active == active {
1921                return;
1922            }
1923            cx.window.is_active = active;
1924
1925            if let Some(focused_id) = cx.window.focused_view_id {
1926                for view_id in cx.ancestors(focused_id).collect::<Vec<_>>() {
1927                    cx.update_any_view(focused_id, |view, cx| {
1928                        if active {
1929                            view.focus_in(focused_id, cx, view_id);
1930                        } else {
1931                            view.focus_out(focused_id, cx, view_id);
1932                        }
1933                    });
1934                }
1935            }
1936
1937            let mut observations = cx.window_activation_observations.clone();
1938            observations.emit(window_id, |callback| callback(active, cx));
1939        });
1940    }
1941
1942    fn handle_focus_effect(&mut self, window_id: usize, mut focused_id: Option<usize>) {
1943        let mut blurred_id = None;
1944        self.update_window(window_id, |cx| {
1945            if cx.window.focused_view_id == focused_id {
1946                focused_id = None;
1947                return;
1948            }
1949            blurred_id = cx.window.focused_view_id;
1950            cx.window.focused_view_id = focused_id;
1951
1952            let blurred_parents = blurred_id
1953                .map(|blurred_id| cx.ancestors(blurred_id).collect::<Vec<_>>())
1954                .unwrap_or_default();
1955            let focused_parents = focused_id
1956                .map(|focused_id| cx.ancestors(focused_id).collect::<Vec<_>>())
1957                .unwrap_or_default();
1958
1959            if let Some(blurred_id) = blurred_id {
1960                for view_id in blurred_parents.iter().copied() {
1961                    if let Some(mut view) = cx.views.remove(&(window_id, view_id)) {
1962                        view.focus_out(blurred_id, cx, view_id);
1963                        cx.views.insert((window_id, view_id), view);
1964                    }
1965                }
1966
1967                let mut subscriptions = cx.focus_observations.clone();
1968                subscriptions.emit(blurred_id, |callback| callback(false, cx));
1969            }
1970
1971            if let Some(focused_id) = focused_id {
1972                for view_id in focused_parents {
1973                    if let Some(mut view) = cx.views.remove(&(window_id, view_id)) {
1974                        view.focus_in(focused_id, cx, view_id);
1975                        cx.views.insert((window_id, view_id), view);
1976                    }
1977                }
1978
1979                let mut subscriptions = cx.focus_observations.clone();
1980                subscriptions.emit(focused_id, |callback| callback(true, cx));
1981            }
1982        });
1983    }
1984
1985    fn handle_dispatch_action_from_effect(
1986        &mut self,
1987        window_id: usize,
1988        view_id: Option<usize>,
1989        action: &dyn Action,
1990    ) {
1991        self.update_window(window_id, |cx| {
1992            cx.handle_dispatch_action_from_effect(view_id, action)
1993        });
1994    }
1995
1996    fn handle_action_dispatch_notification_effect(&mut self, action_id: TypeId) {
1997        self.action_dispatch_observations
1998            .clone()
1999            .emit((), |callback| {
2000                callback(action_id, self);
2001                true
2002            });
2003    }
2004
2005    fn handle_window_should_close_subscription_effect(
2006        &mut self,
2007        window_id: usize,
2008        mut callback: WindowShouldCloseSubscriptionCallback,
2009    ) {
2010        let mut app = self.upgrade();
2011        if let Some(window) = self.windows.get_mut(&window_id) {
2012            window
2013                .platform_window
2014                .on_should_close(Box::new(move || app.update(|cx| callback(cx))))
2015        }
2016    }
2017
2018    fn handle_window_moved(&mut self, window_id: usize) {
2019        self.update_window(window_id, |cx| {
2020            if let Some(display) = cx.window_display_uuid() {
2021                let bounds = cx.window_bounds();
2022                cx.window_bounds_observations
2023                    .clone()
2024                    .emit(window_id, move |callback| {
2025                        callback(bounds, display, cx);
2026                        true
2027                    });
2028            }
2029        });
2030    }
2031
2032    fn handle_active_labeled_tasks_changed_effect(&mut self) {
2033        self.active_labeled_task_observations
2034            .clone()
2035            .emit((), move |callback| {
2036                callback(self);
2037                true
2038            });
2039    }
2040
2041    pub fn focus(&mut self, window_id: usize, view_id: Option<usize>) {
2042        self.pending_effects
2043            .push_back(Effect::Focus { window_id, view_id });
2044    }
2045
2046    fn spawn_internal<F, Fut, T>(&mut self, task_name: Option<&'static str>, f: F) -> Task<T>
2047    where
2048        F: FnOnce(AsyncAppContext) -> Fut,
2049        Fut: 'static + Future<Output = T>,
2050        T: 'static,
2051    {
2052        let label_id = task_name.map(|task_name| {
2053            let id = post_inc(&mut self.next_labeled_task_id);
2054            self.active_labeled_tasks.insert(id, task_name);
2055            self.pending_effects
2056                .push_back(Effect::ActiveLabeledTasksChanged);
2057            id
2058        });
2059
2060        let future = f(self.to_async());
2061        let cx = self.to_async();
2062        self.foreground.spawn(async move {
2063            let result = future.await;
2064            let mut cx = cx.0.borrow_mut();
2065
2066            if let Some(completed_label_id) = label_id {
2067                cx.active_labeled_tasks.remove(&completed_label_id);
2068                cx.pending_effects
2069                    .push_back(Effect::ActiveLabeledTasksChanged);
2070            }
2071            cx.flush_effects();
2072            result
2073        })
2074    }
2075
2076    pub fn spawn_labeled<F, Fut, T>(&mut self, task_name: &'static str, f: F) -> Task<T>
2077    where
2078        F: FnOnce(AsyncAppContext) -> Fut,
2079        Fut: 'static + Future<Output = T>,
2080        T: 'static,
2081    {
2082        self.spawn_internal(Some(task_name), f)
2083    }
2084
2085    pub fn spawn<F, Fut, T>(&mut self, f: F) -> Task<T>
2086    where
2087        F: FnOnce(AsyncAppContext) -> Fut,
2088        Fut: 'static + Future<Output = T>,
2089        T: 'static,
2090    {
2091        self.spawn_internal(None, f)
2092    }
2093
2094    pub fn to_async(&self) -> AsyncAppContext {
2095        AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
2096    }
2097
2098    pub fn write_to_clipboard(&self, item: ClipboardItem) {
2099        self.platform.write_to_clipboard(item);
2100    }
2101
2102    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
2103        self.platform.read_from_clipboard()
2104    }
2105
2106    #[cfg(any(test, feature = "test-support"))]
2107    pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
2108        self.ref_counts.lock().leak_detector.clone()
2109    }
2110}
2111
2112impl ReadModel for AppContext {
2113    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2114        if let Some(model) = self.models.get(&handle.model_id) {
2115            model
2116                .as_any()
2117                .downcast_ref()
2118                .expect("downcast is type safe")
2119        } else {
2120            panic!("circular model reference");
2121        }
2122    }
2123}
2124
2125impl UpdateModel for AppContext {
2126    fn update_model<T: Entity, V>(
2127        &mut self,
2128        handle: &ModelHandle<T>,
2129        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
2130    ) -> V {
2131        if let Some(mut model) = self.models.remove(&handle.model_id) {
2132            self.update(|this| {
2133                let mut cx = ModelContext::new(this, handle.model_id);
2134                let result = update(
2135                    model
2136                        .as_any_mut()
2137                        .downcast_mut()
2138                        .expect("downcast is type safe"),
2139                    &mut cx,
2140                );
2141                this.models.insert(handle.model_id, model);
2142                result
2143            })
2144        } else {
2145            panic!("circular model update");
2146        }
2147    }
2148}
2149
2150impl UpgradeModelHandle for AppContext {
2151    fn upgrade_model_handle<T: Entity>(
2152        &self,
2153        handle: &WeakModelHandle<T>,
2154    ) -> Option<ModelHandle<T>> {
2155        if self.models.contains_key(&handle.model_id) {
2156            Some(ModelHandle::new(handle.model_id, &self.ref_counts))
2157        } else {
2158            None
2159        }
2160    }
2161
2162    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2163        self.models.contains_key(&handle.model_id)
2164    }
2165
2166    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2167        if self.models.contains_key(&handle.model_id) {
2168            Some(AnyModelHandle::new(
2169                handle.model_id,
2170                handle.model_type,
2171                self.ref_counts.clone(),
2172            ))
2173        } else {
2174            None
2175        }
2176    }
2177}
2178
2179impl UpgradeViewHandle for AppContext {
2180    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2181        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2182            Some(ViewHandle::new(
2183                handle.window_id,
2184                handle.view_id,
2185                &self.ref_counts,
2186            ))
2187        } else {
2188            None
2189        }
2190    }
2191
2192    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
2193        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2194            Some(AnyViewHandle::new(
2195                handle.window_id,
2196                handle.view_id,
2197                handle.view_type,
2198                self.ref_counts.clone(),
2199            ))
2200        } else {
2201            None
2202        }
2203    }
2204}
2205
2206impl ReadView for AppContext {
2207    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2208        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
2209            view.as_any().downcast_ref().expect("downcast is type safe")
2210        } else {
2211            panic!("circular view reference for type {}", type_name::<T>());
2212        }
2213    }
2214}
2215
2216impl UpdateView for AppContext {
2217    fn update_view<T, S>(
2218        &mut self,
2219        handle: &ViewHandle<T>,
2220        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
2221    ) -> S
2222    where
2223        T: View,
2224    {
2225        self.update_window(handle.window_id, |cx| cx.update_view(handle, update))
2226            .unwrap() // TODO: Is this unwrap safe?
2227    }
2228}
2229
2230#[derive(Debug)]
2231pub enum ParentId {
2232    View(usize),
2233    Root,
2234}
2235
2236#[derive(Default, Clone)]
2237pub struct WindowInvalidation {
2238    pub updated: HashSet<usize>,
2239    pub removed: Vec<usize>,
2240}
2241
2242pub enum Effect {
2243    Subscription {
2244        entity_id: usize,
2245        subscription_id: usize,
2246        callback: SubscriptionCallback,
2247    },
2248    Event {
2249        entity_id: usize,
2250        payload: Box<dyn Any>,
2251    },
2252    GlobalSubscription {
2253        type_id: TypeId,
2254        subscription_id: usize,
2255        callback: GlobalSubscriptionCallback,
2256    },
2257    GlobalEvent {
2258        payload: Box<dyn Any>,
2259    },
2260    Observation {
2261        entity_id: usize,
2262        subscription_id: usize,
2263        callback: ObservationCallback,
2264    },
2265    ModelNotification {
2266        model_id: usize,
2267    },
2268    ViewNotification {
2269        window_id: usize,
2270        view_id: usize,
2271    },
2272    Deferred {
2273        callback: Box<dyn FnOnce(&mut AppContext)>,
2274        after_window_update: bool,
2275    },
2276    GlobalNotification {
2277        type_id: TypeId,
2278    },
2279    ModelRelease {
2280        model_id: usize,
2281        model: Box<dyn AnyModel>,
2282    },
2283    ViewRelease {
2284        view_id: usize,
2285        view: Box<dyn AnyView>,
2286    },
2287    Focus {
2288        window_id: usize,
2289        view_id: Option<usize>,
2290    },
2291    FocusObservation {
2292        view_id: usize,
2293        subscription_id: usize,
2294        callback: FocusObservationCallback,
2295    },
2296    ResizeWindow {
2297        window_id: usize,
2298    },
2299    MoveWindow {
2300        window_id: usize,
2301    },
2302    ActivateWindow {
2303        window_id: usize,
2304        is_active: bool,
2305    },
2306    WindowActivationObservation {
2307        window_id: usize,
2308        subscription_id: usize,
2309        callback: WindowActivationCallback,
2310    },
2311    FullscreenWindow {
2312        window_id: usize,
2313        is_fullscreen: bool,
2314    },
2315    WindowFullscreenObservation {
2316        window_id: usize,
2317        subscription_id: usize,
2318        callback: WindowFullscreenCallback,
2319    },
2320    WindowBoundsObservation {
2321        window_id: usize,
2322        subscription_id: usize,
2323        callback: WindowBoundsCallback,
2324    },
2325    Keystroke {
2326        window_id: usize,
2327        keystroke: Keystroke,
2328        handled_by: Option<Box<dyn Action>>,
2329        result: MatchResult,
2330    },
2331    RefreshWindows,
2332    DispatchActionFrom {
2333        window_id: usize,
2334        view_id: usize,
2335        action: Box<dyn Action>,
2336    },
2337    ActionDispatchNotification {
2338        action_id: TypeId,
2339    },
2340    WindowShouldCloseSubscription {
2341        window_id: usize,
2342        callback: WindowShouldCloseSubscriptionCallback,
2343    },
2344    ActiveLabeledTasksChanged,
2345    ActiveLabeledTasksObservation {
2346        subscription_id: usize,
2347        callback: ActiveLabeledTasksCallback,
2348    },
2349}
2350
2351impl Debug for Effect {
2352    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2353        match self {
2354            Effect::Subscription {
2355                entity_id,
2356                subscription_id,
2357                ..
2358            } => f
2359                .debug_struct("Effect::Subscribe")
2360                .field("entity_id", entity_id)
2361                .field("subscription_id", subscription_id)
2362                .finish(),
2363            Effect::Event { entity_id, .. } => f
2364                .debug_struct("Effect::Event")
2365                .field("entity_id", entity_id)
2366                .finish(),
2367            Effect::GlobalSubscription {
2368                type_id,
2369                subscription_id,
2370                ..
2371            } => f
2372                .debug_struct("Effect::Subscribe")
2373                .field("type_id", type_id)
2374                .field("subscription_id", subscription_id)
2375                .finish(),
2376            Effect::GlobalEvent { payload, .. } => f
2377                .debug_struct("Effect::GlobalEvent")
2378                .field("type_id", &(&*payload).type_id())
2379                .finish(),
2380            Effect::Observation {
2381                entity_id,
2382                subscription_id,
2383                ..
2384            } => f
2385                .debug_struct("Effect::Observation")
2386                .field("entity_id", entity_id)
2387                .field("subscription_id", subscription_id)
2388                .finish(),
2389            Effect::ModelNotification { model_id } => f
2390                .debug_struct("Effect::ModelNotification")
2391                .field("model_id", model_id)
2392                .finish(),
2393            Effect::ViewNotification { window_id, view_id } => f
2394                .debug_struct("Effect::ViewNotification")
2395                .field("window_id", window_id)
2396                .field("view_id", view_id)
2397                .finish(),
2398            Effect::GlobalNotification { type_id } => f
2399                .debug_struct("Effect::GlobalNotification")
2400                .field("type_id", type_id)
2401                .finish(),
2402            Effect::Deferred { .. } => f.debug_struct("Effect::Deferred").finish(),
2403            Effect::ModelRelease { model_id, .. } => f
2404                .debug_struct("Effect::ModelRelease")
2405                .field("model_id", model_id)
2406                .finish(),
2407            Effect::ViewRelease { view_id, .. } => f
2408                .debug_struct("Effect::ViewRelease")
2409                .field("view_id", view_id)
2410                .finish(),
2411            Effect::Focus { window_id, view_id } => f
2412                .debug_struct("Effect::Focus")
2413                .field("window_id", window_id)
2414                .field("view_id", view_id)
2415                .finish(),
2416            Effect::FocusObservation {
2417                view_id,
2418                subscription_id,
2419                ..
2420            } => f
2421                .debug_struct("Effect::FocusObservation")
2422                .field("view_id", view_id)
2423                .field("subscription_id", subscription_id)
2424                .finish(),
2425            Effect::DispatchActionFrom {
2426                window_id, view_id, ..
2427            } => f
2428                .debug_struct("Effect::DispatchActionFrom")
2429                .field("window_id", window_id)
2430                .field("view_id", view_id)
2431                .finish(),
2432            Effect::ActionDispatchNotification { action_id, .. } => f
2433                .debug_struct("Effect::ActionDispatchNotification")
2434                .field("action_id", action_id)
2435                .finish(),
2436            Effect::ResizeWindow { window_id } => f
2437                .debug_struct("Effect::RefreshWindow")
2438                .field("window_id", window_id)
2439                .finish(),
2440            Effect::MoveWindow { window_id } => f
2441                .debug_struct("Effect::MoveWindow")
2442                .field("window_id", window_id)
2443                .finish(),
2444            Effect::WindowActivationObservation {
2445                window_id,
2446                subscription_id,
2447                ..
2448            } => f
2449                .debug_struct("Effect::WindowActivationObservation")
2450                .field("window_id", window_id)
2451                .field("subscription_id", subscription_id)
2452                .finish(),
2453            Effect::ActivateWindow {
2454                window_id,
2455                is_active,
2456            } => f
2457                .debug_struct("Effect::ActivateWindow")
2458                .field("window_id", window_id)
2459                .field("is_active", is_active)
2460                .finish(),
2461            Effect::FullscreenWindow {
2462                window_id,
2463                is_fullscreen,
2464            } => f
2465                .debug_struct("Effect::FullscreenWindow")
2466                .field("window_id", window_id)
2467                .field("is_fullscreen", is_fullscreen)
2468                .finish(),
2469            Effect::WindowFullscreenObservation {
2470                window_id,
2471                subscription_id,
2472                callback: _,
2473            } => f
2474                .debug_struct("Effect::WindowFullscreenObservation")
2475                .field("window_id", window_id)
2476                .field("subscription_id", subscription_id)
2477                .finish(),
2478
2479            Effect::WindowBoundsObservation {
2480                window_id,
2481                subscription_id,
2482                callback: _,
2483            } => f
2484                .debug_struct("Effect::WindowBoundsObservation")
2485                .field("window_id", window_id)
2486                .field("subscription_id", subscription_id)
2487                .finish(),
2488            Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
2489            Effect::WindowShouldCloseSubscription { window_id, .. } => f
2490                .debug_struct("Effect::WindowShouldCloseSubscription")
2491                .field("window_id", window_id)
2492                .finish(),
2493            Effect::Keystroke {
2494                window_id,
2495                keystroke,
2496                handled_by,
2497                result,
2498            } => f
2499                .debug_struct("Effect::Keystroke")
2500                .field("window_id", window_id)
2501                .field("keystroke", keystroke)
2502                .field(
2503                    "keystroke",
2504                    &handled_by.as_ref().map(|handled_by| handled_by.name()),
2505                )
2506                .field("result", result)
2507                .finish(),
2508            Effect::ActiveLabeledTasksChanged => {
2509                f.debug_struct("Effect::ActiveLabeledTasksChanged").finish()
2510            }
2511            Effect::ActiveLabeledTasksObservation {
2512                subscription_id,
2513                callback: _,
2514            } => f
2515                .debug_struct("Effect::ActiveLabeledTasksObservation")
2516                .field("subscription_id", subscription_id)
2517                .finish(),
2518        }
2519    }
2520}
2521
2522pub trait AnyModel {
2523    fn as_any(&self) -> &dyn Any;
2524    fn as_any_mut(&mut self) -> &mut dyn Any;
2525    fn release(&mut self, cx: &mut AppContext);
2526    fn app_will_quit(
2527        &mut self,
2528        cx: &mut AppContext,
2529    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2530}
2531
2532impl<T> AnyModel for T
2533where
2534    T: Entity,
2535{
2536    fn as_any(&self) -> &dyn Any {
2537        self
2538    }
2539
2540    fn as_any_mut(&mut self) -> &mut dyn Any {
2541        self
2542    }
2543
2544    fn release(&mut self, cx: &mut AppContext) {
2545        self.release(cx);
2546    }
2547
2548    fn app_will_quit(
2549        &mut self,
2550        cx: &mut AppContext,
2551    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2552        self.app_will_quit(cx)
2553    }
2554}
2555
2556pub trait AnyView {
2557    fn as_any(&self) -> &dyn Any;
2558    fn as_any_mut(&mut self) -> &mut dyn Any;
2559    fn release(&mut self, cx: &mut AppContext);
2560    fn app_will_quit(
2561        &mut self,
2562        cx: &mut AppContext,
2563    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2564    fn ui_name(&self) -> &'static str;
2565    fn render(&mut self, cx: &mut WindowContext, view_id: usize) -> Box<dyn AnyRootElement>;
2566    fn focus_in<'a, 'b>(
2567        &mut self,
2568        focused_id: usize,
2569        cx: &mut WindowContext<'a, 'b>,
2570        view_id: usize,
2571    );
2572    fn focus_out(&mut self, focused_id: usize, cx: &mut WindowContext, view_id: usize);
2573    fn key_down(&mut self, event: &KeyDownEvent, cx: &mut WindowContext, view_id: usize) -> bool;
2574    fn key_up(&mut self, event: &KeyUpEvent, cx: &mut WindowContext, view_id: usize) -> bool;
2575    fn modifiers_changed(
2576        &mut self,
2577        event: &ModifiersChangedEvent,
2578        cx: &mut WindowContext,
2579        view_id: usize,
2580    ) -> bool;
2581    fn keymap_context(&self, cx: &AppContext) -> KeymapContext;
2582    fn debug_json(&self, cx: &WindowContext) -> serde_json::Value;
2583
2584    fn text_for_range(&self, range: Range<usize>, cx: &WindowContext) -> Option<String>;
2585    fn selected_text_range(&self, cx: &WindowContext) -> Option<Range<usize>>;
2586    fn marked_text_range(&self, cx: &WindowContext) -> Option<Range<usize>>;
2587    fn unmark_text(&mut self, cx: &mut WindowContext, view_id: usize);
2588    fn replace_text_in_range(
2589        &mut self,
2590        range: Option<Range<usize>>,
2591        text: &str,
2592        cx: &mut WindowContext,
2593        view_id: usize,
2594    );
2595    fn replace_and_mark_text_in_range(
2596        &mut self,
2597        range: Option<Range<usize>>,
2598        new_text: &str,
2599        new_selected_range: Option<Range<usize>>,
2600        cx: &mut WindowContext,
2601        view_id: usize,
2602    );
2603    fn any_handle(&self, window_id: usize, view_id: usize, cx: &AppContext) -> AnyViewHandle {
2604        AnyViewHandle::new(
2605            window_id,
2606            view_id,
2607            self.as_any().type_id(),
2608            cx.ref_counts.clone(),
2609        )
2610    }
2611}
2612
2613impl<V> AnyView for V
2614where
2615    V: View,
2616{
2617    fn as_any(&self) -> &dyn Any {
2618        self
2619    }
2620
2621    fn as_any_mut(&mut self) -> &mut dyn Any {
2622        self
2623    }
2624
2625    fn release(&mut self, cx: &mut AppContext) {
2626        self.release(cx);
2627    }
2628
2629    fn app_will_quit(
2630        &mut self,
2631        cx: &mut AppContext,
2632    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2633        self.app_will_quit(cx)
2634    }
2635
2636    fn ui_name(&self) -> &'static str {
2637        V::ui_name()
2638    }
2639
2640    fn render(&mut self, cx: &mut WindowContext, view_id: usize) -> Box<dyn AnyRootElement> {
2641        let mut view_context = ViewContext::mutable(cx, view_id);
2642        let element = V::render(self, &mut view_context);
2643        let view = WeakViewHandle::new(cx.window_id, view_id);
2644        Box::new(RootElement::new(element, view))
2645    }
2646
2647    fn focus_in(&mut self, focused_id: usize, cx: &mut WindowContext, view_id: usize) {
2648        let mut cx = ViewContext::mutable(cx, view_id);
2649        let focused_view_handle: AnyViewHandle = if view_id == focused_id {
2650            cx.handle().into_any()
2651        } else {
2652            let focused_type = cx
2653                .views
2654                .get(&(cx.window_id, focused_id))
2655                .unwrap()
2656                .as_any()
2657                .type_id();
2658            AnyViewHandle::new(
2659                cx.window_id,
2660                focused_id,
2661                focused_type,
2662                cx.ref_counts.clone(),
2663            )
2664        };
2665        View::focus_in(self, focused_view_handle, &mut cx);
2666    }
2667
2668    fn focus_out(&mut self, blurred_id: usize, cx: &mut WindowContext, view_id: usize) {
2669        let mut cx = ViewContext::mutable(cx, view_id);
2670        let blurred_view_handle: AnyViewHandle = if view_id == blurred_id {
2671            cx.handle().into_any()
2672        } else {
2673            let blurred_type = cx
2674                .views
2675                .get(&(cx.window_id, blurred_id))
2676                .unwrap()
2677                .as_any()
2678                .type_id();
2679            AnyViewHandle::new(
2680                cx.window_id,
2681                blurred_id,
2682                blurred_type,
2683                cx.ref_counts.clone(),
2684            )
2685        };
2686        View::focus_out(self, blurred_view_handle, &mut cx);
2687    }
2688
2689    fn key_down(&mut self, event: &KeyDownEvent, cx: &mut WindowContext, view_id: usize) -> bool {
2690        let mut cx = ViewContext::mutable(cx, view_id);
2691        View::key_down(self, event, &mut cx)
2692    }
2693
2694    fn key_up(&mut self, event: &KeyUpEvent, cx: &mut WindowContext, view_id: usize) -> bool {
2695        let mut cx = ViewContext::mutable(cx, view_id);
2696        View::key_up(self, event, &mut cx)
2697    }
2698
2699    fn modifiers_changed(
2700        &mut self,
2701        event: &ModifiersChangedEvent,
2702        cx: &mut WindowContext,
2703        view_id: usize,
2704    ) -> bool {
2705        let mut cx = ViewContext::mutable(cx, view_id);
2706        View::modifiers_changed(self, event, &mut cx)
2707    }
2708
2709    fn keymap_context(&self, cx: &AppContext) -> KeymapContext {
2710        View::keymap_context(self, cx)
2711    }
2712
2713    fn debug_json(&self, cx: &WindowContext) -> serde_json::Value {
2714        View::debug_json(self, cx)
2715    }
2716
2717    fn text_for_range(&self, range: Range<usize>, cx: &WindowContext) -> Option<String> {
2718        View::text_for_range(self, range, cx)
2719    }
2720
2721    fn selected_text_range(&self, cx: &WindowContext) -> Option<Range<usize>> {
2722        View::selected_text_range(self, cx)
2723    }
2724
2725    fn marked_text_range(&self, cx: &WindowContext) -> Option<Range<usize>> {
2726        View::marked_text_range(self, cx)
2727    }
2728
2729    fn unmark_text(&mut self, cx: &mut WindowContext, view_id: usize) {
2730        let mut cx = ViewContext::mutable(cx, view_id);
2731        View::unmark_text(self, &mut cx)
2732    }
2733
2734    fn replace_text_in_range(
2735        &mut self,
2736        range: Option<Range<usize>>,
2737        text: &str,
2738        cx: &mut WindowContext,
2739        view_id: usize,
2740    ) {
2741        let mut cx = ViewContext::mutable(cx, view_id);
2742        View::replace_text_in_range(self, range, text, &mut cx)
2743    }
2744
2745    fn replace_and_mark_text_in_range(
2746        &mut self,
2747        range: Option<Range<usize>>,
2748        new_text: &str,
2749        new_selected_range: Option<Range<usize>>,
2750        cx: &mut WindowContext,
2751        view_id: usize,
2752    ) {
2753        let mut cx = ViewContext::mutable(cx, view_id);
2754        View::replace_and_mark_text_in_range(self, range, new_text, new_selected_range, &mut cx)
2755    }
2756}
2757
2758pub struct ModelContext<'a, T: ?Sized> {
2759    app: &'a mut AppContext,
2760    model_id: usize,
2761    model_type: PhantomData<T>,
2762    halt_stream: bool,
2763}
2764
2765impl<'a, T: Entity> ModelContext<'a, T> {
2766    fn new(app: &'a mut AppContext, model_id: usize) -> Self {
2767        Self {
2768            app,
2769            model_id,
2770            model_type: PhantomData,
2771            halt_stream: false,
2772        }
2773    }
2774
2775    pub fn background(&self) -> &Arc<executor::Background> {
2776        &self.app.background
2777    }
2778
2779    pub fn halt_stream(&mut self) {
2780        self.halt_stream = true;
2781    }
2782
2783    pub fn model_id(&self) -> usize {
2784        self.model_id
2785    }
2786
2787    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2788    where
2789        S: Entity,
2790        F: FnOnce(&mut ModelContext<S>) -> S,
2791    {
2792        self.app.add_model(build_model)
2793    }
2794
2795    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ModelContext<T>)) {
2796        let handle = self.handle();
2797        self.app.defer(move |cx| {
2798            handle.update(cx, |model, cx| {
2799                callback(model, cx);
2800            })
2801        })
2802    }
2803
2804    pub fn emit(&mut self, payload: T::Event) {
2805        self.app.pending_effects.push_back(Effect::Event {
2806            entity_id: self.model_id,
2807            payload: Box::new(payload),
2808        });
2809    }
2810
2811    pub fn notify(&mut self) {
2812        self.app.notify_model(self.model_id);
2813    }
2814
2815    pub fn subscribe<S: Entity, F>(
2816        &mut self,
2817        handle: &ModelHandle<S>,
2818        mut callback: F,
2819    ) -> Subscription
2820    where
2821        S::Event: 'static,
2822        F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
2823    {
2824        let subscriber = self.weak_handle();
2825        self.app
2826            .subscribe_internal(handle, move |emitter, event, cx| {
2827                if let Some(subscriber) = subscriber.upgrade(cx) {
2828                    subscriber.update(cx, |subscriber, cx| {
2829                        callback(subscriber, emitter, event, cx);
2830                    });
2831                    true
2832                } else {
2833                    false
2834                }
2835            })
2836    }
2837
2838    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
2839    where
2840        S: Entity,
2841        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
2842    {
2843        let observer = self.weak_handle();
2844        self.app.observe_internal(handle, move |observed, cx| {
2845            if let Some(observer) = observer.upgrade(cx) {
2846                observer.update(cx, |observer, cx| {
2847                    callback(observer, observed, cx);
2848                });
2849                true
2850            } else {
2851                false
2852            }
2853        })
2854    }
2855
2856    pub fn observe_global<G, F>(&mut self, mut callback: F) -> Subscription
2857    where
2858        G: Any,
2859        F: 'static + FnMut(&mut T, &mut ModelContext<T>),
2860    {
2861        let observer = self.weak_handle();
2862        self.app.observe_global::<G, _>(move |cx| {
2863            if let Some(observer) = observer.upgrade(cx) {
2864                observer.update(cx, |observer, cx| callback(observer, cx));
2865            }
2866        })
2867    }
2868
2869    pub fn observe_release<S, F>(
2870        &mut self,
2871        handle: &ModelHandle<S>,
2872        mut callback: F,
2873    ) -> Subscription
2874    where
2875        S: Entity,
2876        F: 'static + FnMut(&mut T, &S, &mut ModelContext<T>),
2877    {
2878        let observer = self.weak_handle();
2879        self.app.observe_release(handle, move |released, cx| {
2880            if let Some(observer) = observer.upgrade(cx) {
2881                observer.update(cx, |observer, cx| {
2882                    callback(observer, released, cx);
2883                });
2884            }
2885        })
2886    }
2887
2888    pub fn handle(&self) -> ModelHandle<T> {
2889        ModelHandle::new(self.model_id, &self.app.ref_counts)
2890    }
2891
2892    pub fn weak_handle(&self) -> WeakModelHandle<T> {
2893        WeakModelHandle::new(self.model_id)
2894    }
2895
2896    pub fn spawn<F, Fut, S>(&mut self, f: F) -> Task<S>
2897    where
2898        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
2899        Fut: 'static + Future<Output = S>,
2900        S: 'static,
2901    {
2902        let handle = self.handle();
2903        self.app.spawn(|cx| f(handle, cx))
2904    }
2905
2906    pub fn spawn_weak<F, Fut, S>(&mut self, f: F) -> Task<S>
2907    where
2908        F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
2909        Fut: 'static + Future<Output = S>,
2910        S: 'static,
2911    {
2912        let handle = self.weak_handle();
2913        self.app.spawn(|cx| f(handle, cx))
2914    }
2915}
2916
2917impl<M> AsRef<AppContext> for ModelContext<'_, M> {
2918    fn as_ref(&self) -> &AppContext {
2919        &self.app
2920    }
2921}
2922
2923impl<M> AsMut<AppContext> for ModelContext<'_, M> {
2924    fn as_mut(&mut self) -> &mut AppContext {
2925        self.app
2926    }
2927}
2928
2929impl<M> ReadModel for ModelContext<'_, M> {
2930    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2931        self.app.read_model(handle)
2932    }
2933}
2934
2935impl<M> UpdateModel for ModelContext<'_, M> {
2936    fn update_model<T: Entity, V>(
2937        &mut self,
2938        handle: &ModelHandle<T>,
2939        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
2940    ) -> V {
2941        self.app.update_model(handle, update)
2942    }
2943}
2944
2945impl<M> UpgradeModelHandle for ModelContext<'_, M> {
2946    fn upgrade_model_handle<T: Entity>(
2947        &self,
2948        handle: &WeakModelHandle<T>,
2949    ) -> Option<ModelHandle<T>> {
2950        self.app.upgrade_model_handle(handle)
2951    }
2952
2953    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2954        self.app.model_handle_is_upgradable(handle)
2955    }
2956
2957    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2958        self.app.upgrade_any_model_handle(handle)
2959    }
2960}
2961
2962impl<M> Deref for ModelContext<'_, M> {
2963    type Target = AppContext;
2964
2965    fn deref(&self) -> &Self::Target {
2966        self.app
2967    }
2968}
2969
2970impl<M> DerefMut for ModelContext<'_, M> {
2971    fn deref_mut(&mut self) -> &mut Self::Target {
2972        &mut self.app
2973    }
2974}
2975
2976pub struct ViewContext<'a, 'b, 'c, T: ?Sized> {
2977    window_context: Reference<'c, WindowContext<'a, 'b>>,
2978    view_id: usize,
2979    view_type: PhantomData<T>,
2980}
2981
2982impl<'a, 'b, 'c, T: View> Deref for ViewContext<'a, 'b, 'c, T> {
2983    type Target = WindowContext<'a, 'b>;
2984
2985    fn deref(&self) -> &Self::Target {
2986        &self.window_context
2987    }
2988}
2989
2990impl<T: View> DerefMut for ViewContext<'_, '_, '_, T> {
2991    fn deref_mut(&mut self) -> &mut Self::Target {
2992        &mut self.window_context
2993    }
2994}
2995
2996impl<'a, 'b, 'c, V: View> ViewContext<'a, 'b, 'c, V> {
2997    pub(crate) fn mutable(window_context: &'c mut WindowContext<'a, 'b>, view_id: usize) -> Self {
2998        Self {
2999            window_context: Reference::Mutable(window_context),
3000            view_id,
3001            view_type: PhantomData,
3002        }
3003    }
3004
3005    pub(crate) fn immutable(window_context: &'c WindowContext<'a, 'b>, view_id: usize) -> Self {
3006        Self {
3007            window_context: Reference::Immutable(window_context),
3008            view_id,
3009            view_type: PhantomData,
3010        }
3011    }
3012
3013    pub fn handle(&self) -> ViewHandle<V> {
3014        ViewHandle::new(
3015            self.window_id,
3016            self.view_id,
3017            &self.window_context.ref_counts,
3018        )
3019    }
3020
3021    pub fn weak_handle(&self) -> WeakViewHandle<V> {
3022        WeakViewHandle::new(self.window_id, self.view_id)
3023    }
3024
3025    pub fn parent(&self) -> Option<usize> {
3026        self.window_context.parent(self.view_id)
3027    }
3028
3029    pub fn window_id(&self) -> usize {
3030        self.window_id
3031    }
3032
3033    pub fn view_id(&self) -> usize {
3034        self.view_id
3035    }
3036
3037    pub fn foreground(&self) -> &Rc<executor::Foreground> {
3038        self.window_context.foreground()
3039    }
3040
3041    pub fn background_executor(&self) -> &Arc<executor::Background> {
3042        &self.window_context.background
3043    }
3044
3045    pub fn platform(&self) -> &Arc<dyn Platform> {
3046        self.window_context.platform()
3047    }
3048
3049    pub fn prompt_for_paths(
3050        &self,
3051        options: PathPromptOptions,
3052    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
3053        self.window_context.prompt_for_paths(options)
3054    }
3055
3056    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
3057        self.window_context.prompt_for_new_path(directory)
3058    }
3059
3060    pub fn reveal_path(&self, path: &Path) {
3061        self.window_context.reveal_path(path)
3062    }
3063
3064    pub fn focus(&mut self, handle: &AnyViewHandle) {
3065        self.window_context
3066            .focus(handle.window_id, Some(handle.view_id));
3067    }
3068
3069    pub fn focus_self(&mut self) {
3070        let window_id = self.window_id;
3071        let view_id = self.view_id;
3072        self.window_context.focus(window_id, Some(view_id));
3073    }
3074
3075    pub fn is_self_focused(&self) -> bool {
3076        self.window.focused_view_id == Some(self.view_id)
3077    }
3078
3079    pub fn is_parent_view_focused(&self) -> bool {
3080        if let Some(parent_view_id) = self.ancestors(self.view_id).next().clone() {
3081            self.focused_view_id() == Some(parent_view_id)
3082        } else {
3083            false
3084        }
3085    }
3086
3087    pub fn focus_parent_view(&mut self) {
3088        let next = self.ancestors(self.view_id).next().clone();
3089        if let Some(parent_view_id) = next {
3090            let window_id = self.window_id;
3091            self.window_context.focus(window_id, Some(parent_view_id));
3092        }
3093    }
3094
3095    pub fn is_child(&self, view: impl Into<AnyViewHandle>) -> bool {
3096        let view = view.into();
3097        if self.window_id != view.window_id {
3098            return false;
3099        }
3100        self.ancestors(view.view_id)
3101            .skip(1) // Skip self id
3102            .any(|parent| parent == self.view_id)
3103    }
3104
3105    pub fn blur(&mut self) {
3106        let window_id = self.window_id;
3107        self.window_context.focus(window_id, None);
3108    }
3109
3110    pub fn on_window_should_close<F>(&mut self, mut callback: F)
3111    where
3112        F: 'static + FnMut(&mut V, &mut ViewContext<V>) -> bool,
3113    {
3114        let window_id = self.window_id();
3115        let view = self.weak_handle();
3116        self.pending_effects
3117            .push_back(Effect::WindowShouldCloseSubscription {
3118                window_id,
3119                callback: Box::new(move |cx| {
3120                    if let Some(view) = view.upgrade(cx) {
3121                        view.update(cx, |view, cx| callback(view, cx))
3122                    } else {
3123                        true
3124                    }
3125                }),
3126            });
3127    }
3128
3129    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
3130    where
3131        S: View,
3132        F: FnOnce(&mut ViewContext<S>) -> S,
3133    {
3134        self.window_context
3135            .build_and_insert_view(ParentId::View(self.view_id), |cx| Some(build_view(cx)))
3136            .unwrap()
3137    }
3138
3139    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
3140    where
3141        S: View,
3142        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
3143    {
3144        self.window_context
3145            .build_and_insert_view(ParentId::View(self.view_id), build_view)
3146    }
3147
3148    pub fn reparent(&mut self, view_handle: &AnyViewHandle) {
3149        if self.window_id != view_handle.window_id {
3150            panic!("Can't reparent view to a view from a different window");
3151        }
3152        self.parents
3153            .remove(&(view_handle.window_id, view_handle.view_id));
3154        let new_parent_id = self.view_id;
3155        self.parents.insert(
3156            (view_handle.window_id, view_handle.view_id),
3157            ParentId::View(new_parent_id),
3158        );
3159    }
3160
3161    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
3162    where
3163        E: Entity,
3164        E::Event: 'static,
3165        H: Handle<E>,
3166        F: 'static + FnMut(&mut V, H, &E::Event, &mut ViewContext<V>),
3167    {
3168        let subscriber = self.weak_handle();
3169        self.window_context
3170            .subscribe_internal(handle, move |emitter, event, cx| {
3171                if let Some(subscriber) = subscriber.upgrade(cx) {
3172                    subscriber.update(cx, |subscriber, cx| {
3173                        callback(subscriber, emitter, event, cx);
3174                    });
3175                    true
3176                } else {
3177                    false
3178                }
3179            })
3180    }
3181
3182    pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3183    where
3184        E: Entity,
3185        H: Handle<E>,
3186        F: 'static + FnMut(&mut V, H, &mut ViewContext<V>),
3187    {
3188        let observer = self.weak_handle();
3189        self.window_context
3190            .observe_internal(handle, move |observed, cx| {
3191                if let Some(observer) = observer.upgrade(cx) {
3192                    observer.update(cx, |observer, cx| {
3193                        callback(observer, observed, cx);
3194                    });
3195                    true
3196                } else {
3197                    false
3198                }
3199            })
3200    }
3201
3202    pub fn observe_global<G, F>(&mut self, mut callback: F) -> Subscription
3203    where
3204        G: Any,
3205        F: 'static + FnMut(&mut V, &mut ViewContext<V>),
3206    {
3207        let observer = self.weak_handle();
3208        self.window_context.observe_global::<G, _>(move |cx| {
3209            if let Some(observer) = observer.upgrade(cx) {
3210                observer.update(cx, |observer, cx| callback(observer, cx));
3211            }
3212        })
3213    }
3214
3215    pub fn observe_focus<F, W>(&mut self, handle: &ViewHandle<W>, mut callback: F) -> Subscription
3216    where
3217        F: 'static + FnMut(&mut V, ViewHandle<W>, bool, &mut ViewContext<V>),
3218        W: View,
3219    {
3220        let observer = self.weak_handle();
3221        self.window_context
3222            .observe_focus(handle, move |observed, focused, cx| {
3223                if let Some(observer) = observer.upgrade(cx) {
3224                    observer.update(cx, |observer, cx| {
3225                        callback(observer, observed, focused, cx);
3226                    });
3227                    true
3228                } else {
3229                    false
3230                }
3231            })
3232    }
3233
3234    pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3235    where
3236        E: Entity,
3237        H: Handle<E>,
3238        F: 'static + FnMut(&mut V, &E, &mut ViewContext<V>),
3239    {
3240        let observer = self.weak_handle();
3241        self.window_context
3242            .observe_release(handle, move |released, cx| {
3243                if let Some(observer) = observer.upgrade(cx) {
3244                    observer.update(cx, |observer, cx| {
3245                        callback(observer, released, cx);
3246                    });
3247                }
3248            })
3249    }
3250
3251    pub fn observe_actions<F>(&mut self, mut callback: F) -> Subscription
3252    where
3253        F: 'static + FnMut(&mut V, TypeId, &mut ViewContext<V>),
3254    {
3255        let observer = self.weak_handle();
3256        self.window_context.observe_actions(move |action_id, cx| {
3257            if let Some(observer) = observer.upgrade(cx) {
3258                observer.update(cx, |observer, cx| {
3259                    callback(observer, action_id, cx);
3260                });
3261            }
3262        })
3263    }
3264
3265    pub fn observe_window_activation<F>(&mut self, mut callback: F) -> Subscription
3266    where
3267        F: 'static + FnMut(&mut V, bool, &mut ViewContext<V>),
3268    {
3269        let observer = self.weak_handle();
3270        let window_id = self.window_id;
3271        self.window_context
3272            .observe_window_activation(window_id, move |active, cx| {
3273                if let Some(observer) = observer.upgrade(cx) {
3274                    observer.update(cx, |observer, cx| {
3275                        callback(observer, active, cx);
3276                    });
3277                    true
3278                } else {
3279                    false
3280                }
3281            })
3282    }
3283
3284    pub fn observe_fullscreen<F>(&mut self, mut callback: F) -> Subscription
3285    where
3286        F: 'static + FnMut(&mut V, bool, &mut ViewContext<V>),
3287    {
3288        let observer = self.weak_handle();
3289        let window_id = self.window_id;
3290        self.window_context
3291            .observe_fullscreen(window_id, move |active, cx| {
3292                if let Some(observer) = observer.upgrade(cx) {
3293                    observer.update(cx, |observer, cx| {
3294                        callback(observer, active, cx);
3295                    });
3296                    true
3297                } else {
3298                    false
3299                }
3300            })
3301    }
3302
3303    pub fn observe_keystrokes<F>(&mut self, mut callback: F) -> Subscription
3304    where
3305        F: 'static
3306            + FnMut(
3307                &mut V,
3308                &Keystroke,
3309                Option<&Box<dyn Action>>,
3310                &MatchResult,
3311                &mut ViewContext<V>,
3312            ) -> bool,
3313    {
3314        let observer = self.weak_handle();
3315        let window_id = self.window_id;
3316        self.window_context.observe_keystrokes(
3317            window_id,
3318            move |keystroke, result, handled_by, cx| {
3319                if let Some(observer) = observer.upgrade(cx) {
3320                    observer.update(cx, |observer, cx| {
3321                        callback(observer, keystroke, handled_by, result, cx);
3322                    });
3323                    true
3324                } else {
3325                    false
3326                }
3327            },
3328        )
3329    }
3330
3331    pub fn observe_window_bounds<F>(&mut self, mut callback: F) -> Subscription
3332    where
3333        F: 'static + FnMut(&mut V, WindowBounds, Uuid, &mut ViewContext<V>),
3334    {
3335        let observer = self.weak_handle();
3336        let window_id = self.window_id;
3337        self.window_context
3338            .observe_window_bounds(window_id, move |bounds, display, cx| {
3339                if let Some(observer) = observer.upgrade(cx) {
3340                    observer.update(cx, |observer, cx| {
3341                        callback(observer, bounds, display, cx);
3342                    });
3343                    true
3344                } else {
3345                    false
3346                }
3347            })
3348    }
3349
3350    pub fn observe_active_labeled_tasks<F>(&mut self, mut callback: F) -> Subscription
3351    where
3352        F: 'static + FnMut(&mut V, &mut ViewContext<V>),
3353    {
3354        let observer = self.weak_handle();
3355        self.window_context.observe_active_labeled_tasks(move |cx| {
3356            if let Some(observer) = observer.upgrade(cx) {
3357                observer.update(cx, |observer, cx| {
3358                    callback(observer, cx);
3359                });
3360                true
3361            } else {
3362                false
3363            }
3364        })
3365    }
3366
3367    pub fn emit(&mut self, payload: V::Event) {
3368        self.window_context
3369            .pending_effects
3370            .push_back(Effect::Event {
3371                entity_id: self.view_id,
3372                payload: Box::new(payload),
3373            });
3374    }
3375
3376    pub fn notify(&mut self) {
3377        let window_id = self.window_id;
3378        let view_id = self.view_id;
3379        self.window_context.notify_view(window_id, view_id);
3380    }
3381
3382    pub fn dispatch_action(&mut self, action: impl Action) {
3383        let window_id = self.window_id;
3384        let view_id = self.view_id;
3385        self.window_context
3386            .dispatch_action_at(window_id, view_id, action)
3387    }
3388
3389    pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
3390        let window_id = self.window_id;
3391        let view_id = self.view_id;
3392        self.window_context
3393            .dispatch_any_action_at(window_id, view_id, action)
3394    }
3395
3396    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut V, &mut ViewContext<V>)) {
3397        let handle = self.handle();
3398        self.window_context.defer(move |cx| {
3399            handle.update(cx, |view, cx| {
3400                callback(view, cx);
3401            })
3402        })
3403    }
3404
3405    pub fn after_window_update(
3406        &mut self,
3407        callback: impl 'static + FnOnce(&mut V, &mut ViewContext<V>),
3408    ) {
3409        let handle = self.handle();
3410        self.window_context.after_window_update(move |cx| {
3411            handle.update(cx, |view, cx| {
3412                callback(view, cx);
3413            })
3414        })
3415    }
3416
3417    pub fn propagate_action(&mut self) {
3418        self.window_context.halt_action_dispatch = false;
3419    }
3420
3421    pub fn spawn_labeled<F, Fut, S>(&mut self, task_label: &'static str, f: F) -> Task<S>
3422    where
3423        F: FnOnce(ViewHandle<V>, AsyncAppContext) -> Fut,
3424        Fut: 'static + Future<Output = S>,
3425        S: 'static,
3426    {
3427        let handle = self.handle();
3428        self.window_context
3429            .spawn_labeled(task_label, |cx| f(handle, cx))
3430    }
3431
3432    pub fn spawn<F, Fut, S>(&mut self, f: F) -> Task<S>
3433    where
3434        F: FnOnce(ViewHandle<V>, AsyncAppContext) -> Fut,
3435        Fut: 'static + Future<Output = S>,
3436        S: 'static,
3437    {
3438        let handle = self.handle();
3439        self.window_context.spawn(|cx| f(handle, cx))
3440    }
3441
3442    pub fn spawn_weak<F, Fut, S>(&mut self, f: F) -> Task<S>
3443    where
3444        F: FnOnce(WeakViewHandle<V>, AsyncAppContext) -> Fut,
3445        Fut: 'static + Future<Output = S>,
3446        S: 'static,
3447    {
3448        let handle = self.weak_handle();
3449        self.window_context.spawn(|cx| f(handle, cx))
3450    }
3451
3452    pub fn mouse_state<Tag: 'static>(&self, region_id: usize) -> MouseState {
3453        let region_id = MouseRegionId::new::<Tag>(self.view_id, region_id);
3454        MouseState {
3455            hovered: self.window.hovered_region_ids.contains(&region_id),
3456            clicked: self
3457                .window
3458                .clicked_region_ids
3459                .get(&region_id)
3460                .and_then(|_| self.window.clicked_button),
3461            accessed_hovered: false,
3462            accessed_clicked: false,
3463        }
3464    }
3465
3466    pub fn element_state<Tag: 'static, T: 'static>(
3467        &mut self,
3468        element_id: usize,
3469        initial: T,
3470    ) -> ElementStateHandle<T> {
3471        let id = ElementStateId {
3472            view_id: self.view_id(),
3473            element_id,
3474            tag: TypeId::of::<Tag>(),
3475        };
3476        self.element_states
3477            .entry(id)
3478            .or_insert_with(|| Box::new(initial));
3479        ElementStateHandle::new(id, self.frame_count, &self.ref_counts)
3480    }
3481
3482    pub fn default_element_state<Tag: 'static, T: 'static + Default>(
3483        &mut self,
3484        element_id: usize,
3485    ) -> ElementStateHandle<T> {
3486        self.element_state::<Tag, T>(element_id, T::default())
3487    }
3488}
3489
3490impl<V> UpgradeModelHandle for ViewContext<'_, '_, '_, V> {
3491    fn upgrade_model_handle<T: Entity>(
3492        &self,
3493        handle: &WeakModelHandle<T>,
3494    ) -> Option<ModelHandle<T>> {
3495        self.window_context.upgrade_model_handle(handle)
3496    }
3497
3498    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
3499        self.window_context.model_handle_is_upgradable(handle)
3500    }
3501
3502    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
3503        self.window_context.upgrade_any_model_handle(handle)
3504    }
3505}
3506
3507impl<V> UpgradeViewHandle for ViewContext<'_, '_, '_, V> {
3508    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
3509        self.window_context.upgrade_view_handle(handle)
3510    }
3511
3512    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
3513        self.window_context.upgrade_any_view_handle(handle)
3514    }
3515}
3516
3517impl<V: View> ReadModel for ViewContext<'_, '_, '_, V> {
3518    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
3519        self.window_context.read_model(handle)
3520    }
3521}
3522
3523impl<V: View> UpdateModel for ViewContext<'_, '_, '_, V> {
3524    fn update_model<T: Entity, O>(
3525        &mut self,
3526        handle: &ModelHandle<T>,
3527        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
3528    ) -> O {
3529        self.window_context.update_model(handle, update)
3530    }
3531}
3532
3533impl<V: View> ReadView for ViewContext<'_, '_, '_, V> {
3534    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
3535        self.window_context.read_view(handle)
3536    }
3537}
3538
3539impl<V: View> UpdateView for ViewContext<'_, '_, '_, V> {
3540    fn update_view<T, S>(
3541        &mut self,
3542        handle: &ViewHandle<T>,
3543        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
3544    ) -> S
3545    where
3546        T: View,
3547    {
3548        self.window_context.update_view(handle, update)
3549    }
3550}
3551
3552pub struct EventContext<'a, 'b, 'c, 'd, V: View> {
3553    view_context: &'d mut ViewContext<'a, 'b, 'c, V>,
3554    pub(crate) handled: bool,
3555}
3556
3557impl<'a, 'b, 'c, 'd, V: View> EventContext<'a, 'b, 'c, 'd, V> {
3558    pub(crate) fn new(view_context: &'d mut ViewContext<'a, 'b, 'c, V>) -> Self {
3559        EventContext {
3560            view_context,
3561            handled: true,
3562        }
3563    }
3564
3565    pub fn propagate_event(&mut self) {
3566        self.handled = false;
3567    }
3568}
3569
3570impl<'a, 'b, 'c, 'd, V: View> Deref for EventContext<'a, 'b, 'c, 'd, V> {
3571    type Target = ViewContext<'a, 'b, 'c, V>;
3572
3573    fn deref(&self) -> &Self::Target {
3574        &self.view_context
3575    }
3576}
3577
3578impl<V: View> DerefMut for EventContext<'_, '_, '_, '_, V> {
3579    fn deref_mut(&mut self) -> &mut Self::Target {
3580        &mut self.view_context
3581    }
3582}
3583
3584impl<V: View> UpdateModel for EventContext<'_, '_, '_, '_, V> {
3585    fn update_model<T: Entity, O>(
3586        &mut self,
3587        handle: &ModelHandle<T>,
3588        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
3589    ) -> O {
3590        self.view_context.update_model(handle, update)
3591    }
3592}
3593
3594impl<V: View> ReadView for EventContext<'_, '_, '_, '_, V> {
3595    fn read_view<W: View>(&self, handle: &crate::ViewHandle<W>) -> &W {
3596        self.view_context.read_view(handle)
3597    }
3598}
3599
3600impl<V: View> UpdateView for EventContext<'_, '_, '_, '_, V> {
3601    fn update_view<T, S>(
3602        &mut self,
3603        handle: &ViewHandle<T>,
3604        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
3605    ) -> S
3606    where
3607        T: View,
3608    {
3609        self.view_context.update_view(handle, update)
3610    }
3611}
3612
3613impl<V: View> UpgradeModelHandle for EventContext<'_, '_, '_, '_, V> {
3614    fn upgrade_model_handle<T: Entity>(
3615        &self,
3616        handle: &WeakModelHandle<T>,
3617    ) -> Option<ModelHandle<T>> {
3618        self.view_context.upgrade_model_handle(handle)
3619    }
3620
3621    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
3622        self.view_context.model_handle_is_upgradable(handle)
3623    }
3624
3625    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
3626        self.view_context.upgrade_any_model_handle(handle)
3627    }
3628}
3629
3630impl<V: View> UpgradeViewHandle for EventContext<'_, '_, '_, '_, V> {
3631    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
3632        self.view_context.upgrade_view_handle(handle)
3633    }
3634
3635    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
3636        self.view_context.upgrade_any_view_handle(handle)
3637    }
3638}
3639
3640pub(crate) enum Reference<'a, T> {
3641    Immutable(&'a T),
3642    Mutable(&'a mut T),
3643}
3644
3645impl<'a, T> Deref for Reference<'a, T> {
3646    type Target = T;
3647
3648    fn deref(&self) -> &Self::Target {
3649        match self {
3650            Reference::Immutable(target) => target,
3651            Reference::Mutable(target) => target,
3652        }
3653    }
3654}
3655
3656impl<'a, T> DerefMut for Reference<'a, T> {
3657    fn deref_mut(&mut self) -> &mut Self::Target {
3658        match self {
3659            Reference::Immutable(_) => {
3660                panic!("cannot mutably deref an immutable reference. this is a bug in GPUI.");
3661            }
3662            Reference::Mutable(target) => target,
3663        }
3664    }
3665}
3666
3667#[derive(Debug, Clone, Default)]
3668pub struct MouseState {
3669    pub(crate) hovered: bool,
3670    pub(crate) clicked: Option<MouseButton>,
3671    pub(crate) accessed_hovered: bool,
3672    pub(crate) accessed_clicked: bool,
3673}
3674
3675impl MouseState {
3676    pub fn hovered(&mut self) -> bool {
3677        self.accessed_hovered = true;
3678        self.hovered
3679    }
3680
3681    pub fn clicked(&mut self) -> Option<MouseButton> {
3682        self.accessed_clicked = true;
3683        self.clicked
3684    }
3685
3686    pub fn accessed_hovered(&self) -> bool {
3687        self.accessed_hovered
3688    }
3689
3690    pub fn accessed_clicked(&self) -> bool {
3691        self.accessed_clicked
3692    }
3693}
3694
3695pub trait Handle<T> {
3696    type Weak: 'static;
3697    fn id(&self) -> usize;
3698    fn location(&self) -> EntityLocation;
3699    fn downgrade(&self) -> Self::Weak;
3700    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3701    where
3702        Self: Sized;
3703}
3704
3705pub trait WeakHandle {
3706    fn id(&self) -> usize;
3707}
3708
3709#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
3710pub enum EntityLocation {
3711    Model(usize),
3712    View(usize, usize),
3713}
3714
3715pub struct ModelHandle<T: Entity> {
3716    any_handle: AnyModelHandle,
3717    model_type: PhantomData<T>,
3718}
3719
3720impl<T: Entity> Deref for ModelHandle<T> {
3721    type Target = AnyModelHandle;
3722
3723    fn deref(&self) -> &Self::Target {
3724        &self.any_handle
3725    }
3726}
3727
3728impl<T: Entity> ModelHandle<T> {
3729    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3730        Self {
3731            any_handle: AnyModelHandle::new(model_id, TypeId::of::<T>(), ref_counts.clone()),
3732            model_type: PhantomData,
3733        }
3734    }
3735
3736    pub fn downgrade(&self) -> WeakModelHandle<T> {
3737        WeakModelHandle::new(self.model_id)
3738    }
3739
3740    pub fn id(&self) -> usize {
3741        self.model_id
3742    }
3743
3744    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
3745        cx.read_model(self)
3746    }
3747
3748    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3749    where
3750        C: ReadModelWith,
3751        F: FnOnce(&T, &AppContext) -> S,
3752    {
3753        let mut read = Some(read);
3754        cx.read_model_with(self, &mut |model, cx| {
3755            let read = read.take().unwrap();
3756            read(model, cx)
3757        })
3758    }
3759
3760    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3761    where
3762        C: UpdateModel,
3763        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
3764    {
3765        let mut update = Some(update);
3766        cx.update_model(self, &mut |model, cx| {
3767            let update = update.take().unwrap();
3768            update(model, cx)
3769        })
3770    }
3771}
3772
3773impl<T: Entity> Clone for ModelHandle<T> {
3774    fn clone(&self) -> Self {
3775        Self::new(self.model_id, &self.ref_counts)
3776    }
3777}
3778
3779impl<T: Entity> PartialEq for ModelHandle<T> {
3780    fn eq(&self, other: &Self) -> bool {
3781        self.model_id == other.model_id
3782    }
3783}
3784
3785impl<T: Entity> Eq for ModelHandle<T> {}
3786
3787impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
3788    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
3789        self.model_id == other.model_id
3790    }
3791}
3792
3793impl<T: Entity> Hash for ModelHandle<T> {
3794    fn hash<H: Hasher>(&self, state: &mut H) {
3795        self.model_id.hash(state);
3796    }
3797}
3798
3799impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
3800    fn borrow(&self) -> &usize {
3801        &self.model_id
3802    }
3803}
3804
3805impl<T: Entity> Debug for ModelHandle<T> {
3806    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3807        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
3808            .field(&self.model_id)
3809            .finish()
3810    }
3811}
3812
3813unsafe impl<T: Entity> Send for ModelHandle<T> {}
3814unsafe impl<T: Entity> Sync for ModelHandle<T> {}
3815
3816impl<T: Entity> Handle<T> for ModelHandle<T> {
3817    type Weak = WeakModelHandle<T>;
3818
3819    fn id(&self) -> usize {
3820        self.model_id
3821    }
3822
3823    fn location(&self) -> EntityLocation {
3824        EntityLocation::Model(self.model_id)
3825    }
3826
3827    fn downgrade(&self) -> Self::Weak {
3828        self.downgrade()
3829    }
3830
3831    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3832    where
3833        Self: Sized,
3834    {
3835        weak.upgrade(cx)
3836    }
3837}
3838
3839pub struct WeakModelHandle<T> {
3840    any_handle: AnyWeakModelHandle,
3841    model_type: PhantomData<T>,
3842}
3843
3844impl<T> WeakModelHandle<T> {
3845    pub fn into_any(self) -> AnyWeakModelHandle {
3846        self.any_handle
3847    }
3848}
3849
3850impl<T> Deref for WeakModelHandle<T> {
3851    type Target = AnyWeakModelHandle;
3852
3853    fn deref(&self) -> &Self::Target {
3854        &self.any_handle
3855    }
3856}
3857
3858impl<T> WeakHandle for WeakModelHandle<T> {
3859    fn id(&self) -> usize {
3860        self.model_id
3861    }
3862}
3863
3864unsafe impl<T> Send for WeakModelHandle<T> {}
3865unsafe impl<T> Sync for WeakModelHandle<T> {}
3866
3867impl<T: Entity> WeakModelHandle<T> {
3868    fn new(model_id: usize) -> Self {
3869        Self {
3870            any_handle: AnyWeakModelHandle {
3871                model_id,
3872                model_type: TypeId::of::<T>(),
3873            },
3874            model_type: PhantomData,
3875        }
3876    }
3877
3878    pub fn id(&self) -> usize {
3879        self.model_id
3880    }
3881
3882    pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
3883        cx.model_handle_is_upgradable(self)
3884    }
3885
3886    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
3887        cx.upgrade_model_handle(self)
3888    }
3889}
3890
3891impl<T> Hash for WeakModelHandle<T> {
3892    fn hash<H: Hasher>(&self, state: &mut H) {
3893        self.model_id.hash(state)
3894    }
3895}
3896
3897impl<T> PartialEq for WeakModelHandle<T> {
3898    fn eq(&self, other: &Self) -> bool {
3899        self.model_id == other.model_id
3900    }
3901}
3902
3903impl<T> Eq for WeakModelHandle<T> {}
3904
3905impl<T: Entity> PartialEq<ModelHandle<T>> for WeakModelHandle<T> {
3906    fn eq(&self, other: &ModelHandle<T>) -> bool {
3907        self.model_id == other.model_id
3908    }
3909}
3910
3911impl<T> Clone for WeakModelHandle<T> {
3912    fn clone(&self) -> Self {
3913        Self {
3914            any_handle: self.any_handle.clone(),
3915            model_type: PhantomData,
3916        }
3917    }
3918}
3919
3920impl<T> Copy for WeakModelHandle<T> {}
3921
3922#[repr(transparent)]
3923pub struct ViewHandle<T> {
3924    any_handle: AnyViewHandle,
3925    view_type: PhantomData<T>,
3926}
3927
3928impl<T> Deref for ViewHandle<T> {
3929    type Target = AnyViewHandle;
3930
3931    fn deref(&self) -> &Self::Target {
3932        &self.any_handle
3933    }
3934}
3935
3936impl<T: View> ViewHandle<T> {
3937    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3938        Self {
3939            any_handle: AnyViewHandle::new(
3940                window_id,
3941                view_id,
3942                TypeId::of::<T>(),
3943                ref_counts.clone(),
3944            ),
3945            view_type: PhantomData,
3946        }
3947    }
3948
3949    pub fn downgrade(&self) -> WeakViewHandle<T> {
3950        WeakViewHandle::new(self.window_id, self.view_id)
3951    }
3952
3953    pub fn into_any(self) -> AnyViewHandle {
3954        self.any_handle
3955    }
3956
3957    pub fn window_id(&self) -> usize {
3958        self.window_id
3959    }
3960
3961    pub fn id(&self) -> usize {
3962        self.view_id
3963    }
3964
3965    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
3966        cx.read_view(self)
3967    }
3968
3969    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3970    where
3971        C: ReadViewWith,
3972        F: FnOnce(&T, &AppContext) -> S,
3973    {
3974        let mut read = Some(read);
3975        cx.read_view_with(self, &mut |view, cx| {
3976            let read = read.take().unwrap();
3977            read(view, cx)
3978        })
3979    }
3980
3981    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3982    where
3983        C: UpdateView,
3984        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
3985    {
3986        let mut update = Some(update);
3987        cx.update_view(self, &mut |view, cx| {
3988            let update = update.take().unwrap();
3989            update(view, cx)
3990        })
3991    }
3992
3993    pub fn defer<C, F>(&self, cx: &mut C, update: F)
3994    where
3995        C: AsMut<AppContext>,
3996        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
3997    {
3998        let this = self.clone();
3999        cx.as_mut().defer(move |cx| {
4000            this.update(cx, |view, cx| update(view, cx));
4001        });
4002    }
4003
4004    #[cfg(any(test, feature = "test-support"))]
4005    pub fn is_focused(&self, cx: &AppContext) -> bool {
4006        cx.read_window(self.window_id, |cx| {
4007            cx.focused_view_id() == Some(self.view_id)
4008        })
4009        .unwrap_or(false)
4010    }
4011}
4012
4013impl<T: View> Clone for ViewHandle<T> {
4014    fn clone(&self) -> Self {
4015        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
4016    }
4017}
4018
4019impl<T> PartialEq for ViewHandle<T> {
4020    fn eq(&self, other: &Self) -> bool {
4021        self.window_id == other.window_id && self.view_id == other.view_id
4022    }
4023}
4024
4025impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
4026    fn eq(&self, other: &WeakViewHandle<T>) -> bool {
4027        self.window_id == other.window_id && self.view_id == other.view_id
4028    }
4029}
4030
4031impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
4032    fn eq(&self, other: &ViewHandle<T>) -> bool {
4033        self.window_id == other.window_id && self.view_id == other.view_id
4034    }
4035}
4036
4037impl<T> Eq for ViewHandle<T> {}
4038
4039impl<T> Hash for ViewHandle<T> {
4040    fn hash<H: Hasher>(&self, state: &mut H) {
4041        self.window_id.hash(state);
4042        self.view_id.hash(state);
4043    }
4044}
4045
4046impl<T> Debug for ViewHandle<T> {
4047    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4048        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
4049            .field("window_id", &self.window_id)
4050            .field("view_id", &self.view_id)
4051            .finish()
4052    }
4053}
4054
4055impl<T: View> Handle<T> for ViewHandle<T> {
4056    type Weak = WeakViewHandle<T>;
4057
4058    fn id(&self) -> usize {
4059        self.view_id
4060    }
4061
4062    fn location(&self) -> EntityLocation {
4063        EntityLocation::View(self.window_id, self.view_id)
4064    }
4065
4066    fn downgrade(&self) -> Self::Weak {
4067        self.downgrade()
4068    }
4069
4070    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4071    where
4072        Self: Sized,
4073    {
4074        weak.upgrade(cx)
4075    }
4076}
4077
4078pub struct AnyViewHandle {
4079    window_id: usize,
4080    view_id: usize,
4081    view_type: TypeId,
4082    ref_counts: Arc<Mutex<RefCounts>>,
4083
4084    #[cfg(any(test, feature = "test-support"))]
4085    handle_id: usize,
4086}
4087
4088impl AnyViewHandle {
4089    fn new(
4090        window_id: usize,
4091        view_id: usize,
4092        view_type: TypeId,
4093        ref_counts: Arc<Mutex<RefCounts>>,
4094    ) -> Self {
4095        ref_counts.lock().inc_view(window_id, view_id);
4096
4097        #[cfg(any(test, feature = "test-support"))]
4098        let handle_id = ref_counts
4099            .lock()
4100            .leak_detector
4101            .lock()
4102            .handle_created(None, view_id);
4103
4104        Self {
4105            window_id,
4106            view_id,
4107            view_type,
4108            ref_counts,
4109            #[cfg(any(test, feature = "test-support"))]
4110            handle_id,
4111        }
4112    }
4113
4114    pub fn window_id(&self) -> usize {
4115        self.window_id
4116    }
4117
4118    pub fn id(&self) -> usize {
4119        self.view_id
4120    }
4121
4122    pub fn is<T: 'static>(&self) -> bool {
4123        TypeId::of::<T>() == self.view_type
4124    }
4125
4126    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
4127        if self.is::<T>() {
4128            Some(ViewHandle {
4129                any_handle: self,
4130                view_type: PhantomData,
4131            })
4132        } else {
4133            None
4134        }
4135    }
4136
4137    pub fn downcast_ref<T: View>(&self) -> Option<&ViewHandle<T>> {
4138        if self.is::<T>() {
4139            Some(unsafe { mem::transmute(self) })
4140        } else {
4141            None
4142        }
4143    }
4144
4145    pub fn downgrade(&self) -> AnyWeakViewHandle {
4146        AnyWeakViewHandle {
4147            window_id: self.window_id,
4148            view_id: self.view_id,
4149            view_type: self.view_type,
4150        }
4151    }
4152
4153    pub fn view_type(&self) -> TypeId {
4154        self.view_type
4155    }
4156
4157    pub fn debug_json<'a, 'b>(&self, cx: &'b WindowContext<'a, 'b>) -> serde_json::Value {
4158        cx.views
4159            .get(&(self.window_id, self.view_id))
4160            .map_or_else(|| serde_json::Value::Null, |view| view.debug_json(cx))
4161    }
4162}
4163
4164impl Clone for AnyViewHandle {
4165    fn clone(&self) -> Self {
4166        Self::new(
4167            self.window_id,
4168            self.view_id,
4169            self.view_type,
4170            self.ref_counts.clone(),
4171        )
4172    }
4173}
4174
4175impl<T> PartialEq<ViewHandle<T>> for AnyViewHandle {
4176    fn eq(&self, other: &ViewHandle<T>) -> bool {
4177        self.window_id == other.window_id && self.view_id == other.view_id
4178    }
4179}
4180
4181impl Drop for AnyViewHandle {
4182    fn drop(&mut self) {
4183        self.ref_counts
4184            .lock()
4185            .dec_view(self.window_id, self.view_id);
4186        #[cfg(any(test, feature = "test-support"))]
4187        self.ref_counts
4188            .lock()
4189            .leak_detector
4190            .lock()
4191            .handle_dropped(self.view_id, self.handle_id);
4192    }
4193}
4194
4195pub struct AnyModelHandle {
4196    model_id: usize,
4197    model_type: TypeId,
4198    ref_counts: Arc<Mutex<RefCounts>>,
4199
4200    #[cfg(any(test, feature = "test-support"))]
4201    handle_id: usize,
4202}
4203
4204impl AnyModelHandle {
4205    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
4206        ref_counts.lock().inc_model(model_id);
4207
4208        #[cfg(any(test, feature = "test-support"))]
4209        let handle_id = ref_counts
4210            .lock()
4211            .leak_detector
4212            .lock()
4213            .handle_created(None, model_id);
4214
4215        Self {
4216            model_id,
4217            model_type,
4218            ref_counts,
4219
4220            #[cfg(any(test, feature = "test-support"))]
4221            handle_id,
4222        }
4223    }
4224
4225    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
4226        if self.is::<T>() {
4227            Some(ModelHandle {
4228                any_handle: self,
4229                model_type: PhantomData,
4230            })
4231        } else {
4232            None
4233        }
4234    }
4235
4236    pub fn downgrade(&self) -> AnyWeakModelHandle {
4237        AnyWeakModelHandle {
4238            model_id: self.model_id,
4239            model_type: self.model_type,
4240        }
4241    }
4242
4243    pub fn is<T: Entity>(&self) -> bool {
4244        self.model_type == TypeId::of::<T>()
4245    }
4246
4247    pub fn model_type(&self) -> TypeId {
4248        self.model_type
4249    }
4250}
4251
4252impl Clone for AnyModelHandle {
4253    fn clone(&self) -> Self {
4254        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
4255    }
4256}
4257
4258impl Drop for AnyModelHandle {
4259    fn drop(&mut self) {
4260        let mut ref_counts = self.ref_counts.lock();
4261        ref_counts.dec_model(self.model_id);
4262
4263        #[cfg(any(test, feature = "test-support"))]
4264        ref_counts
4265            .leak_detector
4266            .lock()
4267            .handle_dropped(self.model_id, self.handle_id);
4268    }
4269}
4270
4271#[derive(Hash, PartialEq, Eq, Debug, Clone, Copy)]
4272pub struct AnyWeakModelHandle {
4273    model_id: usize,
4274    model_type: TypeId,
4275}
4276
4277impl AnyWeakModelHandle {
4278    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
4279        cx.upgrade_any_model_handle(self)
4280    }
4281    pub fn model_type(&self) -> TypeId {
4282        self.model_type
4283    }
4284
4285    fn is<T: 'static>(&self) -> bool {
4286        TypeId::of::<T>() == self.model_type
4287    }
4288
4289    pub fn downcast<T: Entity>(self) -> Option<WeakModelHandle<T>> {
4290        if self.is::<T>() {
4291            let result = Some(WeakModelHandle {
4292                any_handle: self,
4293                model_type: PhantomData,
4294            });
4295
4296            result
4297        } else {
4298            None
4299        }
4300    }
4301}
4302
4303#[derive(Debug, Copy)]
4304pub struct WeakViewHandle<T> {
4305    any_handle: AnyWeakViewHandle,
4306    view_type: PhantomData<T>,
4307}
4308
4309impl<T> WeakHandle for WeakViewHandle<T> {
4310    fn id(&self) -> usize {
4311        self.view_id
4312    }
4313}
4314
4315impl<T: View> WeakViewHandle<T> {
4316    fn new(window_id: usize, view_id: usize) -> Self {
4317        Self {
4318            any_handle: AnyWeakViewHandle {
4319                window_id,
4320                view_id,
4321                view_type: TypeId::of::<T>(),
4322            },
4323            view_type: PhantomData,
4324        }
4325    }
4326
4327    pub fn id(&self) -> usize {
4328        self.view_id
4329    }
4330
4331    pub fn window_id(&self) -> usize {
4332        self.window_id
4333    }
4334
4335    pub fn into_any(self) -> AnyWeakViewHandle {
4336        self.any_handle
4337    }
4338
4339    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
4340        cx.upgrade_view_handle(self)
4341    }
4342}
4343
4344impl<T> Deref for WeakViewHandle<T> {
4345    type Target = AnyWeakViewHandle;
4346
4347    fn deref(&self) -> &Self::Target {
4348        &self.any_handle
4349    }
4350}
4351
4352impl<T> Clone for WeakViewHandle<T> {
4353    fn clone(&self) -> Self {
4354        Self {
4355            any_handle: self.any_handle.clone(),
4356            view_type: PhantomData,
4357        }
4358    }
4359}
4360
4361impl<T> PartialEq for WeakViewHandle<T> {
4362    fn eq(&self, other: &Self) -> bool {
4363        self.window_id == other.window_id && self.view_id == other.view_id
4364    }
4365}
4366
4367impl<T> Eq for WeakViewHandle<T> {}
4368
4369impl<T> Hash for WeakViewHandle<T> {
4370    fn hash<H: Hasher>(&self, state: &mut H) {
4371        self.any_handle.hash(state);
4372    }
4373}
4374
4375#[derive(Debug, Clone, Copy)]
4376pub struct AnyWeakViewHandle {
4377    window_id: usize,
4378    view_id: usize,
4379    view_type: TypeId,
4380}
4381
4382impl AnyWeakViewHandle {
4383    pub fn id(&self) -> usize {
4384        self.view_id
4385    }
4386
4387    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<AnyViewHandle> {
4388        cx.upgrade_any_view_handle(self)
4389    }
4390}
4391
4392impl Hash for AnyWeakViewHandle {
4393    fn hash<H: Hasher>(&self, state: &mut H) {
4394        self.window_id.hash(state);
4395        self.view_id.hash(state);
4396        self.view_type.hash(state);
4397    }
4398}
4399
4400#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4401pub struct ElementStateId {
4402    view_id: usize,
4403    element_id: usize,
4404    tag: TypeId,
4405}
4406
4407pub struct ElementStateHandle<T> {
4408    value_type: PhantomData<T>,
4409    id: ElementStateId,
4410    ref_counts: Weak<Mutex<RefCounts>>,
4411}
4412
4413impl<T: 'static> ElementStateHandle<T> {
4414    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4415        ref_counts.lock().inc_element_state(id, frame_id);
4416        Self {
4417            value_type: PhantomData,
4418            id,
4419            ref_counts: Arc::downgrade(ref_counts),
4420        }
4421    }
4422
4423    pub fn id(&self) -> ElementStateId {
4424        self.id
4425    }
4426
4427    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
4428        cx.element_states
4429            .get(&self.id)
4430            .unwrap()
4431            .downcast_ref()
4432            .unwrap()
4433    }
4434
4435    pub fn update<C, D, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
4436    where
4437        C: DerefMut<Target = D>,
4438        D: DerefMut<Target = AppContext>,
4439    {
4440        let mut element_state = cx.deref_mut().element_states.remove(&self.id).unwrap();
4441        let result = f(element_state.downcast_mut().unwrap(), cx);
4442        cx.deref_mut().element_states.insert(self.id, element_state);
4443        result
4444    }
4445}
4446
4447impl<T> Drop for ElementStateHandle<T> {
4448    fn drop(&mut self) {
4449        if let Some(ref_counts) = self.ref_counts.upgrade() {
4450            ref_counts.lock().dec_element_state(self.id);
4451        }
4452    }
4453}
4454
4455#[must_use]
4456pub enum Subscription {
4457    Subscription(callback_collection::Subscription<usize, SubscriptionCallback>),
4458    Observation(callback_collection::Subscription<usize, ObservationCallback>),
4459    GlobalSubscription(callback_collection::Subscription<TypeId, GlobalSubscriptionCallback>),
4460    GlobalObservation(callback_collection::Subscription<TypeId, GlobalObservationCallback>),
4461    FocusObservation(callback_collection::Subscription<usize, FocusObservationCallback>),
4462    WindowActivationObservation(callback_collection::Subscription<usize, WindowActivationCallback>),
4463    WindowFullscreenObservation(callback_collection::Subscription<usize, WindowFullscreenCallback>),
4464    WindowBoundsObservation(callback_collection::Subscription<usize, WindowBoundsCallback>),
4465    KeystrokeObservation(callback_collection::Subscription<usize, KeystrokeCallback>),
4466    ReleaseObservation(callback_collection::Subscription<usize, ReleaseObservationCallback>),
4467    ActionObservation(callback_collection::Subscription<(), ActionObservationCallback>),
4468    ActiveLabeledTasksObservation(
4469        callback_collection::Subscription<(), ActiveLabeledTasksCallback>,
4470    ),
4471}
4472
4473impl Subscription {
4474    pub fn id(&self) -> usize {
4475        match self {
4476            Subscription::Subscription(subscription) => subscription.id(),
4477            Subscription::Observation(subscription) => subscription.id(),
4478            Subscription::GlobalSubscription(subscription) => subscription.id(),
4479            Subscription::GlobalObservation(subscription) => subscription.id(),
4480            Subscription::FocusObservation(subscription) => subscription.id(),
4481            Subscription::WindowActivationObservation(subscription) => subscription.id(),
4482            Subscription::WindowFullscreenObservation(subscription) => subscription.id(),
4483            Subscription::WindowBoundsObservation(subscription) => subscription.id(),
4484            Subscription::KeystrokeObservation(subscription) => subscription.id(),
4485            Subscription::ReleaseObservation(subscription) => subscription.id(),
4486            Subscription::ActionObservation(subscription) => subscription.id(),
4487            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.id(),
4488        }
4489    }
4490
4491    pub fn detach(&mut self) {
4492        match self {
4493            Subscription::Subscription(subscription) => subscription.detach(),
4494            Subscription::GlobalSubscription(subscription) => subscription.detach(),
4495            Subscription::Observation(subscription) => subscription.detach(),
4496            Subscription::GlobalObservation(subscription) => subscription.detach(),
4497            Subscription::FocusObservation(subscription) => subscription.detach(),
4498            Subscription::KeystrokeObservation(subscription) => subscription.detach(),
4499            Subscription::WindowActivationObservation(subscription) => subscription.detach(),
4500            Subscription::WindowFullscreenObservation(subscription) => subscription.detach(),
4501            Subscription::WindowBoundsObservation(subscription) => subscription.detach(),
4502            Subscription::ReleaseObservation(subscription) => subscription.detach(),
4503            Subscription::ActionObservation(subscription) => subscription.detach(),
4504            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.detach(),
4505        }
4506    }
4507}
4508
4509#[cfg(test)]
4510mod tests {
4511    use super::*;
4512    use crate::{
4513        actions,
4514        elements::*,
4515        impl_actions,
4516        platform::{MouseButton, MouseButtonEvent},
4517        window::ChildView,
4518    };
4519    use itertools::Itertools;
4520    use postage::{sink::Sink, stream::Stream};
4521    use serde::Deserialize;
4522    use smol::future::poll_once;
4523    use std::{
4524        cell::Cell,
4525        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
4526    };
4527
4528    #[crate::test(self)]
4529    fn test_model_handles(cx: &mut AppContext) {
4530        struct Model {
4531            other: Option<ModelHandle<Model>>,
4532            events: Vec<String>,
4533        }
4534
4535        impl Entity for Model {
4536            type Event = usize;
4537        }
4538
4539        impl Model {
4540            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
4541                if let Some(other) = other.as_ref() {
4542                    cx.observe(other, |me, _, _| {
4543                        me.events.push("notified".into());
4544                    })
4545                    .detach();
4546                    cx.subscribe(other, |me, _, event, _| {
4547                        me.events.push(format!("observed event {}", event));
4548                    })
4549                    .detach();
4550                }
4551
4552                Self {
4553                    other,
4554                    events: Vec::new(),
4555                }
4556            }
4557        }
4558
4559        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
4560        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
4561        assert_eq!(cx.models.len(), 2);
4562
4563        handle_1.update(cx, |model, cx| {
4564            model.events.push("updated".into());
4565            cx.emit(1);
4566            cx.notify();
4567            cx.emit(2);
4568        });
4569        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4570        assert_eq!(
4571            handle_2.read(cx).events,
4572            vec![
4573                "observed event 1".to_string(),
4574                "notified".to_string(),
4575                "observed event 2".to_string(),
4576            ]
4577        );
4578
4579        handle_2.update(cx, |model, _| {
4580            drop(handle_1);
4581            model.other.take();
4582        });
4583
4584        assert_eq!(cx.models.len(), 1);
4585        assert!(cx.subscriptions.is_empty());
4586        assert!(cx.observations.is_empty());
4587    }
4588
4589    #[crate::test(self)]
4590    fn test_model_events(cx: &mut AppContext) {
4591        #[derive(Default)]
4592        struct Model {
4593            events: Vec<usize>,
4594        }
4595
4596        impl Entity for Model {
4597            type Event = usize;
4598        }
4599
4600        let handle_1 = cx.add_model(|_| Model::default());
4601        let handle_2 = cx.add_model(|_| Model::default());
4602
4603        handle_1.update(cx, |_, cx| {
4604            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
4605                model.events.push(*event);
4606
4607                cx.subscribe(&emitter, |model, _, event, _| {
4608                    model.events.push(*event * 2);
4609                })
4610                .detach();
4611            })
4612            .detach();
4613        });
4614
4615        handle_2.update(cx, |_, c| c.emit(7));
4616        assert_eq!(handle_1.read(cx).events, vec![7]);
4617
4618        handle_2.update(cx, |_, c| c.emit(5));
4619        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4620    }
4621
4622    #[crate::test(self)]
4623    fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
4624        #[derive(Default)]
4625        struct Model;
4626
4627        impl Entity for Model {
4628            type Event = ();
4629        }
4630
4631        let events = Rc::new(RefCell::new(Vec::new()));
4632        cx.add_model(|cx| {
4633            drop(cx.subscribe(&cx.handle(), {
4634                let events = events.clone();
4635                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
4636            }));
4637            cx.subscribe(&cx.handle(), {
4638                let events = events.clone();
4639                move |_, _, _, _| events.borrow_mut().push("before emit")
4640            })
4641            .detach();
4642            cx.emit(());
4643            cx.subscribe(&cx.handle(), {
4644                let events = events.clone();
4645                move |_, _, _, _| events.borrow_mut().push("after emit")
4646            })
4647            .detach();
4648            Model
4649        });
4650        assert_eq!(*events.borrow(), ["before emit"]);
4651    }
4652
4653    #[crate::test(self)]
4654    fn test_observe_and_notify_from_model(cx: &mut AppContext) {
4655        #[derive(Default)]
4656        struct Model {
4657            count: usize,
4658            events: Vec<usize>,
4659        }
4660
4661        impl Entity for Model {
4662            type Event = ();
4663        }
4664
4665        let handle_1 = cx.add_model(|_| Model::default());
4666        let handle_2 = cx.add_model(|_| Model::default());
4667
4668        handle_1.update(cx, |_, c| {
4669            c.observe(&handle_2, move |model, observed, c| {
4670                model.events.push(observed.read(c).count);
4671                c.observe(&observed, |model, observed, c| {
4672                    model.events.push(observed.read(c).count * 2);
4673                })
4674                .detach();
4675            })
4676            .detach();
4677        });
4678
4679        handle_2.update(cx, |model, c| {
4680            model.count = 7;
4681            c.notify()
4682        });
4683        assert_eq!(handle_1.read(cx).events, vec![7]);
4684
4685        handle_2.update(cx, |model, c| {
4686            model.count = 5;
4687            c.notify()
4688        });
4689        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
4690    }
4691
4692    #[crate::test(self)]
4693    fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
4694        #[derive(Default)]
4695        struct Model;
4696
4697        impl Entity for Model {
4698            type Event = ();
4699        }
4700
4701        let events = Rc::new(RefCell::new(Vec::new()));
4702        cx.add_model(|cx| {
4703            drop(cx.observe(&cx.handle(), {
4704                let events = events.clone();
4705                move |_, _, _| events.borrow_mut().push("dropped before flush")
4706            }));
4707            cx.observe(&cx.handle(), {
4708                let events = events.clone();
4709                move |_, _, _| events.borrow_mut().push("before notify")
4710            })
4711            .detach();
4712            cx.notify();
4713            cx.observe(&cx.handle(), {
4714                let events = events.clone();
4715                move |_, _, _| events.borrow_mut().push("after notify")
4716            })
4717            .detach();
4718            Model
4719        });
4720        assert_eq!(*events.borrow(), ["before notify"]);
4721    }
4722
4723    #[crate::test(self)]
4724    fn test_defer_and_after_window_update(cx: &mut AppContext) {
4725        struct View {
4726            render_count: usize,
4727        }
4728
4729        impl Entity for View {
4730            type Event = usize;
4731        }
4732
4733        impl super::View for View {
4734            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
4735                post_inc(&mut self.render_count);
4736                Empty::new().boxed()
4737            }
4738
4739            fn ui_name() -> &'static str {
4740                "View"
4741            }
4742        }
4743
4744        let (_, view) = cx.add_window(Default::default(), |_| View { render_count: 0 });
4745        let called_defer = Rc::new(AtomicBool::new(false));
4746        let called_after_window_update = Rc::new(AtomicBool::new(false));
4747
4748        view.update(cx, |this, cx| {
4749            assert_eq!(this.render_count, 1);
4750            cx.defer({
4751                let called_defer = called_defer.clone();
4752                move |this, _| {
4753                    assert_eq!(this.render_count, 1);
4754                    called_defer.store(true, SeqCst);
4755                }
4756            });
4757            cx.after_window_update({
4758                let called_after_window_update = called_after_window_update.clone();
4759                move |this, cx| {
4760                    assert_eq!(this.render_count, 2);
4761                    called_after_window_update.store(true, SeqCst);
4762                    cx.notify();
4763                }
4764            });
4765            assert!(!called_defer.load(SeqCst));
4766            assert!(!called_after_window_update.load(SeqCst));
4767            cx.notify();
4768        });
4769
4770        assert!(called_defer.load(SeqCst));
4771        assert!(called_after_window_update.load(SeqCst));
4772        assert_eq!(view.read(cx).render_count, 3);
4773    }
4774
4775    #[crate::test(self)]
4776    fn test_view_handles(cx: &mut AppContext) {
4777        struct View {
4778            other: Option<ViewHandle<View>>,
4779            events: Vec<String>,
4780        }
4781
4782        impl Entity for View {
4783            type Event = usize;
4784        }
4785
4786        impl super::View for View {
4787            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
4788                Empty::new().boxed()
4789            }
4790
4791            fn ui_name() -> &'static str {
4792                "View"
4793            }
4794        }
4795
4796        impl View {
4797            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
4798                if let Some(other) = other.as_ref() {
4799                    cx.subscribe(other, |me, _, event, _| {
4800                        me.events.push(format!("observed event {}", event));
4801                    })
4802                    .detach();
4803                }
4804                Self {
4805                    other,
4806                    events: Vec::new(),
4807                }
4808            }
4809        }
4810
4811        let (_, root_view) = cx.add_window(Default::default(), |cx| View::new(None, cx));
4812        let handle_1 = cx.add_view(&root_view, |cx| View::new(None, cx));
4813        let handle_2 = cx.add_view(&root_view, |cx| View::new(Some(handle_1.clone()), cx));
4814        assert_eq!(cx.views.len(), 3);
4815
4816        handle_1.update(cx, |view, cx| {
4817            view.events.push("updated".into());
4818            cx.emit(1);
4819            cx.emit(2);
4820        });
4821        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4822        assert_eq!(
4823            handle_2.read(cx).events,
4824            vec![
4825                "observed event 1".to_string(),
4826                "observed event 2".to_string(),
4827            ]
4828        );
4829
4830        handle_2.update(cx, |view, _| {
4831            drop(handle_1);
4832            view.other.take();
4833        });
4834
4835        assert_eq!(cx.views.len(), 2);
4836        assert!(cx.subscriptions.is_empty());
4837        assert!(cx.observations.is_empty());
4838    }
4839
4840    #[crate::test(self)]
4841    fn test_add_window(cx: &mut AppContext) {
4842        struct View {
4843            mouse_down_count: Arc<AtomicUsize>,
4844        }
4845
4846        impl Entity for View {
4847            type Event = ();
4848        }
4849
4850        impl super::View for View {
4851            fn render(&mut self, cx: &mut ViewContext<Self>) -> Element<Self> {
4852                enum Handler {}
4853                let mouse_down_count = self.mouse_down_count.clone();
4854                MouseEventHandler::<Handler, _>::new(0, cx, |_, _| Empty::new().boxed())
4855                    .on_down(MouseButton::Left, move |_, _, _| {
4856                        mouse_down_count.fetch_add(1, SeqCst);
4857                    })
4858                    .boxed()
4859            }
4860
4861            fn ui_name() -> &'static str {
4862                "View"
4863            }
4864        }
4865
4866        let mouse_down_count = Arc::new(AtomicUsize::new(0));
4867        let (window_id, _) = cx.add_window(Default::default(), |_| View {
4868            mouse_down_count: mouse_down_count.clone(),
4869        });
4870
4871        cx.update_window(window_id, |cx| {
4872            // Ensure window's root element is in a valid lifecycle state.
4873            cx.dispatch_event(
4874                Event::MouseDown(MouseButtonEvent {
4875                    position: Default::default(),
4876                    button: MouseButton::Left,
4877                    modifiers: Default::default(),
4878                    click_count: 1,
4879                }),
4880                false,
4881            );
4882            assert_eq!(mouse_down_count.load(SeqCst), 1);
4883        });
4884    }
4885
4886    #[crate::test(self)]
4887    fn test_entity_release_hooks(cx: &mut AppContext) {
4888        struct Model {
4889            released: Rc<Cell<bool>>,
4890        }
4891
4892        struct View {
4893            released: Rc<Cell<bool>>,
4894        }
4895
4896        impl Entity for Model {
4897            type Event = ();
4898
4899            fn release(&mut self, _: &mut AppContext) {
4900                self.released.set(true);
4901            }
4902        }
4903
4904        impl Entity for View {
4905            type Event = ();
4906
4907            fn release(&mut self, _: &mut AppContext) {
4908                self.released.set(true);
4909            }
4910        }
4911
4912        impl super::View for View {
4913            fn ui_name() -> &'static str {
4914                "View"
4915            }
4916
4917            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
4918                Empty::new().boxed()
4919            }
4920        }
4921
4922        let model_released = Rc::new(Cell::new(false));
4923        let model_release_observed = Rc::new(Cell::new(false));
4924        let view_released = Rc::new(Cell::new(false));
4925        let view_release_observed = Rc::new(Cell::new(false));
4926
4927        let model = cx.add_model(|_| Model {
4928            released: model_released.clone(),
4929        });
4930        let (window_id, view) = cx.add_window(Default::default(), |_| View {
4931            released: view_released.clone(),
4932        });
4933        assert!(!model_released.get());
4934        assert!(!view_released.get());
4935
4936        cx.observe_release(&model, {
4937            let model_release_observed = model_release_observed.clone();
4938            move |_, _| model_release_observed.set(true)
4939        })
4940        .detach();
4941        cx.observe_release(&view, {
4942            let view_release_observed = view_release_observed.clone();
4943            move |_, _| view_release_observed.set(true)
4944        })
4945        .detach();
4946
4947        cx.update(move |_| {
4948            drop(model);
4949        });
4950        assert!(model_released.get());
4951        assert!(model_release_observed.get());
4952
4953        drop(view);
4954        cx.remove_window(window_id);
4955        assert!(view_released.get());
4956        assert!(view_release_observed.get());
4957    }
4958
4959    #[crate::test(self)]
4960    fn test_view_events(cx: &mut AppContext) {
4961        struct Model;
4962
4963        impl Entity for Model {
4964            type Event = String;
4965        }
4966
4967        let (_, handle_1) = cx.add_window(Default::default(), |_| TestView::default());
4968        let handle_2 = cx.add_view(&handle_1, |_| TestView::default());
4969        let handle_3 = cx.add_model(|_| Model);
4970
4971        handle_1.update(cx, |_, cx| {
4972            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
4973                me.events.push(event.clone());
4974
4975                cx.subscribe(&emitter, |me, _, event, _| {
4976                    me.events.push(format!("{event} from inner"));
4977                })
4978                .detach();
4979            })
4980            .detach();
4981
4982            cx.subscribe(&handle_3, |me, _, event, _| {
4983                me.events.push(event.clone());
4984            })
4985            .detach();
4986        });
4987
4988        handle_2.update(cx, |_, c| c.emit("7".into()));
4989        assert_eq!(handle_1.read(cx).events, vec!["7"]);
4990
4991        handle_2.update(cx, |_, c| c.emit("5".into()));
4992        assert_eq!(handle_1.read(cx).events, vec!["7", "5", "5 from inner"]);
4993
4994        handle_3.update(cx, |_, c| c.emit("9".into()));
4995        assert_eq!(
4996            handle_1.read(cx).events,
4997            vec!["7", "5", "5 from inner", "9"]
4998        );
4999    }
5000
5001    #[crate::test(self)]
5002    fn test_global_events(cx: &mut AppContext) {
5003        #[derive(Clone, Debug, Eq, PartialEq)]
5004        struct GlobalEvent(u64);
5005
5006        let events = Rc::new(RefCell::new(Vec::new()));
5007        let first_subscription;
5008        let second_subscription;
5009
5010        {
5011            let events = events.clone();
5012            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5013                events.borrow_mut().push(("First", e.clone()));
5014            });
5015        }
5016
5017        {
5018            let events = events.clone();
5019            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5020                events.borrow_mut().push(("Second", e.clone()));
5021            });
5022        }
5023
5024        cx.update(|cx| {
5025            cx.emit_global(GlobalEvent(1));
5026            cx.emit_global(GlobalEvent(2));
5027        });
5028
5029        drop(first_subscription);
5030
5031        cx.update(|cx| {
5032            cx.emit_global(GlobalEvent(3));
5033        });
5034
5035        drop(second_subscription);
5036
5037        cx.update(|cx| {
5038            cx.emit_global(GlobalEvent(4));
5039        });
5040
5041        assert_eq!(
5042            &*events.borrow(),
5043            &[
5044                ("First", GlobalEvent(1)),
5045                ("Second", GlobalEvent(1)),
5046                ("First", GlobalEvent(2)),
5047                ("Second", GlobalEvent(2)),
5048                ("Second", GlobalEvent(3)),
5049            ]
5050        );
5051    }
5052
5053    #[crate::test(self)]
5054    fn test_global_events_emitted_before_subscription_in_same_update_cycle(cx: &mut AppContext) {
5055        let events = Rc::new(RefCell::new(Vec::new()));
5056        cx.update(|cx| {
5057            {
5058                let events = events.clone();
5059                drop(cx.subscribe_global(move |_: &(), _| {
5060                    events.borrow_mut().push("dropped before emit");
5061                }));
5062            }
5063
5064            {
5065                let events = events.clone();
5066                cx.subscribe_global(move |_: &(), _| {
5067                    events.borrow_mut().push("before emit");
5068                })
5069                .detach();
5070            }
5071
5072            cx.emit_global(());
5073
5074            {
5075                let events = events.clone();
5076                cx.subscribe_global(move |_: &(), _| {
5077                    events.borrow_mut().push("after emit");
5078                })
5079                .detach();
5080            }
5081        });
5082
5083        assert_eq!(*events.borrow(), ["before emit"]);
5084    }
5085
5086    #[crate::test(self)]
5087    fn test_global_nested_events(cx: &mut AppContext) {
5088        #[derive(Clone, Debug, Eq, PartialEq)]
5089        struct GlobalEvent(u64);
5090
5091        let events = Rc::new(RefCell::new(Vec::new()));
5092
5093        {
5094            let events = events.clone();
5095            cx.subscribe_global(move |e: &GlobalEvent, cx| {
5096                events.borrow_mut().push(("Outer", e.clone()));
5097
5098                if e.0 == 1 {
5099                    let events = events.clone();
5100                    cx.subscribe_global(move |e: &GlobalEvent, _| {
5101                        events.borrow_mut().push(("Inner", e.clone()));
5102                    })
5103                    .detach();
5104                }
5105            })
5106            .detach();
5107        }
5108
5109        cx.update(|cx| {
5110            cx.emit_global(GlobalEvent(1));
5111            cx.emit_global(GlobalEvent(2));
5112            cx.emit_global(GlobalEvent(3));
5113        });
5114        cx.update(|cx| {
5115            cx.emit_global(GlobalEvent(4));
5116        });
5117
5118        assert_eq!(
5119            &*events.borrow(),
5120            &[
5121                ("Outer", GlobalEvent(1)),
5122                ("Outer", GlobalEvent(2)),
5123                ("Outer", GlobalEvent(3)),
5124                ("Outer", GlobalEvent(4)),
5125                ("Inner", GlobalEvent(4)),
5126            ]
5127        );
5128    }
5129
5130    #[crate::test(self)]
5131    fn test_global(cx: &mut AppContext) {
5132        type Global = usize;
5133
5134        let observation_count = Rc::new(RefCell::new(0));
5135        let subscription = cx.observe_global::<Global, _>({
5136            let observation_count = observation_count.clone();
5137            move |_| {
5138                *observation_count.borrow_mut() += 1;
5139            }
5140        });
5141
5142        assert!(!cx.has_global::<Global>());
5143        assert_eq!(cx.default_global::<Global>(), &0);
5144        assert_eq!(*observation_count.borrow(), 1);
5145        assert!(cx.has_global::<Global>());
5146        assert_eq!(
5147            cx.update_global::<Global, _, _>(|global, _| {
5148                *global = 1;
5149                "Update Result"
5150            }),
5151            "Update Result"
5152        );
5153        assert_eq!(*observation_count.borrow(), 2);
5154        assert_eq!(cx.global::<Global>(), &1);
5155
5156        drop(subscription);
5157        cx.update_global::<Global, _, _>(|global, _| {
5158            *global = 2;
5159        });
5160        assert_eq!(*observation_count.borrow(), 2);
5161
5162        type OtherGlobal = f32;
5163
5164        let observation_count = Rc::new(RefCell::new(0));
5165        cx.observe_global::<OtherGlobal, _>({
5166            let observation_count = observation_count.clone();
5167            move |_| {
5168                *observation_count.borrow_mut() += 1;
5169            }
5170        })
5171        .detach();
5172
5173        assert_eq!(
5174            cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
5175                assert_eq!(global, &0.0);
5176                *global = 2.0;
5177                "Default update result"
5178            }),
5179            "Default update result"
5180        );
5181        assert_eq!(cx.global::<OtherGlobal>(), &2.0);
5182        assert_eq!(*observation_count.borrow(), 1);
5183    }
5184
5185    #[crate::test(self)]
5186    fn test_dropping_subscribers(cx: &mut AppContext) {
5187        struct Model;
5188
5189        impl Entity for Model {
5190            type Event = ();
5191        }
5192
5193        let (_, root_view) = cx.add_window(Default::default(), |_| TestView::default());
5194        let observing_view = cx.add_view(&root_view, |_| TestView::default());
5195        let emitting_view = cx.add_view(&root_view, |_| TestView::default());
5196        let observing_model = cx.add_model(|_| Model);
5197        let observed_model = cx.add_model(|_| Model);
5198
5199        observing_view.update(cx, |_, cx| {
5200            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
5201            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5202        });
5203        observing_model.update(cx, |_, cx| {
5204            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5205        });
5206
5207        cx.update(|_| {
5208            drop(observing_view);
5209            drop(observing_model);
5210        });
5211
5212        emitting_view.update(cx, |_, cx| cx.emit(Default::default()));
5213        observed_model.update(cx, |_, cx| cx.emit(()));
5214    }
5215
5216    #[crate::test(self)]
5217    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
5218        let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
5219            drop(cx.subscribe(&cx.handle(), {
5220                move |this, _, _, _| this.events.push("dropped before flush".into())
5221            }));
5222            cx.subscribe(&cx.handle(), {
5223                move |this, _, _, _| this.events.push("before emit".into())
5224            })
5225            .detach();
5226            cx.emit("the event".into());
5227            cx.subscribe(&cx.handle(), {
5228                move |this, _, _, _| this.events.push("after emit".into())
5229            })
5230            .detach();
5231            TestView { events: Vec::new() }
5232        });
5233
5234        assert_eq!(view.read(cx).events, ["before emit"]);
5235    }
5236
5237    #[crate::test(self)]
5238    fn test_observe_and_notify_from_view(cx: &mut AppContext) {
5239        #[derive(Default)]
5240        struct Model {
5241            state: String,
5242        }
5243
5244        impl Entity for Model {
5245            type Event = ();
5246        }
5247
5248        let (_, view) = cx.add_window(Default::default(), |_| TestView::default());
5249        let model = cx.add_model(|_| Model {
5250            state: "old-state".into(),
5251        });
5252
5253        view.update(cx, |_, c| {
5254            c.observe(&model, |me, observed, cx| {
5255                me.events.push(observed.read(cx).state.clone())
5256            })
5257            .detach();
5258        });
5259
5260        model.update(cx, |model, cx| {
5261            model.state = "new-state".into();
5262            cx.notify();
5263        });
5264        assert_eq!(view.read(cx).events, vec!["new-state"]);
5265    }
5266
5267    #[crate::test(self)]
5268    fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
5269        let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
5270            drop(cx.observe(&cx.handle(), {
5271                move |this, _, _| this.events.push("dropped before flush".into())
5272            }));
5273            cx.observe(&cx.handle(), {
5274                move |this, _, _| this.events.push("before notify".into())
5275            })
5276            .detach();
5277            cx.notify();
5278            cx.observe(&cx.handle(), {
5279                move |this, _, _| this.events.push("after notify".into())
5280            })
5281            .detach();
5282            TestView { events: Vec::new() }
5283        });
5284
5285        assert_eq!(view.read(cx).events, ["before notify"]);
5286    }
5287
5288    #[crate::test(self)]
5289    fn test_notify_and_drop_observe_subscription_in_same_update_cycle(cx: &mut AppContext) {
5290        struct Model;
5291        impl Entity for Model {
5292            type Event = ();
5293        }
5294
5295        let model = cx.add_model(|_| Model);
5296        let (_, view) = cx.add_window(Default::default(), |_| TestView::default());
5297
5298        view.update(cx, |_, cx| {
5299            model.update(cx, |_, cx| cx.notify());
5300            drop(cx.observe(&model, move |this, _, _| {
5301                this.events.push("model notified".into());
5302            }));
5303            model.update(cx, |_, cx| cx.notify());
5304        });
5305
5306        for _ in 0..3 {
5307            model.update(cx, |_, cx| cx.notify());
5308        }
5309
5310        assert_eq!(view.read(cx).events, Vec::<String>::new());
5311    }
5312
5313    #[crate::test(self)]
5314    fn test_dropping_observers(cx: &mut AppContext) {
5315        struct Model;
5316
5317        impl Entity for Model {
5318            type Event = ();
5319        }
5320
5321        let (_, root_view) = cx.add_window(Default::default(), |_| TestView::default());
5322        let observing_view = cx.add_view(&root_view, |_| TestView::default());
5323        let observing_model = cx.add_model(|_| Model);
5324        let observed_model = cx.add_model(|_| Model);
5325
5326        observing_view.update(cx, |_, cx| {
5327            cx.observe(&observed_model, |_, _, _| {}).detach();
5328        });
5329        observing_model.update(cx, |_, cx| {
5330            cx.observe(&observed_model, |_, _, _| {}).detach();
5331        });
5332
5333        cx.update(|_| {
5334            drop(observing_view);
5335            drop(observing_model);
5336        });
5337
5338        observed_model.update(cx, |_, cx| cx.notify());
5339    }
5340
5341    #[crate::test(self)]
5342    fn test_dropping_subscriptions_during_callback(cx: &mut AppContext) {
5343        struct Model;
5344
5345        impl Entity for Model {
5346            type Event = u64;
5347        }
5348
5349        // Events
5350        let observing_model = cx.add_model(|_| Model);
5351        let observed_model = cx.add_model(|_| Model);
5352
5353        let events = Rc::new(RefCell::new(Vec::new()));
5354
5355        observing_model.update(cx, |_, cx| {
5356            let events = events.clone();
5357            let subscription = Rc::new(RefCell::new(None));
5358            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
5359                let subscription = subscription.clone();
5360                move |_, _, e, _| {
5361                    subscription.borrow_mut().take();
5362                    events.borrow_mut().push(*e);
5363                }
5364            }));
5365        });
5366
5367        observed_model.update(cx, |_, cx| {
5368            cx.emit(1);
5369            cx.emit(2);
5370        });
5371
5372        assert_eq!(*events.borrow(), [1]);
5373
5374        // Global Events
5375        #[derive(Clone, Debug, Eq, PartialEq)]
5376        struct GlobalEvent(u64);
5377
5378        let events = Rc::new(RefCell::new(Vec::new()));
5379
5380        {
5381            let events = events.clone();
5382            let subscription = Rc::new(RefCell::new(None));
5383            *subscription.borrow_mut() = Some(cx.subscribe_global({
5384                let subscription = subscription.clone();
5385                move |e: &GlobalEvent, _| {
5386                    subscription.borrow_mut().take();
5387                    events.borrow_mut().push(e.clone());
5388                }
5389            }));
5390        }
5391
5392        cx.update(|cx| {
5393            cx.emit_global(GlobalEvent(1));
5394            cx.emit_global(GlobalEvent(2));
5395        });
5396
5397        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
5398
5399        // Model Observation
5400        let observing_model = cx.add_model(|_| Model);
5401        let observed_model = cx.add_model(|_| Model);
5402
5403        let observation_count = Rc::new(RefCell::new(0));
5404
5405        observing_model.update(cx, |_, cx| {
5406            let observation_count = observation_count.clone();
5407            let subscription = Rc::new(RefCell::new(None));
5408            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
5409                let subscription = subscription.clone();
5410                move |_, _, _| {
5411                    subscription.borrow_mut().take();
5412                    *observation_count.borrow_mut() += 1;
5413                }
5414            }));
5415        });
5416
5417        observed_model.update(cx, |_, cx| {
5418            cx.notify();
5419        });
5420
5421        observed_model.update(cx, |_, cx| {
5422            cx.notify();
5423        });
5424
5425        assert_eq!(*observation_count.borrow(), 1);
5426
5427        // View Observation
5428        struct View;
5429
5430        impl Entity for View {
5431            type Event = ();
5432        }
5433
5434        impl super::View for View {
5435            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5436                Empty::new().boxed()
5437            }
5438
5439            fn ui_name() -> &'static str {
5440                "View"
5441            }
5442        }
5443
5444        let (_, root_view) = cx.add_window(Default::default(), |_| View);
5445        let observing_view = cx.add_view(&root_view, |_| View);
5446        let observed_view = cx.add_view(&root_view, |_| View);
5447
5448        let observation_count = Rc::new(RefCell::new(0));
5449        observing_view.update(cx, |_, cx| {
5450            let observation_count = observation_count.clone();
5451            let subscription = Rc::new(RefCell::new(None));
5452            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
5453                let subscription = subscription.clone();
5454                move |_, _, _| {
5455                    subscription.borrow_mut().take();
5456                    *observation_count.borrow_mut() += 1;
5457                }
5458            }));
5459        });
5460
5461        observed_view.update(cx, |_, cx| {
5462            cx.notify();
5463        });
5464
5465        observed_view.update(cx, |_, cx| {
5466            cx.notify();
5467        });
5468
5469        assert_eq!(*observation_count.borrow(), 1);
5470
5471        // Global Observation
5472        let observation_count = Rc::new(RefCell::new(0));
5473        let subscription = Rc::new(RefCell::new(None));
5474        *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
5475            let observation_count = observation_count.clone();
5476            let subscription = subscription.clone();
5477            move |_| {
5478                subscription.borrow_mut().take();
5479                *observation_count.borrow_mut() += 1;
5480            }
5481        }));
5482
5483        cx.default_global::<()>();
5484        cx.set_global(());
5485        assert_eq!(*observation_count.borrow(), 1);
5486    }
5487
5488    #[crate::test(self)]
5489    fn test_focus(cx: &mut AppContext) {
5490        struct View {
5491            name: String,
5492            events: Arc<Mutex<Vec<String>>>,
5493        }
5494
5495        impl Entity for View {
5496            type Event = ();
5497        }
5498
5499        impl super::View for View {
5500            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5501                Empty::new().boxed()
5502            }
5503
5504            fn ui_name() -> &'static str {
5505                "View"
5506            }
5507
5508            fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
5509                if cx.handle().id() == focused.id() {
5510                    self.events.lock().push(format!("{} focused", &self.name));
5511                }
5512            }
5513
5514            fn focus_out(&mut self, blurred: AnyViewHandle, cx: &mut ViewContext<Self>) {
5515                if cx.handle().id() == blurred.id() {
5516                    self.events.lock().push(format!("{} blurred", &self.name));
5517                }
5518            }
5519        }
5520
5521        let view_events: Arc<Mutex<Vec<String>>> = Default::default();
5522        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
5523            events: view_events.clone(),
5524            name: "view 1".to_string(),
5525        });
5526        let view_2 = cx.add_view(&view_1, |_| View {
5527            events: view_events.clone(),
5528            name: "view 2".to_string(),
5529        });
5530
5531        let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
5532        view_1.update(cx, |_, cx| {
5533            cx.observe_focus(&view_2, {
5534                let observed_events = observed_events.clone();
5535                move |this, view, focused, cx| {
5536                    let label = if focused { "focus" } else { "blur" };
5537                    observed_events.lock().push(format!(
5538                        "{} observed {}'s {}",
5539                        this.name,
5540                        view.read(cx).name,
5541                        label
5542                    ))
5543                }
5544            })
5545            .detach();
5546        });
5547        view_2.update(cx, |_, cx| {
5548            cx.observe_focus(&view_1, {
5549                let observed_events = observed_events.clone();
5550                move |this, view, focused, cx| {
5551                    let label = if focused { "focus" } else { "blur" };
5552                    observed_events.lock().push(format!(
5553                        "{} observed {}'s {}",
5554                        this.name,
5555                        view.read(cx).name,
5556                        label
5557                    ))
5558                }
5559            })
5560            .detach();
5561        });
5562        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
5563        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
5564
5565        view_1.update(cx, |_, cx| {
5566            // Ensure focus events are sent for all intermediate focuses
5567            cx.focus(&view_2);
5568            cx.focus(&view_1);
5569            cx.focus(&view_2);
5570        });
5571
5572        cx.read_window(window_id, |cx| {
5573            assert!(cx.is_child_focused(&view_1));
5574            assert!(!cx.is_child_focused(&view_2));
5575        });
5576        assert_eq!(
5577            mem::take(&mut *view_events.lock()),
5578            [
5579                "view 1 blurred",
5580                "view 2 focused",
5581                "view 2 blurred",
5582                "view 1 focused",
5583                "view 1 blurred",
5584                "view 2 focused"
5585            ],
5586        );
5587        assert_eq!(
5588            mem::take(&mut *observed_events.lock()),
5589            [
5590                "view 2 observed view 1's blur",
5591                "view 1 observed view 2's focus",
5592                "view 1 observed view 2's blur",
5593                "view 2 observed view 1's focus",
5594                "view 2 observed view 1's blur",
5595                "view 1 observed view 2's focus"
5596            ]
5597        );
5598
5599        view_1.update(cx, |_, cx| cx.focus(&view_1));
5600        cx.read_window(window_id, |cx| {
5601            assert!(!cx.is_child_focused(&view_1));
5602            assert!(!cx.is_child_focused(&view_2));
5603        });
5604        assert_eq!(
5605            mem::take(&mut *view_events.lock()),
5606            ["view 2 blurred", "view 1 focused"],
5607        );
5608        assert_eq!(
5609            mem::take(&mut *observed_events.lock()),
5610            [
5611                "view 1 observed view 2's blur",
5612                "view 2 observed view 1's focus"
5613            ]
5614        );
5615
5616        view_1.update(cx, |_, cx| cx.focus(&view_2));
5617        assert_eq!(
5618            mem::take(&mut *view_events.lock()),
5619            ["view 1 blurred", "view 2 focused"],
5620        );
5621        assert_eq!(
5622            mem::take(&mut *observed_events.lock()),
5623            [
5624                "view 2 observed view 1's blur",
5625                "view 1 observed view 2's focus"
5626            ]
5627        );
5628
5629        view_1.update(cx, |_, _| drop(view_2));
5630        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
5631        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
5632    }
5633
5634    #[crate::test(self)]
5635    fn test_deserialize_actions(cx: &mut AppContext) {
5636        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
5637        pub struct ComplexAction {
5638            arg: String,
5639            count: usize,
5640        }
5641
5642        actions!(test::something, [SimpleAction]);
5643        impl_actions!(test::something, [ComplexAction]);
5644
5645        cx.add_global_action(move |_: &SimpleAction, _: &mut AppContext| {});
5646        cx.add_global_action(move |_: &ComplexAction, _: &mut AppContext| {});
5647
5648        let action1 = cx
5649            .deserialize_action(
5650                "test::something::ComplexAction",
5651                Some(r#"{"arg": "a", "count": 5}"#),
5652            )
5653            .unwrap();
5654        let action2 = cx
5655            .deserialize_action("test::something::SimpleAction", None)
5656            .unwrap();
5657        assert_eq!(
5658            action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
5659            &ComplexAction {
5660                arg: "a".to_string(),
5661                count: 5,
5662            }
5663        );
5664        assert_eq!(
5665            action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
5666            &SimpleAction
5667        );
5668    }
5669
5670    #[crate::test(self)]
5671    fn test_dispatch_action(cx: &mut AppContext) {
5672        struct ViewA {
5673            id: usize,
5674        }
5675
5676        impl Entity for ViewA {
5677            type Event = ();
5678        }
5679
5680        impl View for ViewA {
5681            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5682                Empty::new().boxed()
5683            }
5684
5685            fn ui_name() -> &'static str {
5686                "View"
5687            }
5688        }
5689
5690        struct ViewB {
5691            id: usize,
5692        }
5693
5694        impl Entity for ViewB {
5695            type Event = ();
5696        }
5697
5698        impl View for ViewB {
5699            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5700                Empty::new().boxed()
5701            }
5702
5703            fn ui_name() -> &'static str {
5704                "View"
5705            }
5706        }
5707
5708        #[derive(Clone, Default, Deserialize, PartialEq)]
5709        pub struct Action(pub String);
5710
5711        impl_actions!(test, [Action]);
5712
5713        let actions = Rc::new(RefCell::new(Vec::new()));
5714
5715        cx.add_global_action({
5716            let actions = actions.clone();
5717            move |_: &Action, _: &mut AppContext| {
5718                actions.borrow_mut().push("global".to_string());
5719            }
5720        });
5721
5722        cx.add_action({
5723            let actions = actions.clone();
5724            move |view: &mut ViewA, action: &Action, cx| {
5725                assert_eq!(action.0, "bar");
5726                cx.propagate_action();
5727                actions.borrow_mut().push(format!("{} a", view.id));
5728            }
5729        });
5730
5731        cx.add_action({
5732            let actions = actions.clone();
5733            move |view: &mut ViewA, _: &Action, cx| {
5734                if view.id != 1 {
5735                    cx.add_view(|cx| {
5736                        cx.propagate_action(); // Still works on a nested ViewContext
5737                        ViewB { id: 5 }
5738                    });
5739                }
5740                actions.borrow_mut().push(format!("{} b", view.id));
5741            }
5742        });
5743
5744        cx.add_action({
5745            let actions = actions.clone();
5746            move |view: &mut ViewB, _: &Action, cx| {
5747                cx.propagate_action();
5748                actions.borrow_mut().push(format!("{} c", view.id));
5749            }
5750        });
5751
5752        cx.add_action({
5753            let actions = actions.clone();
5754            move |view: &mut ViewB, _: &Action, cx| {
5755                cx.propagate_action();
5756                actions.borrow_mut().push(format!("{} d", view.id));
5757            }
5758        });
5759
5760        cx.capture_action({
5761            let actions = actions.clone();
5762            move |view: &mut ViewA, _: &Action, cx| {
5763                cx.propagate_action();
5764                actions.borrow_mut().push(format!("{} capture", view.id));
5765            }
5766        });
5767
5768        let observed_actions = Rc::new(RefCell::new(Vec::new()));
5769        cx.observe_actions({
5770            let observed_actions = observed_actions.clone();
5771            move |action_id, _| observed_actions.borrow_mut().push(action_id)
5772        })
5773        .detach();
5774
5775        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
5776        let view_2 = cx.add_view(&view_1, |_| ViewB { id: 2 });
5777        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
5778        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
5779
5780        cx.update_window(window_id, |cx| {
5781            cx.handle_dispatch_action_from_effect(Some(view_4.id()), &Action("bar".to_string()))
5782        });
5783
5784        assert_eq!(
5785            *actions.borrow(),
5786            vec![
5787                "1 capture",
5788                "3 capture",
5789                "4 d",
5790                "4 c",
5791                "3 b",
5792                "3 a",
5793                "2 d",
5794                "2 c",
5795                "1 b"
5796            ]
5797        );
5798        assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
5799
5800        // Remove view_1, which doesn't propagate the action
5801
5802        let (window_id, view_2) = cx.add_window(Default::default(), |_| ViewB { id: 2 });
5803        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
5804        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
5805
5806        actions.borrow_mut().clear();
5807        cx.update_window(window_id, |cx| {
5808            cx.handle_dispatch_action_from_effect(Some(view_4.id()), &Action("bar".to_string()))
5809        });
5810
5811        assert_eq!(
5812            *actions.borrow(),
5813            vec![
5814                "3 capture",
5815                "4 d",
5816                "4 c",
5817                "3 b",
5818                "3 a",
5819                "2 d",
5820                "2 c",
5821                "global"
5822            ]
5823        );
5824        assert_eq!(
5825            *observed_actions.borrow(),
5826            [Action::default().id(), Action::default().id()]
5827        );
5828    }
5829
5830    #[crate::test(self)]
5831    fn test_dispatch_keystroke(cx: &mut AppContext) {
5832        #[derive(Clone, Deserialize, PartialEq)]
5833        pub struct Action(String);
5834
5835        impl_actions!(test, [Action]);
5836
5837        struct View {
5838            id: usize,
5839            keymap_context: KeymapContext,
5840        }
5841
5842        impl Entity for View {
5843            type Event = ();
5844        }
5845
5846        impl super::View for View {
5847            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5848                Empty::new().boxed()
5849            }
5850
5851            fn ui_name() -> &'static str {
5852                "View"
5853            }
5854
5855            fn keymap_context(&self, _: &AppContext) -> KeymapContext {
5856                self.keymap_context.clone()
5857            }
5858        }
5859
5860        impl View {
5861            fn new(id: usize) -> Self {
5862                View {
5863                    id,
5864                    keymap_context: KeymapContext::default(),
5865                }
5866            }
5867        }
5868
5869        let mut view_1 = View::new(1);
5870        let mut view_2 = View::new(2);
5871        let mut view_3 = View::new(3);
5872        view_1.keymap_context.add_identifier("a");
5873        view_2.keymap_context.add_identifier("a");
5874        view_2.keymap_context.add_identifier("b");
5875        view_3.keymap_context.add_identifier("a");
5876        view_3.keymap_context.add_identifier("b");
5877        view_3.keymap_context.add_identifier("c");
5878
5879        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
5880        let view_2 = cx.add_view(&view_1, |_| view_2);
5881        let _view_3 = cx.add_view(&view_2, |cx| {
5882            cx.focus_self();
5883            view_3
5884        });
5885
5886        // This binding only dispatches an action on view 2 because that view will have
5887        // "a" and "b" in its context, but not "c".
5888        cx.add_bindings(vec![Binding::new(
5889            "a",
5890            Action("a".to_string()),
5891            Some("a && b && !c"),
5892        )]);
5893
5894        cx.add_bindings(vec![Binding::new("b", Action("b".to_string()), None)]);
5895
5896        // This binding only dispatches an action on views 2 and 3, because they have
5897        // a parent view with a in its context
5898        cx.add_bindings(vec![Binding::new(
5899            "c",
5900            Action("c".to_string()),
5901            Some("b > c"),
5902        )]);
5903
5904        // This binding only dispatches an action on view 2, because they have
5905        // a parent view with a in its context
5906        cx.add_bindings(vec![Binding::new(
5907            "d",
5908            Action("d".to_string()),
5909            Some("a && !b > b"),
5910        )]);
5911
5912        let actions = Rc::new(RefCell::new(Vec::new()));
5913        cx.add_action({
5914            let actions = actions.clone();
5915            move |view: &mut View, action: &Action, cx| {
5916                actions
5917                    .borrow_mut()
5918                    .push(format!("{} {}", view.id, action.0));
5919
5920                if action.0 == "b" {
5921                    cx.propagate_action();
5922                }
5923            }
5924        });
5925
5926        cx.add_global_action({
5927            let actions = actions.clone();
5928            move |action: &Action, _| {
5929                actions.borrow_mut().push(format!("global {}", action.0));
5930            }
5931        });
5932
5933        cx.update_window(window_id, |cx| {
5934            cx.dispatch_keystroke(&Keystroke::parse("a").unwrap())
5935        });
5936        assert_eq!(&*actions.borrow(), &["2 a"]);
5937        actions.borrow_mut().clear();
5938
5939        cx.update_window(window_id, |cx| {
5940            cx.dispatch_keystroke(&Keystroke::parse("b").unwrap());
5941        });
5942
5943        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
5944        actions.borrow_mut().clear();
5945
5946        cx.update_window(window_id, |cx| {
5947            cx.dispatch_keystroke(&Keystroke::parse("c").unwrap());
5948        });
5949        assert_eq!(&*actions.borrow(), &["3 c"]);
5950        actions.borrow_mut().clear();
5951
5952        cx.update_window(window_id, |cx| {
5953            cx.dispatch_keystroke(&Keystroke::parse("d").unwrap());
5954        });
5955        assert_eq!(&*actions.borrow(), &["2 d"]);
5956        actions.borrow_mut().clear();
5957    }
5958
5959    #[crate::test(self)]
5960    fn test_keystrokes_for_action(cx: &mut AppContext) {
5961        actions!(test, [Action1, Action2, GlobalAction]);
5962
5963        struct View1 {}
5964        struct View2 {}
5965
5966        impl Entity for View1 {
5967            type Event = ();
5968        }
5969        impl Entity for View2 {
5970            type Event = ();
5971        }
5972
5973        impl super::View for View1 {
5974            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5975                Empty::new().boxed()
5976            }
5977            fn ui_name() -> &'static str {
5978                "View1"
5979            }
5980        }
5981        impl super::View for View2 {
5982            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5983                Empty::new().boxed()
5984            }
5985            fn ui_name() -> &'static str {
5986                "View2"
5987            }
5988        }
5989
5990        let (window_id, view_1) = cx.add_window(Default::default(), |_| View1 {});
5991        let view_2 = cx.add_view(&view_1, |cx| {
5992            cx.focus_self();
5993            View2 {}
5994        });
5995
5996        cx.add_action(|_: &mut View1, _: &Action1, _cx| {});
5997        cx.add_action(|_: &mut View2, _: &Action2, _cx| {});
5998        cx.add_global_action(|_: &GlobalAction, _| {});
5999
6000        cx.add_bindings(vec![
6001            Binding::new("a", Action1, Some("View1")),
6002            Binding::new("b", Action2, Some("View1 > View2")),
6003            Binding::new("c", GlobalAction, Some("View3")), // View 3 does not exist
6004        ]);
6005
6006        cx.update_window(window_id, |cx| {
6007            // Sanity check
6008            assert_eq!(
6009                cx.keystrokes_for_action(view_1.id(), &Action1)
6010                    .unwrap()
6011                    .as_slice(),
6012                &[Keystroke::parse("a").unwrap()]
6013            );
6014            assert_eq!(
6015                cx.keystrokes_for_action(view_2.id(), &Action2)
6016                    .unwrap()
6017                    .as_slice(),
6018                &[Keystroke::parse("b").unwrap()]
6019            );
6020
6021            // The 'a' keystroke propagates up the view tree from view_2
6022            // to view_1. The action, Action1, is handled by view_1.
6023            assert_eq!(
6024                cx.keystrokes_for_action(view_2.id(), &Action1)
6025                    .unwrap()
6026                    .as_slice(),
6027                &[Keystroke::parse("a").unwrap()]
6028            );
6029
6030            // Actions that are handled below the current view don't have bindings
6031            assert_eq!(cx.keystrokes_for_action(view_1.id(), &Action2), None);
6032
6033            // Actions that are handled in other branches of the tree should not have a binding
6034            assert_eq!(cx.keystrokes_for_action(view_2.id(), &GlobalAction), None);
6035
6036            // Check that global actions do not have a binding, even if a binding does exist in another view
6037            assert_eq!(
6038                &available_actions(view_1.id(), cx),
6039                &[
6040                    ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
6041                    ("test::GlobalAction", vec![])
6042                ],
6043            );
6044
6045            // Check that view 1 actions and bindings are available even when called from view 2
6046            assert_eq!(
6047                &available_actions(view_2.id(), cx),
6048                &[
6049                    ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
6050                    ("test::Action2", vec![Keystroke::parse("b").unwrap()]),
6051                    ("test::GlobalAction", vec![]),
6052                ],
6053            );
6054        });
6055
6056        // Produces a list of actions and key bindings
6057        fn available_actions(
6058            view_id: usize,
6059            cx: &WindowContext,
6060        ) -> Vec<(&'static str, Vec<Keystroke>)> {
6061            cx.available_actions(view_id)
6062                .map(|(action_name, _, bindings)| {
6063                    (
6064                        action_name,
6065                        bindings
6066                            .iter()
6067                            .map(|binding| binding.keystrokes()[0].clone())
6068                            .collect::<Vec<_>>(),
6069                    )
6070                })
6071                .sorted_by(|(name1, _), (name2, _)| name1.cmp(name2))
6072                .collect()
6073        }
6074    }
6075
6076    #[crate::test(self)]
6077    async fn test_model_condition(cx: &mut TestAppContext) {
6078        struct Counter(usize);
6079
6080        impl super::Entity for Counter {
6081            type Event = ();
6082        }
6083
6084        impl Counter {
6085            fn inc(&mut self, cx: &mut ModelContext<Self>) {
6086                self.0 += 1;
6087                cx.notify();
6088            }
6089        }
6090
6091        let model = cx.add_model(|_| Counter(0));
6092
6093        let condition1 = model.condition(cx, |model, _| model.0 == 2);
6094        let condition2 = model.condition(cx, |model, _| model.0 == 3);
6095        smol::pin!(condition1, condition2);
6096
6097        model.update(cx, |model, cx| model.inc(cx));
6098        assert_eq!(poll_once(&mut condition1).await, None);
6099        assert_eq!(poll_once(&mut condition2).await, None);
6100
6101        model.update(cx, |model, cx| model.inc(cx));
6102        assert_eq!(poll_once(&mut condition1).await, Some(()));
6103        assert_eq!(poll_once(&mut condition2).await, None);
6104
6105        model.update(cx, |model, cx| model.inc(cx));
6106        assert_eq!(poll_once(&mut condition2).await, Some(()));
6107
6108        model.update(cx, |_, cx| cx.notify());
6109    }
6110
6111    #[crate::test(self)]
6112    #[should_panic]
6113    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
6114        struct Model;
6115
6116        impl super::Entity for Model {
6117            type Event = ();
6118        }
6119
6120        let model = cx.add_model(|_| Model);
6121        model.condition(cx, |_, _| false).await;
6122    }
6123
6124    #[crate::test(self)]
6125    #[should_panic(expected = "model dropped with pending condition")]
6126    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
6127        struct Model;
6128
6129        impl super::Entity for Model {
6130            type Event = ();
6131        }
6132
6133        let model = cx.add_model(|_| Model);
6134        let condition = model.condition(cx, |_, _| false);
6135        cx.update(|_| drop(model));
6136        condition.await;
6137    }
6138
6139    #[crate::test(self)]
6140    async fn test_view_condition(cx: &mut TestAppContext) {
6141        struct Counter(usize);
6142
6143        impl super::Entity for Counter {
6144            type Event = ();
6145        }
6146
6147        impl super::View for Counter {
6148            fn ui_name() -> &'static str {
6149                "test view"
6150            }
6151
6152            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6153                Empty::new().boxed()
6154            }
6155        }
6156
6157        impl Counter {
6158            fn inc(&mut self, cx: &mut ViewContext<Self>) {
6159                self.0 += 1;
6160                cx.notify();
6161            }
6162        }
6163
6164        let (_, view) = cx.add_window(|_| Counter(0));
6165
6166        let condition1 = view.condition(cx, |view, _| view.0 == 2);
6167        let condition2 = view.condition(cx, |view, _| view.0 == 3);
6168        smol::pin!(condition1, condition2);
6169
6170        view.update(cx, |view, cx| view.inc(cx));
6171        assert_eq!(poll_once(&mut condition1).await, None);
6172        assert_eq!(poll_once(&mut condition2).await, None);
6173
6174        view.update(cx, |view, cx| view.inc(cx));
6175        assert_eq!(poll_once(&mut condition1).await, Some(()));
6176        assert_eq!(poll_once(&mut condition2).await, None);
6177
6178        view.update(cx, |view, cx| view.inc(cx));
6179        assert_eq!(poll_once(&mut condition2).await, Some(()));
6180        view.update(cx, |_, cx| cx.notify());
6181    }
6182
6183    #[crate::test(self)]
6184    #[should_panic]
6185    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
6186        let (_, view) = cx.add_window(|_| TestView::default());
6187        view.condition(cx, |_, _| false).await;
6188    }
6189
6190    #[crate::test(self)]
6191    #[should_panic(expected = "view dropped with pending condition")]
6192    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
6193        let (_, root_view) = cx.add_window(|_| TestView::default());
6194        let view = cx.add_view(&root_view, |_| TestView::default());
6195
6196        let condition = view.condition(cx, |_, _| false);
6197        cx.update(|_| drop(view));
6198        condition.await;
6199    }
6200
6201    #[crate::test(self)]
6202    fn test_refresh_windows(cx: &mut AppContext) {
6203        struct View(usize);
6204
6205        impl super::Entity for View {
6206            type Event = ();
6207        }
6208
6209        impl super::View for View {
6210            fn ui_name() -> &'static str {
6211                "test view"
6212            }
6213
6214            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6215                Empty::new().named(format!("render count: {}", post_inc(&mut self.0)))
6216            }
6217        }
6218
6219        let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
6220        cx.update_window(window_id, |cx| {
6221            assert_eq!(
6222                cx.window.rendered_views[&root_view.id()].name(),
6223                Some("render count: 0")
6224            );
6225        });
6226
6227        let view = cx.add_view(&root_view, |cx| {
6228            cx.refresh_windows();
6229            View(0)
6230        });
6231
6232        cx.update_window(window_id, |cx| {
6233            assert_eq!(
6234                cx.window.rendered_views[&root_view.id()].name(),
6235                Some("render count: 1")
6236            );
6237            assert_eq!(
6238                cx.window.rendered_views[&view.id()].name(),
6239                Some("render count: 0")
6240            );
6241        });
6242
6243        cx.update(|cx| cx.refresh_windows());
6244
6245        cx.update_window(window_id, |cx| {
6246            assert_eq!(
6247                cx.window.rendered_views[&root_view.id()].name(),
6248                Some("render count: 2")
6249            );
6250            assert_eq!(
6251                cx.window.rendered_views[&view.id()].name(),
6252                Some("render count: 1")
6253            );
6254        });
6255
6256        cx.update(|cx| {
6257            cx.refresh_windows();
6258            drop(view);
6259        });
6260
6261        cx.update_window(window_id, |cx| {
6262            assert_eq!(
6263                cx.window.rendered_views[&root_view.id()].name(),
6264                Some("render count: 3")
6265            );
6266            assert_eq!(cx.window.rendered_views.len(), 1);
6267        });
6268    }
6269
6270    #[crate::test(self)]
6271    async fn test_labeled_tasks(cx: &mut TestAppContext) {
6272        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6273        let (mut sender, mut reciever) = postage::oneshot::channel::<()>();
6274        let task = cx
6275            .update(|cx| cx.spawn_labeled("Test Label", |_| async move { reciever.recv().await }));
6276
6277        assert_eq!(
6278            Some("Test Label"),
6279            cx.update(|cx| cx.active_labeled_tasks().next())
6280        );
6281        sender
6282            .send(())
6283            .await
6284            .expect("Could not send message to complete task");
6285        task.await;
6286
6287        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6288    }
6289
6290    #[crate::test(self)]
6291    async fn test_window_activation(cx: &mut TestAppContext) {
6292        struct View(&'static str);
6293
6294        impl super::Entity for View {
6295            type Event = ();
6296        }
6297
6298        impl super::View for View {
6299            fn ui_name() -> &'static str {
6300                "test view"
6301            }
6302
6303            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6304                Empty::new().boxed()
6305            }
6306        }
6307
6308        let events = Rc::new(RefCell::new(Vec::new()));
6309        let (window_1, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6310            cx.observe_window_activation({
6311                let events = events.clone();
6312                move |this, active, _| events.borrow_mut().push((this.0, active))
6313            })
6314            .detach();
6315            View("window 1")
6316        });
6317        assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
6318
6319        let (window_2, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6320            cx.observe_window_activation({
6321                let events = events.clone();
6322                move |this, active, _| events.borrow_mut().push((this.0, active))
6323            })
6324            .detach();
6325            View("window 2")
6326        });
6327        assert_eq!(
6328            mem::take(&mut *events.borrow_mut()),
6329            [("window 1", false), ("window 2", true)]
6330        );
6331
6332        let (window_3, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6333            cx.observe_window_activation({
6334                let events = events.clone();
6335                move |this, active, _| events.borrow_mut().push((this.0, active))
6336            })
6337            .detach();
6338            View("window 3")
6339        });
6340        assert_eq!(
6341            mem::take(&mut *events.borrow_mut()),
6342            [("window 2", false), ("window 3", true)]
6343        );
6344
6345        cx.simulate_window_activation(Some(window_2));
6346        assert_eq!(
6347            mem::take(&mut *events.borrow_mut()),
6348            [("window 3", false), ("window 2", true)]
6349        );
6350
6351        cx.simulate_window_activation(Some(window_1));
6352        assert_eq!(
6353            mem::take(&mut *events.borrow_mut()),
6354            [("window 2", false), ("window 1", true)]
6355        );
6356
6357        cx.simulate_window_activation(Some(window_3));
6358        assert_eq!(
6359            mem::take(&mut *events.borrow_mut()),
6360            [("window 1", false), ("window 3", true)]
6361        );
6362
6363        cx.simulate_window_activation(Some(window_3));
6364        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6365    }
6366
6367    #[crate::test(self)]
6368    fn test_child_view(cx: &mut AppContext) {
6369        struct Child {
6370            rendered: Rc<Cell<bool>>,
6371            dropped: Rc<Cell<bool>>,
6372        }
6373
6374        impl super::Entity for Child {
6375            type Event = ();
6376        }
6377
6378        impl super::View for Child {
6379            fn ui_name() -> &'static str {
6380                "child view"
6381            }
6382
6383            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6384                self.rendered.set(true);
6385                Empty::new().boxed()
6386            }
6387        }
6388
6389        impl Drop for Child {
6390            fn drop(&mut self) {
6391                self.dropped.set(true);
6392            }
6393        }
6394
6395        struct Parent {
6396            child: Option<ViewHandle<Child>>,
6397        }
6398
6399        impl super::Entity for Parent {
6400            type Event = ();
6401        }
6402
6403        impl super::View for Parent {
6404            fn ui_name() -> &'static str {
6405                "parent view"
6406            }
6407
6408            fn render(&mut self, cx: &mut ViewContext<Self>) -> Element<Self> {
6409                if let Some(child) = self.child.as_ref() {
6410                    ChildView::new(child, cx).boxed()
6411                } else {
6412                    Empty::new().boxed()
6413                }
6414            }
6415        }
6416
6417        let child_rendered = Rc::new(Cell::new(false));
6418        let child_dropped = Rc::new(Cell::new(false));
6419        let (_, root_view) = cx.add_window(Default::default(), |cx| Parent {
6420            child: Some(cx.add_view(|_| Child {
6421                rendered: child_rendered.clone(),
6422                dropped: child_dropped.clone(),
6423            })),
6424        });
6425        assert!(child_rendered.take());
6426        assert!(!child_dropped.take());
6427
6428        root_view.update(cx, |view, cx| {
6429            view.child.take();
6430            cx.notify();
6431        });
6432        assert!(!child_rendered.take());
6433        assert!(child_dropped.take());
6434    }
6435
6436    #[derive(Default)]
6437    struct TestView {
6438        events: Vec<String>,
6439    }
6440
6441    impl Entity for TestView {
6442        type Event = String;
6443    }
6444
6445    impl View for TestView {
6446        fn ui_name() -> &'static str {
6447            "TestView"
6448        }
6449
6450        fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6451            Empty::new().boxed()
6452        }
6453    }
6454}