app.rs

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