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::SubscribeGlobal {
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::Subscribe {
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 id = post_inc(&mut self.next_subscription_id);
1180        let observed = handle.downgrade();
1181        self.observations
1182            .lock()
1183            .entry(handle.id())
1184            .or_default()
1185            .insert(
1186                id,
1187                Some(Box::new(move |cx| {
1188                    if let Some(observed) = H::upgrade_from(&observed, cx) {
1189                        callback(observed, cx)
1190                    } else {
1191                        false
1192                    }
1193                })),
1194            );
1195        Subscription::Observation {
1196            id,
1197            entity_id: handle.id(),
1198            observations: Some(Arc::downgrade(&self.observations)),
1199        }
1200    }
1201
1202    pub fn observe_release<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1203    where
1204        E: Entity,
1205        E::Event: 'static,
1206        H: Handle<E>,
1207        F: 'static + FnMut(&E, &mut Self),
1208    {
1209        let id = post_inc(&mut self.next_subscription_id);
1210        self.release_observations
1211            .lock()
1212            .entry(handle.id())
1213            .or_default()
1214            .insert(
1215                id,
1216                Box::new(move |released, cx| {
1217                    let released = released.downcast_ref().unwrap();
1218                    callback(released, cx)
1219                }),
1220            );
1221        Subscription::ReleaseObservation {
1222            id,
1223            entity_id: handle.id(),
1224            observations: Some(Arc::downgrade(&self.release_observations)),
1225        }
1226    }
1227
1228    fn defer(&mut self, callback: Box<dyn FnOnce(&mut MutableAppContext)>) {
1229        self.pending_effects.push_back(Effect::Deferred(callback))
1230    }
1231
1232    pub(crate) fn notify_model(&mut self, model_id: usize) {
1233        if self.pending_notifications.insert(model_id) {
1234            self.pending_effects
1235                .push_back(Effect::ModelNotification { model_id });
1236        }
1237    }
1238
1239    pub(crate) fn notify_view(&mut self, window_id: usize, view_id: usize) {
1240        if self.pending_notifications.insert(view_id) {
1241            self.pending_effects
1242                .push_back(Effect::ViewNotification { window_id, view_id });
1243        }
1244    }
1245
1246    pub fn dispatch_action<A: Action>(
1247        &mut self,
1248        window_id: usize,
1249        responder_chain: Vec<usize>,
1250        action: &A,
1251    ) {
1252        self.dispatch_action_any(window_id, &responder_chain, action);
1253    }
1254
1255    pub(crate) fn dispatch_action_any(
1256        &mut self,
1257        window_id: usize,
1258        path: &[usize],
1259        action: &dyn AnyAction,
1260    ) -> bool {
1261        self.update(|this| {
1262            this.halt_action_dispatch = false;
1263            for (capture_phase, view_id) in path
1264                .iter()
1265                .map(|view_id| (true, *view_id))
1266                .chain(path.iter().rev().map(|view_id| (false, *view_id)))
1267            {
1268                if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
1269                    let type_id = view.as_any().type_id();
1270
1271                    if let Some((name, mut handlers)) = this
1272                        .actions_mut(capture_phase)
1273                        .get_mut(&type_id)
1274                        .and_then(|h| h.remove_entry(&action.id()))
1275                    {
1276                        for handler in handlers.iter_mut().rev() {
1277                            this.halt_action_dispatch = true;
1278                            handler(view.as_mut(), action, this, window_id, view_id);
1279                            if this.halt_action_dispatch {
1280                                break;
1281                            }
1282                        }
1283                        this.actions_mut(capture_phase)
1284                            .get_mut(&type_id)
1285                            .unwrap()
1286                            .insert(name, handlers);
1287                    }
1288
1289                    this.cx.views.insert((window_id, view_id), view);
1290
1291                    if this.halt_action_dispatch {
1292                        break;
1293                    }
1294                }
1295            }
1296
1297            if !this.halt_action_dispatch {
1298                this.halt_action_dispatch = this.dispatch_global_action_any(action);
1299            }
1300            this.halt_action_dispatch
1301        })
1302    }
1303
1304    fn actions_mut(
1305        &mut self,
1306        capture_phase: bool,
1307    ) -> &mut HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>> {
1308        if capture_phase {
1309            &mut self.capture_actions
1310        } else {
1311            &mut self.actions
1312        }
1313    }
1314
1315    pub fn dispatch_global_action<A: Action>(&mut self, action: A) {
1316        self.dispatch_global_action_any(&action);
1317    }
1318
1319    fn dispatch_global_action_any(&mut self, action: &dyn AnyAction) -> bool {
1320        self.update(|this| {
1321            if let Some((name, mut handler)) = this.global_actions.remove_entry(&action.id()) {
1322                handler(action, this);
1323                this.global_actions.insert(name, handler);
1324                true
1325            } else {
1326                false
1327            }
1328        })
1329    }
1330
1331    pub fn add_bindings<T: IntoIterator<Item = keymap::Binding>>(&mut self, bindings: T) {
1332        self.keystroke_matcher.add_bindings(bindings);
1333    }
1334
1335    pub fn dispatch_keystroke(
1336        &mut self,
1337        window_id: usize,
1338        responder_chain: Vec<usize>,
1339        keystroke: &Keystroke,
1340    ) -> Result<bool> {
1341        let mut context_chain = Vec::new();
1342        for view_id in &responder_chain {
1343            if let Some(view) = self.cx.views.get(&(window_id, *view_id)) {
1344                context_chain.push(view.keymap_context(self.as_ref()));
1345            } else {
1346                return Err(anyhow!(
1347                    "View {} in responder chain does not exist",
1348                    view_id
1349                ));
1350            }
1351        }
1352
1353        let mut pending = false;
1354        for (i, cx) in context_chain.iter().enumerate().rev() {
1355            match self
1356                .keystroke_matcher
1357                .push_keystroke(keystroke.clone(), responder_chain[i], cx)
1358            {
1359                MatchResult::None => {}
1360                MatchResult::Pending => pending = true,
1361                MatchResult::Action(action) => {
1362                    if self.dispatch_action_any(window_id, &responder_chain[0..=i], action.as_ref())
1363                    {
1364                        self.keystroke_matcher.clear_pending();
1365                        return Ok(true);
1366                    }
1367                }
1368            }
1369        }
1370
1371        Ok(pending)
1372    }
1373
1374    pub fn default_global<T: 'static + Default>(&mut self) -> &T {
1375        self.cx
1376            .globals
1377            .entry(TypeId::of::<T>())
1378            .or_insert_with(|| Box::new(T::default()))
1379            .downcast_ref()
1380            .unwrap()
1381    }
1382
1383    pub fn set_global<T: 'static>(&mut self, state: T) {
1384        self.cx.globals.insert(TypeId::of::<T>(), Box::new(state));
1385    }
1386
1387    pub fn update_default_global<T, F, U>(&mut self, update: F) -> U
1388    where
1389        T: 'static + Default,
1390        F: FnOnce(&mut T, &mut MutableAppContext) -> U,
1391    {
1392        let type_id = TypeId::of::<T>();
1393        let mut state = self
1394            .cx
1395            .globals
1396            .remove(&type_id)
1397            .unwrap_or_else(|| Box::new(T::default()));
1398        let result = update(state.downcast_mut().unwrap(), self);
1399        self.cx.globals.insert(type_id, state);
1400        result
1401    }
1402
1403    pub fn update_global<T, F, U>(&mut self, update: F) -> U
1404    where
1405        T: 'static,
1406        F: FnOnce(&mut T, &mut MutableAppContext) -> U,
1407    {
1408        let type_id = TypeId::of::<T>();
1409        let mut state = self
1410            .cx
1411            .globals
1412            .remove(&type_id)
1413            .expect("no global has been added for this type");
1414        let result = update(state.downcast_mut().unwrap(), self);
1415        self.cx.globals.insert(type_id, state);
1416        result
1417    }
1418
1419    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
1420    where
1421        T: Entity,
1422        F: FnOnce(&mut ModelContext<T>) -> T,
1423    {
1424        self.update(|this| {
1425            let model_id = post_inc(&mut this.next_entity_id);
1426            let handle = ModelHandle::new(model_id, &this.cx.ref_counts);
1427            let mut cx = ModelContext::new(this, model_id);
1428            let model = build_model(&mut cx);
1429            this.cx.models.insert(model_id, Box::new(model));
1430            handle
1431        })
1432    }
1433
1434    pub fn add_window<T, F>(
1435        &mut self,
1436        window_options: WindowOptions,
1437        build_root_view: F,
1438    ) -> (usize, ViewHandle<T>)
1439    where
1440        T: View,
1441        F: FnOnce(&mut ViewContext<T>) -> T,
1442    {
1443        self.update(|this| {
1444            let window_id = post_inc(&mut this.next_window_id);
1445            let root_view = this.add_view(window_id, build_root_view);
1446
1447            this.cx.windows.insert(
1448                window_id,
1449                Window {
1450                    root_view: root_view.clone().into(),
1451                    focused_view_id: Some(root_view.id()),
1452                    invalidation: None,
1453                },
1454            );
1455            root_view.update(this, |view, cx| {
1456                view.on_focus(cx);
1457            });
1458            this.open_platform_window(window_id, window_options);
1459
1460            (window_id, root_view)
1461        })
1462    }
1463
1464    pub fn remove_window(&mut self, window_id: usize) {
1465        self.cx.windows.remove(&window_id);
1466        self.presenters_and_platform_windows.remove(&window_id);
1467        self.flush_effects();
1468    }
1469
1470    fn open_platform_window(&mut self, window_id: usize, window_options: WindowOptions) {
1471        let mut window =
1472            self.cx
1473                .platform
1474                .open_window(window_id, window_options, self.foreground.clone());
1475        let presenter = Rc::new(RefCell::new(
1476            self.build_presenter(window_id, window.titlebar_height()),
1477        ));
1478
1479        {
1480            let mut app = self.upgrade();
1481            let presenter = presenter.clone();
1482            window.on_event(Box::new(move |event| {
1483                app.update(|cx| {
1484                    if let Event::KeyDown { keystroke, .. } = &event {
1485                        if cx
1486                            .dispatch_keystroke(
1487                                window_id,
1488                                presenter.borrow().dispatch_path(cx.as_ref()),
1489                                keystroke,
1490                            )
1491                            .unwrap()
1492                        {
1493                            return;
1494                        }
1495                    }
1496
1497                    presenter.borrow_mut().dispatch_event(event, cx);
1498                })
1499            }));
1500        }
1501
1502        {
1503            let mut app = self.upgrade();
1504            window.on_resize(Box::new(move || {
1505                app.update(|cx| cx.resize_window(window_id))
1506            }));
1507        }
1508
1509        {
1510            let mut app = self.upgrade();
1511            window.on_close(Box::new(move || {
1512                app.update(|cx| cx.remove_window(window_id));
1513            }));
1514        }
1515
1516        let scene =
1517            presenter
1518                .borrow_mut()
1519                .build_scene(window.size(), window.scale_factor(), false, self);
1520        window.present_scene(scene);
1521        self.presenters_and_platform_windows
1522            .insert(window_id, (presenter.clone(), window));
1523    }
1524
1525    pub fn build_presenter(&mut self, window_id: usize, titlebar_height: f32) -> Presenter {
1526        Presenter::new(
1527            window_id,
1528            titlebar_height,
1529            self.cx.font_cache.clone(),
1530            TextLayoutCache::new(self.cx.platform.fonts()),
1531            self.assets.clone(),
1532            self,
1533        )
1534    }
1535
1536    pub fn build_render_context<V: View>(
1537        &mut self,
1538        window_id: usize,
1539        view_id: usize,
1540        titlebar_height: f32,
1541        refreshing: bool,
1542    ) -> RenderContext<V> {
1543        RenderContext {
1544            app: self,
1545            titlebar_height,
1546            refreshing,
1547            window_id,
1548            view_id,
1549            view_type: PhantomData,
1550        }
1551    }
1552
1553    pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
1554    where
1555        T: View,
1556        F: FnOnce(&mut ViewContext<T>) -> T,
1557    {
1558        self.add_option_view(window_id, |cx| Some(build_view(cx)))
1559            .unwrap()
1560    }
1561
1562    pub fn add_option_view<T, F>(
1563        &mut self,
1564        window_id: usize,
1565        build_view: F,
1566    ) -> Option<ViewHandle<T>>
1567    where
1568        T: View,
1569        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1570    {
1571        self.update(|this| {
1572            let view_id = post_inc(&mut this.next_entity_id);
1573            let mut cx = ViewContext::new(this, window_id, view_id);
1574            let handle = if let Some(view) = build_view(&mut cx) {
1575                this.cx.views.insert((window_id, view_id), Box::new(view));
1576                if let Some(window) = this.cx.windows.get_mut(&window_id) {
1577                    window
1578                        .invalidation
1579                        .get_or_insert_with(Default::default)
1580                        .updated
1581                        .insert(view_id);
1582                }
1583                Some(ViewHandle::new(window_id, view_id, &this.cx.ref_counts))
1584            } else {
1585                None
1586            };
1587            handle
1588        })
1589    }
1590
1591    fn remove_dropped_entities(&mut self) {
1592        loop {
1593            let (dropped_models, dropped_views, dropped_element_states) =
1594                self.cx.ref_counts.lock().take_dropped();
1595            if dropped_models.is_empty()
1596                && dropped_views.is_empty()
1597                && dropped_element_states.is_empty()
1598            {
1599                break;
1600            }
1601
1602            for model_id in dropped_models {
1603                self.subscriptions.lock().remove(&model_id);
1604                self.observations.lock().remove(&model_id);
1605                let mut model = self.cx.models.remove(&model_id).unwrap();
1606                model.release(self);
1607                self.pending_effects
1608                    .push_back(Effect::ModelRelease { model_id, model });
1609            }
1610
1611            for (window_id, view_id) in dropped_views {
1612                self.subscriptions.lock().remove(&view_id);
1613                self.observations.lock().remove(&view_id);
1614                let mut view = self.cx.views.remove(&(window_id, view_id)).unwrap();
1615                view.release(self);
1616                let change_focus_to = self.cx.windows.get_mut(&window_id).and_then(|window| {
1617                    window
1618                        .invalidation
1619                        .get_or_insert_with(Default::default)
1620                        .removed
1621                        .push(view_id);
1622                    if window.focused_view_id == Some(view_id) {
1623                        Some(window.root_view.id())
1624                    } else {
1625                        None
1626                    }
1627                });
1628
1629                if let Some(view_id) = change_focus_to {
1630                    self.focus(window_id, Some(view_id));
1631                }
1632
1633                self.pending_effects
1634                    .push_back(Effect::ViewRelease { view_id, view });
1635            }
1636
1637            for key in dropped_element_states {
1638                self.cx.element_states.remove(&key);
1639            }
1640        }
1641    }
1642
1643    fn flush_effects(&mut self) {
1644        self.pending_flushes = self.pending_flushes.saturating_sub(1);
1645
1646        if !self.flushing_effects && self.pending_flushes == 0 {
1647            self.flushing_effects = true;
1648
1649            let mut refreshing = false;
1650            loop {
1651                if let Some(effect) = self.pending_effects.pop_front() {
1652                    match effect {
1653                        Effect::Subscribe {
1654                            entity_id,
1655                            subscription_id,
1656                            callback,
1657                        } => self.handle_subscribe_effect(entity_id, subscription_id, callback),
1658                        Effect::Event { entity_id, payload } => self.emit_event(entity_id, payload),
1659                        Effect::SubscribeGlobal {
1660                            type_id,
1661                            subscription_id,
1662                            callback,
1663                        } => {
1664                            self.handle_subscribe_global_effect(type_id, subscription_id, callback)
1665                        }
1666                        Effect::GlobalEvent { payload } => self.emit_global_event(payload),
1667                        Effect::ModelNotification { model_id } => {
1668                            self.notify_model_observers(model_id)
1669                        }
1670                        Effect::ViewNotification { window_id, view_id } => {
1671                            self.notify_view_observers(window_id, view_id)
1672                        }
1673                        Effect::Deferred(callback) => callback(self),
1674                        Effect::ModelRelease { model_id, model } => {
1675                            self.notify_release_observers(model_id, model.as_any())
1676                        }
1677                        Effect::ViewRelease { view_id, view } => {
1678                            self.notify_release_observers(view_id, view.as_any())
1679                        }
1680                        Effect::Focus { window_id, view_id } => {
1681                            self.focus(window_id, view_id);
1682                        }
1683                        Effect::ResizeWindow { window_id } => {
1684                            if let Some(window) = self.cx.windows.get_mut(&window_id) {
1685                                window
1686                                    .invalidation
1687                                    .get_or_insert(WindowInvalidation::default());
1688                            }
1689                        }
1690                        Effect::RefreshWindows => {
1691                            refreshing = true;
1692                        }
1693                    }
1694                    self.pending_notifications.clear();
1695                    self.remove_dropped_entities();
1696                } else {
1697                    self.remove_dropped_entities();
1698                    if refreshing {
1699                        self.perform_window_refresh();
1700                    } else {
1701                        self.update_windows();
1702                    }
1703
1704                    if self.pending_effects.is_empty() {
1705                        self.flushing_effects = false;
1706                        self.pending_notifications.clear();
1707                        break;
1708                    } else {
1709                        refreshing = false;
1710                    }
1711                }
1712            }
1713        }
1714    }
1715
1716    fn update_windows(&mut self) {
1717        let mut invalidations = HashMap::new();
1718        for (window_id, window) in &mut self.cx.windows {
1719            if let Some(invalidation) = window.invalidation.take() {
1720                invalidations.insert(*window_id, invalidation);
1721            }
1722        }
1723
1724        for (window_id, mut invalidation) in invalidations {
1725            if let Some((presenter, mut window)) =
1726                self.presenters_and_platform_windows.remove(&window_id)
1727            {
1728                {
1729                    let mut presenter = presenter.borrow_mut();
1730                    presenter.invalidate(&mut invalidation, self);
1731                    let scene =
1732                        presenter.build_scene(window.size(), window.scale_factor(), false, self);
1733                    window.present_scene(scene);
1734                }
1735                self.presenters_and_platform_windows
1736                    .insert(window_id, (presenter, window));
1737            }
1738        }
1739    }
1740
1741    fn resize_window(&mut self, window_id: usize) {
1742        self.pending_effects
1743            .push_back(Effect::ResizeWindow { window_id });
1744    }
1745
1746    pub fn refresh_windows(&mut self) {
1747        self.pending_effects.push_back(Effect::RefreshWindows);
1748    }
1749
1750    fn perform_window_refresh(&mut self) {
1751        let mut presenters = mem::take(&mut self.presenters_and_platform_windows);
1752        for (window_id, (presenter, window)) in &mut presenters {
1753            let mut invalidation = self
1754                .cx
1755                .windows
1756                .get_mut(&window_id)
1757                .unwrap()
1758                .invalidation
1759                .take();
1760            let mut presenter = presenter.borrow_mut();
1761            presenter.refresh(
1762                invalidation.as_mut().unwrap_or(&mut Default::default()),
1763                self,
1764            );
1765            let scene = presenter.build_scene(window.size(), window.scale_factor(), true, self);
1766            window.present_scene(scene);
1767        }
1768        self.presenters_and_platform_windows = presenters;
1769    }
1770
1771    pub fn set_cursor_style(&mut self, style: CursorStyle) -> CursorStyleHandle {
1772        self.platform.set_cursor_style(style);
1773        let id = self.next_cursor_style_handle_id.fetch_add(1, SeqCst);
1774        CursorStyleHandle {
1775            id,
1776            next_cursor_style_handle_id: self.next_cursor_style_handle_id.clone(),
1777            platform: self.platform(),
1778        }
1779    }
1780
1781    fn handle_subscribe_effect(
1782        &mut self,
1783        entity_id: usize,
1784        subscription_id: usize,
1785        callback: SubscriptionCallback,
1786    ) {
1787        match self
1788            .subscriptions
1789            .lock()
1790            .entry(entity_id)
1791            .or_default()
1792            .entry(subscription_id)
1793        {
1794            btree_map::Entry::Vacant(entry) => {
1795                entry.insert(Some(callback));
1796            }
1797            // Subscription was dropped before effect was processed
1798            btree_map::Entry::Occupied(entry) => {
1799                debug_assert!(entry.get().is_none());
1800                entry.remove();
1801            }
1802        }
1803    }
1804
1805    fn emit_event(&mut self, entity_id: usize, payload: Box<dyn Any>) {
1806        let callbacks = self.subscriptions.lock().remove(&entity_id);
1807        if let Some(callbacks) = callbacks {
1808            for (id, callback) in callbacks {
1809                if let Some(mut callback) = callback {
1810                    let alive = callback(payload.as_ref(), self);
1811                    if alive {
1812                        match self
1813                            .subscriptions
1814                            .lock()
1815                            .entry(entity_id)
1816                            .or_default()
1817                            .entry(id)
1818                        {
1819                            btree_map::Entry::Vacant(entry) => {
1820                                entry.insert(Some(callback));
1821                            }
1822                            btree_map::Entry::Occupied(entry) => {
1823                                entry.remove();
1824                            }
1825                        }
1826                    }
1827                }
1828            }
1829        }
1830    }
1831
1832    fn handle_subscribe_global_effect(
1833        &mut self,
1834        type_id: TypeId,
1835        subscription_id: usize,
1836        callback: GlobalSubscriptionCallback,
1837    ) {
1838        match self
1839            .global_subscriptions
1840            .lock()
1841            .entry(type_id)
1842            .or_default()
1843            .entry(subscription_id)
1844        {
1845            btree_map::Entry::Vacant(entry) => {
1846                entry.insert(Some(callback));
1847            }
1848            // Subscription was dropped before effect was processed
1849            btree_map::Entry::Occupied(entry) => {
1850                debug_assert!(entry.get().is_none());
1851                entry.remove();
1852            }
1853        }
1854    }
1855
1856    fn emit_global_event(&mut self, payload: Box<dyn Any>) {
1857        let type_id = (&*payload).type_id();
1858        let callbacks = self.global_subscriptions.lock().remove(&type_id);
1859        if let Some(callbacks) = callbacks {
1860            for (id, callback) in callbacks {
1861                if let Some(mut callback) = callback {
1862                    callback(payload.as_ref(), self);
1863                    match self
1864                        .global_subscriptions
1865                        .lock()
1866                        .entry(type_id)
1867                        .or_default()
1868                        .entry(id)
1869                    {
1870                        btree_map::Entry::Vacant(entry) => {
1871                            entry.insert(Some(callback));
1872                        }
1873                        btree_map::Entry::Occupied(entry) => {
1874                            entry.remove();
1875                        }
1876                    }
1877                }
1878            }
1879        }
1880    }
1881
1882    fn notify_model_observers(&mut self, observed_id: usize) {
1883        let callbacks = self.observations.lock().remove(&observed_id);
1884        if let Some(callbacks) = callbacks {
1885            if self.cx.models.contains_key(&observed_id) {
1886                for (id, callback) in callbacks {
1887                    if let Some(mut callback) = callback {
1888                        let alive = callback(self);
1889                        if alive {
1890                            match self
1891                                .observations
1892                                .lock()
1893                                .entry(observed_id)
1894                                .or_default()
1895                                .entry(id)
1896                            {
1897                                btree_map::Entry::Vacant(entry) => {
1898                                    entry.insert(Some(callback));
1899                                }
1900                                btree_map::Entry::Occupied(entry) => {
1901                                    entry.remove();
1902                                }
1903                            }
1904                        }
1905                    }
1906                }
1907            }
1908        }
1909    }
1910
1911    fn notify_view_observers(&mut self, observed_window_id: usize, observed_view_id: usize) {
1912        if let Some(window) = self.cx.windows.get_mut(&observed_window_id) {
1913            window
1914                .invalidation
1915                .get_or_insert_with(Default::default)
1916                .updated
1917                .insert(observed_view_id);
1918        }
1919
1920        let callbacks = self.observations.lock().remove(&observed_view_id);
1921        if let Some(callbacks) = callbacks {
1922            if self
1923                .cx
1924                .views
1925                .contains_key(&(observed_window_id, observed_view_id))
1926            {
1927                for (id, callback) in callbacks {
1928                    if let Some(mut callback) = callback {
1929                        let alive = callback(self);
1930                        if alive {
1931                            match self
1932                                .observations
1933                                .lock()
1934                                .entry(observed_view_id)
1935                                .or_default()
1936                                .entry(id)
1937                            {
1938                                btree_map::Entry::Vacant(entry) => {
1939                                    entry.insert(Some(callback));
1940                                }
1941                                btree_map::Entry::Occupied(entry) => {
1942                                    entry.remove();
1943                                }
1944                            }
1945                        }
1946                    }
1947                }
1948            }
1949        }
1950    }
1951
1952    fn notify_release_observers(&mut self, entity_id: usize, entity: &dyn Any) {
1953        let callbacks = self.release_observations.lock().remove(&entity_id);
1954        if let Some(callbacks) = callbacks {
1955            for (_, mut callback) in callbacks {
1956                callback(entity, self);
1957            }
1958        }
1959    }
1960
1961    fn focus(&mut self, window_id: usize, focused_id: Option<usize>) {
1962        if self
1963            .cx
1964            .windows
1965            .get(&window_id)
1966            .map(|w| w.focused_view_id)
1967            .map_or(false, |cur_focused| cur_focused == focused_id)
1968        {
1969            return;
1970        }
1971
1972        self.update(|this| {
1973            let blurred_id = this.cx.windows.get_mut(&window_id).and_then(|window| {
1974                let blurred_id = window.focused_view_id;
1975                window.focused_view_id = focused_id;
1976                blurred_id
1977            });
1978
1979            if let Some(blurred_id) = blurred_id {
1980                if let Some(mut blurred_view) = this.cx.views.remove(&(window_id, blurred_id)) {
1981                    blurred_view.on_blur(this, window_id, blurred_id);
1982                    this.cx.views.insert((window_id, blurred_id), blurred_view);
1983                }
1984            }
1985
1986            if let Some(focused_id) = focused_id {
1987                if let Some(mut focused_view) = this.cx.views.remove(&(window_id, focused_id)) {
1988                    focused_view.on_focus(this, window_id, focused_id);
1989                    this.cx.views.insert((window_id, focused_id), focused_view);
1990                }
1991            }
1992        })
1993    }
1994
1995    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
1996    where
1997        F: FnOnce(AsyncAppContext) -> Fut,
1998        Fut: 'static + Future<Output = T>,
1999        T: 'static,
2000    {
2001        let future = f(self.to_async());
2002        let cx = self.to_async();
2003        self.foreground.spawn(async move {
2004            let result = future.await;
2005            cx.0.borrow_mut().flush_effects();
2006            result
2007        })
2008    }
2009
2010    pub fn to_async(&self) -> AsyncAppContext {
2011        AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
2012    }
2013
2014    pub fn write_to_clipboard(&self, item: ClipboardItem) {
2015        self.cx.platform.write_to_clipboard(item);
2016    }
2017
2018    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
2019        self.cx.platform.read_from_clipboard()
2020    }
2021
2022    #[cfg(any(test, feature = "test-support"))]
2023    pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
2024        self.cx.ref_counts.lock().leak_detector.clone()
2025    }
2026}
2027
2028impl ReadModel for MutableAppContext {
2029    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2030        if let Some(model) = self.cx.models.get(&handle.model_id) {
2031            model
2032                .as_any()
2033                .downcast_ref()
2034                .expect("downcast is type safe")
2035        } else {
2036            panic!("circular model reference");
2037        }
2038    }
2039}
2040
2041impl UpdateModel for MutableAppContext {
2042    fn update_model<T: Entity, V>(
2043        &mut self,
2044        handle: &ModelHandle<T>,
2045        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
2046    ) -> V {
2047        if let Some(mut model) = self.cx.models.remove(&handle.model_id) {
2048            self.update(|this| {
2049                let mut cx = ModelContext::new(this, handle.model_id);
2050                let result = update(
2051                    model
2052                        .as_any_mut()
2053                        .downcast_mut()
2054                        .expect("downcast is type safe"),
2055                    &mut cx,
2056                );
2057                this.cx.models.insert(handle.model_id, model);
2058                result
2059            })
2060        } else {
2061            panic!("circular model update");
2062        }
2063    }
2064}
2065
2066impl UpgradeModelHandle for MutableAppContext {
2067    fn upgrade_model_handle<T: Entity>(
2068        &self,
2069        handle: &WeakModelHandle<T>,
2070    ) -> Option<ModelHandle<T>> {
2071        self.cx.upgrade_model_handle(handle)
2072    }
2073
2074    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2075        self.cx.model_handle_is_upgradable(handle)
2076    }
2077
2078    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2079        self.cx.upgrade_any_model_handle(handle)
2080    }
2081}
2082
2083impl UpgradeViewHandle for MutableAppContext {
2084    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2085        self.cx.upgrade_view_handle(handle)
2086    }
2087
2088    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
2089        self.cx.upgrade_any_view_handle(handle)
2090    }
2091}
2092
2093impl ReadView for MutableAppContext {
2094    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2095        if let Some(view) = self.cx.views.get(&(handle.window_id, handle.view_id)) {
2096            view.as_any().downcast_ref().expect("downcast is type safe")
2097        } else {
2098            panic!("circular view reference");
2099        }
2100    }
2101}
2102
2103impl UpdateView for MutableAppContext {
2104    fn update_view<T, S>(
2105        &mut self,
2106        handle: &ViewHandle<T>,
2107        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
2108    ) -> S
2109    where
2110        T: View,
2111    {
2112        self.update(|this| {
2113            let mut view = this
2114                .cx
2115                .views
2116                .remove(&(handle.window_id, handle.view_id))
2117                .expect("circular view update");
2118
2119            let mut cx = ViewContext::new(this, handle.window_id, handle.view_id);
2120            let result = update(
2121                view.as_any_mut()
2122                    .downcast_mut()
2123                    .expect("downcast is type safe"),
2124                &mut cx,
2125            );
2126            this.cx
2127                .views
2128                .insert((handle.window_id, handle.view_id), view);
2129            result
2130        })
2131    }
2132}
2133
2134impl AsRef<AppContext> for MutableAppContext {
2135    fn as_ref(&self) -> &AppContext {
2136        &self.cx
2137    }
2138}
2139
2140impl Deref for MutableAppContext {
2141    type Target = AppContext;
2142
2143    fn deref(&self) -> &Self::Target {
2144        &self.cx
2145    }
2146}
2147
2148pub struct AppContext {
2149    models: HashMap<usize, Box<dyn AnyModel>>,
2150    views: HashMap<(usize, usize), Box<dyn AnyView>>,
2151    windows: HashMap<usize, Window>,
2152    globals: HashMap<TypeId, Box<dyn Any>>,
2153    element_states: HashMap<ElementStateId, Box<dyn Any>>,
2154    background: Arc<executor::Background>,
2155    ref_counts: Arc<Mutex<RefCounts>>,
2156    font_cache: Arc<FontCache>,
2157    platform: Arc<dyn Platform>,
2158}
2159
2160impl AppContext {
2161    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
2162        self.windows
2163            .get(&window_id)
2164            .map(|window| window.root_view.id())
2165    }
2166
2167    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
2168        self.windows
2169            .get(&window_id)
2170            .and_then(|window| window.focused_view_id)
2171    }
2172
2173    pub fn background(&self) -> &Arc<executor::Background> {
2174        &self.background
2175    }
2176
2177    pub fn font_cache(&self) -> &Arc<FontCache> {
2178        &self.font_cache
2179    }
2180
2181    pub fn platform(&self) -> &Arc<dyn Platform> {
2182        &self.platform
2183    }
2184
2185    pub fn has_global<T: 'static>(&self) -> bool {
2186        self.globals.contains_key(&TypeId::of::<T>())
2187    }
2188
2189    pub fn global<T: 'static>(&self) -> &T {
2190        self.globals
2191            .get(&TypeId::of::<T>())
2192            .expect("no app state has been added for this type")
2193            .downcast_ref()
2194            .unwrap()
2195    }
2196}
2197
2198impl ReadModel for AppContext {
2199    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2200        if let Some(model) = self.models.get(&handle.model_id) {
2201            model
2202                .as_any()
2203                .downcast_ref()
2204                .expect("downcast should be type safe")
2205        } else {
2206            panic!("circular model reference");
2207        }
2208    }
2209}
2210
2211impl UpgradeModelHandle for AppContext {
2212    fn upgrade_model_handle<T: Entity>(
2213        &self,
2214        handle: &WeakModelHandle<T>,
2215    ) -> Option<ModelHandle<T>> {
2216        if self.models.contains_key(&handle.model_id) {
2217            Some(ModelHandle::new(handle.model_id, &self.ref_counts))
2218        } else {
2219            None
2220        }
2221    }
2222
2223    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2224        self.models.contains_key(&handle.model_id)
2225    }
2226
2227    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2228        if self.models.contains_key(&handle.model_id) {
2229            Some(AnyModelHandle::new(
2230                handle.model_id,
2231                handle.model_type,
2232                self.ref_counts.clone(),
2233            ))
2234        } else {
2235            None
2236        }
2237    }
2238}
2239
2240impl UpgradeViewHandle for AppContext {
2241    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2242        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2243            Some(ViewHandle::new(
2244                handle.window_id,
2245                handle.view_id,
2246                &self.ref_counts,
2247            ))
2248        } else {
2249            None
2250        }
2251    }
2252
2253    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
2254        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2255            Some(AnyViewHandle::new(
2256                handle.window_id,
2257                handle.view_id,
2258                handle.view_type,
2259                self.ref_counts.clone(),
2260            ))
2261        } else {
2262            None
2263        }
2264    }
2265}
2266
2267impl ReadView for AppContext {
2268    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2269        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
2270            view.as_any()
2271                .downcast_ref()
2272                .expect("downcast should be type safe")
2273        } else {
2274            panic!("circular view reference");
2275        }
2276    }
2277}
2278
2279struct Window {
2280    root_view: AnyViewHandle,
2281    focused_view_id: Option<usize>,
2282    invalidation: Option<WindowInvalidation>,
2283}
2284
2285#[derive(Default, Clone)]
2286pub struct WindowInvalidation {
2287    pub updated: HashSet<usize>,
2288    pub removed: Vec<usize>,
2289}
2290
2291pub enum Effect {
2292    Subscribe {
2293        entity_id: usize,
2294        subscription_id: usize,
2295        callback: SubscriptionCallback,
2296    },
2297    Event {
2298        entity_id: usize,
2299        payload: Box<dyn Any>,
2300    },
2301    SubscribeGlobal {
2302        type_id: TypeId,
2303        subscription_id: usize,
2304        callback: GlobalSubscriptionCallback,
2305    },
2306    GlobalEvent {
2307        payload: Box<dyn Any>,
2308    },
2309    ModelNotification {
2310        model_id: usize,
2311    },
2312    ViewNotification {
2313        window_id: usize,
2314        view_id: usize,
2315    },
2316    Deferred(Box<dyn FnOnce(&mut MutableAppContext)>),
2317    ModelRelease {
2318        model_id: usize,
2319        model: Box<dyn AnyModel>,
2320    },
2321    ViewRelease {
2322        view_id: usize,
2323        view: Box<dyn AnyView>,
2324    },
2325    Focus {
2326        window_id: usize,
2327        view_id: Option<usize>,
2328    },
2329    ResizeWindow {
2330        window_id: usize,
2331    },
2332    RefreshWindows,
2333}
2334
2335impl Debug for Effect {
2336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2337        match self {
2338            Effect::Subscribe {
2339                entity_id,
2340                subscription_id,
2341                ..
2342            } => f
2343                .debug_struct("Effect::Subscribe")
2344                .field("entity_id", entity_id)
2345                .field("subscription_id", subscription_id)
2346                .finish(),
2347            Effect::Event { entity_id, .. } => f
2348                .debug_struct("Effect::Event")
2349                .field("entity_id", entity_id)
2350                .finish(),
2351            Effect::SubscribeGlobal {
2352                type_id,
2353                subscription_id,
2354                ..
2355            } => f
2356                .debug_struct("Effect::Subscribe")
2357                .field("type_id", type_id)
2358                .field("subscription_id", subscription_id)
2359                .finish(),
2360            Effect::GlobalEvent { payload, .. } => f
2361                .debug_struct("Effect::GlobalEvent")
2362                .field("type_id", &(&*payload).type_id())
2363                .finish(),
2364            Effect::ModelNotification { model_id } => f
2365                .debug_struct("Effect::ModelNotification")
2366                .field("model_id", model_id)
2367                .finish(),
2368            Effect::ViewNotification { window_id, view_id } => f
2369                .debug_struct("Effect::ViewNotification")
2370                .field("window_id", window_id)
2371                .field("view_id", view_id)
2372                .finish(),
2373            Effect::Deferred(_) => f.debug_struct("Effect::Deferred").finish(),
2374            Effect::ModelRelease { model_id, .. } => f
2375                .debug_struct("Effect::ModelRelease")
2376                .field("model_id", model_id)
2377                .finish(),
2378            Effect::ViewRelease { view_id, .. } => f
2379                .debug_struct("Effect::ViewRelease")
2380                .field("view_id", view_id)
2381                .finish(),
2382            Effect::Focus { window_id, view_id } => f
2383                .debug_struct("Effect::Focus")
2384                .field("window_id", window_id)
2385                .field("view_id", view_id)
2386                .finish(),
2387            Effect::ResizeWindow { window_id } => f
2388                .debug_struct("Effect::RefreshWindow")
2389                .field("window_id", window_id)
2390                .finish(),
2391            Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
2392        }
2393    }
2394}
2395
2396pub trait AnyModel {
2397    fn as_any(&self) -> &dyn Any;
2398    fn as_any_mut(&mut self) -> &mut dyn Any;
2399    fn release(&mut self, cx: &mut MutableAppContext);
2400    fn app_will_quit(
2401        &mut self,
2402        cx: &mut MutableAppContext,
2403    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2404}
2405
2406impl<T> AnyModel for T
2407where
2408    T: Entity,
2409{
2410    fn as_any(&self) -> &dyn Any {
2411        self
2412    }
2413
2414    fn as_any_mut(&mut self) -> &mut dyn Any {
2415        self
2416    }
2417
2418    fn release(&mut self, cx: &mut MutableAppContext) {
2419        self.release(cx);
2420    }
2421
2422    fn app_will_quit(
2423        &mut self,
2424        cx: &mut MutableAppContext,
2425    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2426        self.app_will_quit(cx)
2427    }
2428}
2429
2430pub trait AnyView {
2431    fn as_any(&self) -> &dyn Any;
2432    fn as_any_mut(&mut self) -> &mut dyn Any;
2433    fn release(&mut self, cx: &mut MutableAppContext);
2434    fn app_will_quit(
2435        &mut self,
2436        cx: &mut MutableAppContext,
2437    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2438    fn ui_name(&self) -> &'static str;
2439    fn render<'a>(
2440        &mut self,
2441        window_id: usize,
2442        view_id: usize,
2443        titlebar_height: f32,
2444        refreshing: bool,
2445        cx: &mut MutableAppContext,
2446    ) -> ElementBox;
2447    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
2448    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
2449    fn keymap_context(&self, cx: &AppContext) -> keymap::Context;
2450}
2451
2452impl<T> AnyView for T
2453where
2454    T: View,
2455{
2456    fn as_any(&self) -> &dyn Any {
2457        self
2458    }
2459
2460    fn as_any_mut(&mut self) -> &mut dyn Any {
2461        self
2462    }
2463
2464    fn release(&mut self, cx: &mut MutableAppContext) {
2465        self.release(cx);
2466    }
2467
2468    fn app_will_quit(
2469        &mut self,
2470        cx: &mut MutableAppContext,
2471    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2472        self.app_will_quit(cx)
2473    }
2474
2475    fn ui_name(&self) -> &'static str {
2476        T::ui_name()
2477    }
2478
2479    fn render<'a>(
2480        &mut self,
2481        window_id: usize,
2482        view_id: usize,
2483        titlebar_height: f32,
2484        refreshing: bool,
2485        cx: &mut MutableAppContext,
2486    ) -> ElementBox {
2487        View::render(
2488            self,
2489            &mut RenderContext {
2490                window_id,
2491                view_id,
2492                app: cx,
2493                view_type: PhantomData::<T>,
2494                titlebar_height,
2495                refreshing,
2496            },
2497        )
2498    }
2499
2500    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
2501        let mut cx = ViewContext::new(cx, window_id, view_id);
2502        View::on_focus(self, &mut cx);
2503    }
2504
2505    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
2506        let mut cx = ViewContext::new(cx, window_id, view_id);
2507        View::on_blur(self, &mut cx);
2508    }
2509
2510    fn keymap_context(&self, cx: &AppContext) -> keymap::Context {
2511        View::keymap_context(self, cx)
2512    }
2513}
2514
2515pub struct ModelContext<'a, T: ?Sized> {
2516    app: &'a mut MutableAppContext,
2517    model_id: usize,
2518    model_type: PhantomData<T>,
2519    halt_stream: bool,
2520}
2521
2522impl<'a, T: Entity> ModelContext<'a, T> {
2523    fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
2524        Self {
2525            app,
2526            model_id,
2527            model_type: PhantomData,
2528            halt_stream: false,
2529        }
2530    }
2531
2532    pub fn background(&self) -> &Arc<executor::Background> {
2533        &self.app.cx.background
2534    }
2535
2536    pub fn halt_stream(&mut self) {
2537        self.halt_stream = true;
2538    }
2539
2540    pub fn model_id(&self) -> usize {
2541        self.model_id
2542    }
2543
2544    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2545    where
2546        S: Entity,
2547        F: FnOnce(&mut ModelContext<S>) -> S,
2548    {
2549        self.app.add_model(build_model)
2550    }
2551
2552    pub fn emit(&mut self, payload: T::Event) {
2553        self.app.pending_effects.push_back(Effect::Event {
2554            entity_id: self.model_id,
2555            payload: Box::new(payload),
2556        });
2557    }
2558
2559    pub fn notify(&mut self) {
2560        self.app.notify_model(self.model_id);
2561    }
2562
2563    pub fn subscribe<S: Entity, F>(
2564        &mut self,
2565        handle: &ModelHandle<S>,
2566        mut callback: F,
2567    ) -> Subscription
2568    where
2569        S::Event: 'static,
2570        F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
2571    {
2572        let subscriber = self.weak_handle();
2573        self.app
2574            .subscribe_internal(handle, move |emitter, event, cx| {
2575                if let Some(subscriber) = subscriber.upgrade(cx) {
2576                    subscriber.update(cx, |subscriber, cx| {
2577                        callback(subscriber, emitter, event, cx);
2578                    });
2579                    true
2580                } else {
2581                    false
2582                }
2583            })
2584    }
2585
2586    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
2587    where
2588        S: Entity,
2589        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
2590    {
2591        let observer = self.weak_handle();
2592        self.app.observe_internal(handle, move |observed, cx| {
2593            if let Some(observer) = observer.upgrade(cx) {
2594                observer.update(cx, |observer, cx| {
2595                    callback(observer, observed, cx);
2596                });
2597                true
2598            } else {
2599                false
2600            }
2601        })
2602    }
2603
2604    pub fn observe_release<S, F>(
2605        &mut self,
2606        handle: &ModelHandle<S>,
2607        mut callback: F,
2608    ) -> Subscription
2609    where
2610        S: Entity,
2611        F: 'static + FnMut(&mut T, &S, &mut ModelContext<T>),
2612    {
2613        let observer = self.weak_handle();
2614        self.app.observe_release(handle, move |released, cx| {
2615            if let Some(observer) = observer.upgrade(cx) {
2616                observer.update(cx, |observer, cx| {
2617                    callback(observer, released, cx);
2618                });
2619            }
2620        })
2621    }
2622
2623    pub fn handle(&self) -> ModelHandle<T> {
2624        ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
2625    }
2626
2627    pub fn weak_handle(&self) -> WeakModelHandle<T> {
2628        WeakModelHandle::new(self.model_id)
2629    }
2630
2631    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2632    where
2633        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
2634        Fut: 'static + Future<Output = S>,
2635        S: 'static,
2636    {
2637        let handle = self.handle();
2638        self.app.spawn(|cx| f(handle, cx))
2639    }
2640
2641    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
2642    where
2643        F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
2644        Fut: 'static + Future<Output = S>,
2645        S: 'static,
2646    {
2647        let handle = self.weak_handle();
2648        self.app.spawn(|cx| f(handle, cx))
2649    }
2650}
2651
2652impl<M> AsRef<AppContext> for ModelContext<'_, M> {
2653    fn as_ref(&self) -> &AppContext {
2654        &self.app.cx
2655    }
2656}
2657
2658impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
2659    fn as_mut(&mut self) -> &mut MutableAppContext {
2660        self.app
2661    }
2662}
2663
2664impl<M> ReadModel for ModelContext<'_, M> {
2665    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2666        self.app.read_model(handle)
2667    }
2668}
2669
2670impl<M> UpdateModel for ModelContext<'_, M> {
2671    fn update_model<T: Entity, V>(
2672        &mut self,
2673        handle: &ModelHandle<T>,
2674        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
2675    ) -> V {
2676        self.app.update_model(handle, update)
2677    }
2678}
2679
2680impl<M> UpgradeModelHandle for ModelContext<'_, M> {
2681    fn upgrade_model_handle<T: Entity>(
2682        &self,
2683        handle: &WeakModelHandle<T>,
2684    ) -> Option<ModelHandle<T>> {
2685        self.cx.upgrade_model_handle(handle)
2686    }
2687
2688    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2689        self.cx.model_handle_is_upgradable(handle)
2690    }
2691
2692    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2693        self.cx.upgrade_any_model_handle(handle)
2694    }
2695}
2696
2697impl<M> Deref for ModelContext<'_, M> {
2698    type Target = MutableAppContext;
2699
2700    fn deref(&self) -> &Self::Target {
2701        &self.app
2702    }
2703}
2704
2705impl<M> DerefMut for ModelContext<'_, M> {
2706    fn deref_mut(&mut self) -> &mut Self::Target {
2707        &mut self.app
2708    }
2709}
2710
2711pub struct ViewContext<'a, T: ?Sized> {
2712    app: &'a mut MutableAppContext,
2713    window_id: usize,
2714    view_id: usize,
2715    view_type: PhantomData<T>,
2716}
2717
2718impl<'a, T: View> ViewContext<'a, T> {
2719    fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
2720        Self {
2721            app,
2722            window_id,
2723            view_id,
2724            view_type: PhantomData,
2725        }
2726    }
2727
2728    pub fn handle(&self) -> ViewHandle<T> {
2729        ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
2730    }
2731
2732    pub fn weak_handle(&self) -> WeakViewHandle<T> {
2733        WeakViewHandle::new(self.window_id, self.view_id)
2734    }
2735
2736    pub fn window_id(&self) -> usize {
2737        self.window_id
2738    }
2739
2740    pub fn view_id(&self) -> usize {
2741        self.view_id
2742    }
2743
2744    pub fn foreground(&self) -> &Rc<executor::Foreground> {
2745        self.app.foreground()
2746    }
2747
2748    pub fn background_executor(&self) -> &Arc<executor::Background> {
2749        &self.app.cx.background
2750    }
2751
2752    pub fn platform(&self) -> Arc<dyn Platform> {
2753        self.app.platform()
2754    }
2755
2756    pub fn prompt(
2757        &self,
2758        level: PromptLevel,
2759        msg: &str,
2760        answers: &[&str],
2761    ) -> oneshot::Receiver<usize> {
2762        self.app.prompt(self.window_id, level, msg, answers)
2763    }
2764
2765    pub fn prompt_for_paths(
2766        &self,
2767        options: PathPromptOptions,
2768    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2769        self.app.prompt_for_paths(options)
2770    }
2771
2772    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
2773        self.app.prompt_for_new_path(directory)
2774    }
2775
2776    pub fn debug_elements(&self) -> crate::json::Value {
2777        self.app.debug_elements(self.window_id).unwrap()
2778    }
2779
2780    pub fn focus<S>(&mut self, handle: S)
2781    where
2782        S: Into<AnyViewHandle>,
2783    {
2784        let handle = handle.into();
2785        self.app.pending_effects.push_back(Effect::Focus {
2786            window_id: handle.window_id,
2787            view_id: Some(handle.view_id),
2788        });
2789    }
2790
2791    pub fn focus_self(&mut self) {
2792        self.app.pending_effects.push_back(Effect::Focus {
2793            window_id: self.window_id,
2794            view_id: Some(self.view_id),
2795        });
2796    }
2797
2798    pub fn blur(&mut self) {
2799        self.app.pending_effects.push_back(Effect::Focus {
2800            window_id: self.window_id,
2801            view_id: None,
2802        });
2803    }
2804
2805    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2806    where
2807        S: Entity,
2808        F: FnOnce(&mut ModelContext<S>) -> S,
2809    {
2810        self.app.add_model(build_model)
2811    }
2812
2813    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
2814    where
2815        S: View,
2816        F: FnOnce(&mut ViewContext<S>) -> S,
2817    {
2818        self.app.add_view(self.window_id, build_view)
2819    }
2820
2821    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
2822    where
2823        S: View,
2824        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
2825    {
2826        self.app.add_option_view(self.window_id, build_view)
2827    }
2828
2829    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
2830    where
2831        E: Entity,
2832        E::Event: 'static,
2833        H: Handle<E>,
2834        F: 'static + FnMut(&mut T, H, &E::Event, &mut ViewContext<T>),
2835    {
2836        let subscriber = self.weak_handle();
2837        self.app
2838            .subscribe_internal(handle, move |emitter, event, cx| {
2839                if let Some(subscriber) = subscriber.upgrade(cx) {
2840                    subscriber.update(cx, |subscriber, cx| {
2841                        callback(subscriber, emitter, event, cx);
2842                    });
2843                    true
2844                } else {
2845                    false
2846                }
2847            })
2848    }
2849
2850    pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2851    where
2852        E: Entity,
2853        H: Handle<E>,
2854        F: 'static + FnMut(&mut T, H, &mut ViewContext<T>),
2855    {
2856        let observer = self.weak_handle();
2857        self.app.observe_internal(handle, move |observed, cx| {
2858            if let Some(observer) = observer.upgrade(cx) {
2859                observer.update(cx, |observer, cx| {
2860                    callback(observer, observed, cx);
2861                });
2862                true
2863            } else {
2864                false
2865            }
2866        })
2867    }
2868
2869    pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2870    where
2871        E: Entity,
2872        H: Handle<E>,
2873        F: 'static + FnMut(&mut T, &E, &mut ViewContext<T>),
2874    {
2875        let observer = self.weak_handle();
2876        self.app.observe_release(handle, move |released, cx| {
2877            if let Some(observer) = observer.upgrade(cx) {
2878                observer.update(cx, |observer, cx| {
2879                    callback(observer, released, cx);
2880                });
2881            }
2882        })
2883    }
2884
2885    pub fn emit(&mut self, payload: T::Event) {
2886        self.app.pending_effects.push_back(Effect::Event {
2887            entity_id: self.view_id,
2888            payload: Box::new(payload),
2889        });
2890    }
2891
2892    pub fn notify(&mut self) {
2893        self.app.notify_view(self.window_id, self.view_id);
2894    }
2895
2896    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>)) {
2897        let handle = self.handle();
2898        self.app.defer(Box::new(move |cx| {
2899            handle.update(cx, |view, cx| {
2900                callback(view, cx);
2901            })
2902        }))
2903    }
2904
2905    pub fn propagate_action(&mut self) {
2906        self.app.halt_action_dispatch = false;
2907    }
2908
2909    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2910    where
2911        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
2912        Fut: 'static + Future<Output = S>,
2913        S: 'static,
2914    {
2915        let handle = self.handle();
2916        self.app.spawn(|cx| f(handle, cx))
2917    }
2918
2919    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
2920    where
2921        F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut,
2922        Fut: 'static + Future<Output = S>,
2923        S: 'static,
2924    {
2925        let handle = self.weak_handle();
2926        self.app.spawn(|cx| f(handle, cx))
2927    }
2928}
2929
2930pub struct RenderContext<'a, T: View> {
2931    pub app: &'a mut MutableAppContext,
2932    pub titlebar_height: f32,
2933    pub refreshing: bool,
2934    window_id: usize,
2935    view_id: usize,
2936    view_type: PhantomData<T>,
2937}
2938
2939impl<'a, T: View> RenderContext<'a, T> {
2940    pub fn handle(&self) -> WeakViewHandle<T> {
2941        WeakViewHandle::new(self.window_id, self.view_id)
2942    }
2943
2944    pub fn view_id(&self) -> usize {
2945        self.view_id
2946    }
2947}
2948
2949impl AsRef<AppContext> for &AppContext {
2950    fn as_ref(&self) -> &AppContext {
2951        self
2952    }
2953}
2954
2955impl<V: View> Deref for RenderContext<'_, V> {
2956    type Target = MutableAppContext;
2957
2958    fn deref(&self) -> &Self::Target {
2959        self.app
2960    }
2961}
2962
2963impl<V: View> DerefMut for RenderContext<'_, V> {
2964    fn deref_mut(&mut self) -> &mut Self::Target {
2965        self.app
2966    }
2967}
2968
2969impl<V: View> ReadModel for RenderContext<'_, V> {
2970    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2971        self.app.read_model(handle)
2972    }
2973}
2974
2975impl<V: View> UpdateModel for RenderContext<'_, V> {
2976    fn update_model<T: Entity, O>(
2977        &mut self,
2978        handle: &ModelHandle<T>,
2979        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
2980    ) -> O {
2981        self.app.update_model(handle, update)
2982    }
2983}
2984
2985impl<V: View> ReadView for RenderContext<'_, V> {
2986    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2987        self.app.read_view(handle)
2988    }
2989}
2990
2991impl<V: View> ElementStateContext for RenderContext<'_, V> {
2992    fn current_view_id(&self) -> usize {
2993        self.view_id
2994    }
2995}
2996
2997impl<M> AsRef<AppContext> for ViewContext<'_, M> {
2998    fn as_ref(&self) -> &AppContext {
2999        &self.app.cx
3000    }
3001}
3002
3003impl<M> Deref for ViewContext<'_, M> {
3004    type Target = MutableAppContext;
3005
3006    fn deref(&self) -> &Self::Target {
3007        &self.app
3008    }
3009}
3010
3011impl<M> DerefMut for ViewContext<'_, M> {
3012    fn deref_mut(&mut self) -> &mut Self::Target {
3013        &mut self.app
3014    }
3015}
3016
3017impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
3018    fn as_mut(&mut self) -> &mut MutableAppContext {
3019        self.app
3020    }
3021}
3022
3023impl<V> ReadModel for ViewContext<'_, V> {
3024    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
3025        self.app.read_model(handle)
3026    }
3027}
3028
3029impl<V> UpgradeModelHandle for ViewContext<'_, V> {
3030    fn upgrade_model_handle<T: Entity>(
3031        &self,
3032        handle: &WeakModelHandle<T>,
3033    ) -> Option<ModelHandle<T>> {
3034        self.cx.upgrade_model_handle(handle)
3035    }
3036
3037    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
3038        self.cx.model_handle_is_upgradable(handle)
3039    }
3040
3041    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
3042        self.cx.upgrade_any_model_handle(handle)
3043    }
3044}
3045
3046impl<V> UpgradeViewHandle for ViewContext<'_, V> {
3047    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
3048        self.cx.upgrade_view_handle(handle)
3049    }
3050
3051    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
3052        self.cx.upgrade_any_view_handle(handle)
3053    }
3054}
3055
3056impl<V: View> UpdateModel for ViewContext<'_, V> {
3057    fn update_model<T: Entity, O>(
3058        &mut self,
3059        handle: &ModelHandle<T>,
3060        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
3061    ) -> O {
3062        self.app.update_model(handle, update)
3063    }
3064}
3065
3066impl<V: View> ReadView for ViewContext<'_, V> {
3067    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
3068        self.app.read_view(handle)
3069    }
3070}
3071
3072impl<V: View> UpdateView for ViewContext<'_, V> {
3073    fn update_view<T, S>(
3074        &mut self,
3075        handle: &ViewHandle<T>,
3076        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
3077    ) -> S
3078    where
3079        T: View,
3080    {
3081        self.app.update_view(handle, update)
3082    }
3083}
3084
3085impl<V: View> ElementStateContext for ViewContext<'_, V> {
3086    fn current_view_id(&self) -> usize {
3087        self.view_id
3088    }
3089}
3090
3091pub trait Handle<T> {
3092    type Weak: 'static;
3093    fn id(&self) -> usize;
3094    fn location(&self) -> EntityLocation;
3095    fn downgrade(&self) -> Self::Weak;
3096    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3097    where
3098        Self: Sized;
3099}
3100
3101#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
3102pub enum EntityLocation {
3103    Model(usize),
3104    View(usize, usize),
3105}
3106
3107pub struct ModelHandle<T: Entity> {
3108    model_id: usize,
3109    model_type: PhantomData<T>,
3110    ref_counts: Arc<Mutex<RefCounts>>,
3111
3112    #[cfg(any(test, feature = "test-support"))]
3113    handle_id: usize,
3114}
3115
3116impl<T: Entity> ModelHandle<T> {
3117    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3118        ref_counts.lock().inc_model(model_id);
3119
3120        #[cfg(any(test, feature = "test-support"))]
3121        let handle_id = ref_counts
3122            .lock()
3123            .leak_detector
3124            .lock()
3125            .handle_created(Some(type_name::<T>()), model_id);
3126
3127        Self {
3128            model_id,
3129            model_type: PhantomData,
3130            ref_counts: ref_counts.clone(),
3131
3132            #[cfg(any(test, feature = "test-support"))]
3133            handle_id,
3134        }
3135    }
3136
3137    pub fn downgrade(&self) -> WeakModelHandle<T> {
3138        WeakModelHandle::new(self.model_id)
3139    }
3140
3141    pub fn id(&self) -> usize {
3142        self.model_id
3143    }
3144
3145    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
3146        cx.read_model(self)
3147    }
3148
3149    pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
3150    where
3151        C: ReadModelWith,
3152        F: FnOnce(&T, &AppContext) -> S,
3153    {
3154        let mut read = Some(read);
3155        cx.read_model_with(self, &mut |model, cx| {
3156            let read = read.take().unwrap();
3157            read(model, cx)
3158        })
3159    }
3160
3161    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3162    where
3163        C: UpdateModel,
3164        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
3165    {
3166        let mut update = Some(update);
3167        cx.update_model(self, &mut |model, cx| {
3168            let update = update.take().unwrap();
3169            update(model, cx)
3170        })
3171    }
3172
3173    #[cfg(any(test, feature = "test-support"))]
3174    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
3175        use postage::prelude::{Sink as _, Stream as _};
3176
3177        let (mut tx, mut rx) = postage::mpsc::channel(1);
3178        let mut cx = cx.cx.borrow_mut();
3179        let subscription = cx.observe(self, move |_, _| {
3180            tx.try_send(()).ok();
3181        });
3182
3183        let duration = if std::env::var("CI").is_ok() {
3184            Duration::from_secs(5)
3185        } else {
3186            Duration::from_secs(1)
3187        };
3188
3189        async move {
3190            let notification = crate::util::timeout(duration, rx.recv())
3191                .await
3192                .expect("next notification timed out");
3193            drop(subscription);
3194            notification.expect("model dropped while test was waiting for its next notification")
3195        }
3196    }
3197
3198    #[cfg(any(test, feature = "test-support"))]
3199    pub fn next_event(&self, cx: &TestAppContext) -> impl Future<Output = T::Event>
3200    where
3201        T::Event: Clone,
3202    {
3203        use postage::prelude::{Sink as _, Stream as _};
3204
3205        let (mut tx, mut rx) = postage::mpsc::channel(1);
3206        let mut cx = cx.cx.borrow_mut();
3207        let subscription = cx.subscribe(self, move |_, event, _| {
3208            tx.blocking_send(event.clone()).ok();
3209        });
3210
3211        let duration = if std::env::var("CI").is_ok() {
3212            Duration::from_secs(5)
3213        } else {
3214            Duration::from_secs(1)
3215        };
3216
3217        async move {
3218            let event = crate::util::timeout(duration, rx.recv())
3219                .await
3220                .expect("next event timed out");
3221            drop(subscription);
3222            event.expect("model dropped while test was waiting for its next event")
3223        }
3224    }
3225
3226    #[cfg(any(test, feature = "test-support"))]
3227    pub fn condition(
3228        &self,
3229        cx: &TestAppContext,
3230        mut predicate: impl FnMut(&T, &AppContext) -> bool,
3231    ) -> impl Future<Output = ()> {
3232        use postage::prelude::{Sink as _, Stream as _};
3233
3234        let (tx, mut rx) = postage::mpsc::channel(1024);
3235
3236        let mut cx = cx.cx.borrow_mut();
3237        let subscriptions = (
3238            cx.observe(self, {
3239                let mut tx = tx.clone();
3240                move |_, _| {
3241                    tx.blocking_send(()).ok();
3242                }
3243            }),
3244            cx.subscribe(self, {
3245                let mut tx = tx.clone();
3246                move |_, _, _| {
3247                    tx.blocking_send(()).ok();
3248                }
3249            }),
3250        );
3251
3252        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
3253        let handle = self.downgrade();
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            crate::util::timeout(duration, async move {
3262                loop {
3263                    {
3264                        let cx = cx.borrow();
3265                        let cx = cx.as_ref();
3266                        if predicate(
3267                            handle
3268                                .upgrade(cx)
3269                                .expect("model dropped with pending condition")
3270                                .read(cx),
3271                            cx,
3272                        ) {
3273                            break;
3274                        }
3275                    }
3276
3277                    cx.borrow().foreground().start_waiting();
3278                    rx.recv()
3279                        .await
3280                        .expect("model dropped with pending condition");
3281                    cx.borrow().foreground().finish_waiting();
3282                }
3283            })
3284            .await
3285            .expect("condition timed out");
3286            drop(subscriptions);
3287        }
3288    }
3289}
3290
3291impl<T: Entity> Clone for ModelHandle<T> {
3292    fn clone(&self) -> Self {
3293        Self::new(self.model_id, &self.ref_counts)
3294    }
3295}
3296
3297impl<T: Entity> PartialEq for ModelHandle<T> {
3298    fn eq(&self, other: &Self) -> bool {
3299        self.model_id == other.model_id
3300    }
3301}
3302
3303impl<T: Entity> Eq for ModelHandle<T> {}
3304
3305impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
3306    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
3307        self.model_id == other.model_id
3308    }
3309}
3310
3311impl<T: Entity> Hash for ModelHandle<T> {
3312    fn hash<H: Hasher>(&self, state: &mut H) {
3313        self.model_id.hash(state);
3314    }
3315}
3316
3317impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
3318    fn borrow(&self) -> &usize {
3319        &self.model_id
3320    }
3321}
3322
3323impl<T: Entity> Debug for ModelHandle<T> {
3324    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3325        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
3326            .field(&self.model_id)
3327            .finish()
3328    }
3329}
3330
3331unsafe impl<T: Entity> Send for ModelHandle<T> {}
3332unsafe impl<T: Entity> Sync for ModelHandle<T> {}
3333
3334impl<T: Entity> Drop for ModelHandle<T> {
3335    fn drop(&mut self) {
3336        let mut ref_counts = self.ref_counts.lock();
3337        ref_counts.dec_model(self.model_id);
3338
3339        #[cfg(any(test, feature = "test-support"))]
3340        ref_counts
3341            .leak_detector
3342            .lock()
3343            .handle_dropped(self.model_id, self.handle_id);
3344    }
3345}
3346
3347impl<T: Entity> Handle<T> for ModelHandle<T> {
3348    type Weak = WeakModelHandle<T>;
3349
3350    fn id(&self) -> usize {
3351        self.model_id
3352    }
3353
3354    fn location(&self) -> EntityLocation {
3355        EntityLocation::Model(self.model_id)
3356    }
3357
3358    fn downgrade(&self) -> Self::Weak {
3359        self.downgrade()
3360    }
3361
3362    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3363    where
3364        Self: Sized,
3365    {
3366        weak.upgrade(cx)
3367    }
3368}
3369
3370pub struct WeakModelHandle<T> {
3371    model_id: usize,
3372    model_type: PhantomData<T>,
3373}
3374
3375unsafe impl<T> Send for WeakModelHandle<T> {}
3376unsafe impl<T> Sync for WeakModelHandle<T> {}
3377
3378impl<T: Entity> WeakModelHandle<T> {
3379    fn new(model_id: usize) -> Self {
3380        Self {
3381            model_id,
3382            model_type: PhantomData,
3383        }
3384    }
3385
3386    pub fn id(&self) -> usize {
3387        self.model_id
3388    }
3389
3390    pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
3391        cx.model_handle_is_upgradable(self)
3392    }
3393
3394    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
3395        cx.upgrade_model_handle(self)
3396    }
3397}
3398
3399impl<T> Hash for WeakModelHandle<T> {
3400    fn hash<H: Hasher>(&self, state: &mut H) {
3401        self.model_id.hash(state)
3402    }
3403}
3404
3405impl<T> PartialEq for WeakModelHandle<T> {
3406    fn eq(&self, other: &Self) -> bool {
3407        self.model_id == other.model_id
3408    }
3409}
3410
3411impl<T> Eq for WeakModelHandle<T> {}
3412
3413impl<T> Clone for WeakModelHandle<T> {
3414    fn clone(&self) -> Self {
3415        Self {
3416            model_id: self.model_id,
3417            model_type: PhantomData,
3418        }
3419    }
3420}
3421
3422impl<T> Copy for WeakModelHandle<T> {}
3423
3424pub struct ViewHandle<T> {
3425    window_id: usize,
3426    view_id: usize,
3427    view_type: PhantomData<T>,
3428    ref_counts: Arc<Mutex<RefCounts>>,
3429    #[cfg(any(test, feature = "test-support"))]
3430    handle_id: usize,
3431}
3432
3433impl<T: View> ViewHandle<T> {
3434    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3435        ref_counts.lock().inc_view(window_id, view_id);
3436        #[cfg(any(test, feature = "test-support"))]
3437        let handle_id = ref_counts
3438            .lock()
3439            .leak_detector
3440            .lock()
3441            .handle_created(Some(type_name::<T>()), view_id);
3442
3443        Self {
3444            window_id,
3445            view_id,
3446            view_type: PhantomData,
3447            ref_counts: ref_counts.clone(),
3448
3449            #[cfg(any(test, feature = "test-support"))]
3450            handle_id,
3451        }
3452    }
3453
3454    pub fn downgrade(&self) -> WeakViewHandle<T> {
3455        WeakViewHandle::new(self.window_id, self.view_id)
3456    }
3457
3458    pub fn window_id(&self) -> usize {
3459        self.window_id
3460    }
3461
3462    pub fn id(&self) -> usize {
3463        self.view_id
3464    }
3465
3466    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
3467        cx.read_view(self)
3468    }
3469
3470    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3471    where
3472        C: ReadViewWith,
3473        F: FnOnce(&T, &AppContext) -> S,
3474    {
3475        let mut read = Some(read);
3476        cx.read_view_with(self, &mut |view, cx| {
3477            let read = read.take().unwrap();
3478            read(view, cx)
3479        })
3480    }
3481
3482    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3483    where
3484        C: UpdateView,
3485        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
3486    {
3487        let mut update = Some(update);
3488        cx.update_view(self, &mut |view, cx| {
3489            let update = update.take().unwrap();
3490            update(view, cx)
3491        })
3492    }
3493
3494    pub fn defer<C, F>(&self, cx: &mut C, update: F)
3495    where
3496        C: AsMut<MutableAppContext>,
3497        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
3498    {
3499        let this = self.clone();
3500        cx.as_mut().defer(Box::new(move |cx| {
3501            this.update(cx, |view, cx| update(view, cx));
3502        }));
3503    }
3504
3505    pub fn is_focused(&self, cx: &AppContext) -> bool {
3506        cx.focused_view_id(self.window_id)
3507            .map_or(false, |focused_id| focused_id == self.view_id)
3508    }
3509
3510    #[cfg(any(test, feature = "test-support"))]
3511    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
3512        use postage::prelude::{Sink as _, Stream as _};
3513
3514        let (mut tx, mut rx) = postage::mpsc::channel(1);
3515        let mut cx = cx.cx.borrow_mut();
3516        let subscription = cx.observe(self, move |_, _| {
3517            tx.try_send(()).ok();
3518        });
3519
3520        let duration = if std::env::var("CI").is_ok() {
3521            Duration::from_secs(5)
3522        } else {
3523            Duration::from_secs(1)
3524        };
3525
3526        async move {
3527            let notification = crate::util::timeout(duration, rx.recv())
3528                .await
3529                .expect("next notification timed out");
3530            drop(subscription);
3531            notification.expect("model dropped while test was waiting for its next notification")
3532        }
3533    }
3534
3535    #[cfg(any(test, feature = "test-support"))]
3536    pub fn condition(
3537        &self,
3538        cx: &TestAppContext,
3539        mut predicate: impl FnMut(&T, &AppContext) -> bool,
3540    ) -> impl Future<Output = ()> {
3541        use postage::prelude::{Sink as _, Stream as _};
3542
3543        let (tx, mut rx) = postage::mpsc::channel(1024);
3544
3545        let mut cx = cx.cx.borrow_mut();
3546        let subscriptions = self.update(&mut *cx, |_, cx| {
3547            (
3548                cx.observe(self, {
3549                    let mut tx = tx.clone();
3550                    move |_, _, _| {
3551                        tx.blocking_send(()).ok();
3552                    }
3553                }),
3554                cx.subscribe(self, {
3555                    let mut tx = tx.clone();
3556                    move |_, _, _, _| {
3557                        tx.blocking_send(()).ok();
3558                    }
3559                }),
3560            )
3561        });
3562
3563        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
3564        let handle = self.downgrade();
3565        let duration = if std::env::var("CI").is_ok() {
3566            Duration::from_secs(2)
3567        } else {
3568            Duration::from_millis(500)
3569        };
3570
3571        async move {
3572            crate::util::timeout(duration, async move {
3573                loop {
3574                    {
3575                        let cx = cx.borrow();
3576                        let cx = cx.as_ref();
3577                        if predicate(
3578                            handle
3579                                .upgrade(cx)
3580                                .expect("view dropped with pending condition")
3581                                .read(cx),
3582                            cx,
3583                        ) {
3584                            break;
3585                        }
3586                    }
3587
3588                    cx.borrow().foreground().start_waiting();
3589                    rx.recv()
3590                        .await
3591                        .expect("view dropped with pending condition");
3592                    cx.borrow().foreground().finish_waiting();
3593                }
3594            })
3595            .await
3596            .expect("condition timed out");
3597            drop(subscriptions);
3598        }
3599    }
3600}
3601
3602impl<T: View> Clone for ViewHandle<T> {
3603    fn clone(&self) -> Self {
3604        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
3605    }
3606}
3607
3608impl<T> PartialEq for ViewHandle<T> {
3609    fn eq(&self, other: &Self) -> bool {
3610        self.window_id == other.window_id && self.view_id == other.view_id
3611    }
3612}
3613
3614impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
3615    fn eq(&self, other: &WeakViewHandle<T>) -> bool {
3616        self.window_id == other.window_id && self.view_id == other.view_id
3617    }
3618}
3619
3620impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
3621    fn eq(&self, other: &ViewHandle<T>) -> bool {
3622        self.window_id == other.window_id && self.view_id == other.view_id
3623    }
3624}
3625
3626impl<T> Eq for ViewHandle<T> {}
3627
3628impl<T> Hash for ViewHandle<T> {
3629    fn hash<H: Hasher>(&self, state: &mut H) {
3630        self.window_id.hash(state);
3631        self.view_id.hash(state);
3632    }
3633}
3634
3635impl<T> Debug for ViewHandle<T> {
3636    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3637        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
3638            .field("window_id", &self.window_id)
3639            .field("view_id", &self.view_id)
3640            .finish()
3641    }
3642}
3643
3644impl<T> Drop for ViewHandle<T> {
3645    fn drop(&mut self) {
3646        self.ref_counts
3647            .lock()
3648            .dec_view(self.window_id, self.view_id);
3649        #[cfg(any(test, feature = "test-support"))]
3650        self.ref_counts
3651            .lock()
3652            .leak_detector
3653            .lock()
3654            .handle_dropped(self.view_id, self.handle_id);
3655    }
3656}
3657
3658impl<T: View> Handle<T> for ViewHandle<T> {
3659    type Weak = WeakViewHandle<T>;
3660
3661    fn id(&self) -> usize {
3662        self.view_id
3663    }
3664
3665    fn location(&self) -> EntityLocation {
3666        EntityLocation::View(self.window_id, self.view_id)
3667    }
3668
3669    fn downgrade(&self) -> Self::Weak {
3670        self.downgrade()
3671    }
3672
3673    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3674    where
3675        Self: Sized,
3676    {
3677        weak.upgrade(cx)
3678    }
3679}
3680
3681pub struct AnyViewHandle {
3682    window_id: usize,
3683    view_id: usize,
3684    view_type: TypeId,
3685    ref_counts: Arc<Mutex<RefCounts>>,
3686
3687    #[cfg(any(test, feature = "test-support"))]
3688    handle_id: usize,
3689}
3690
3691impl AnyViewHandle {
3692    fn new(
3693        window_id: usize,
3694        view_id: usize,
3695        view_type: TypeId,
3696        ref_counts: Arc<Mutex<RefCounts>>,
3697    ) -> Self {
3698        ref_counts.lock().inc_view(window_id, view_id);
3699
3700        #[cfg(any(test, feature = "test-support"))]
3701        let handle_id = ref_counts
3702            .lock()
3703            .leak_detector
3704            .lock()
3705            .handle_created(None, view_id);
3706
3707        Self {
3708            window_id,
3709            view_id,
3710            view_type,
3711            ref_counts,
3712            #[cfg(any(test, feature = "test-support"))]
3713            handle_id,
3714        }
3715    }
3716
3717    pub fn id(&self) -> usize {
3718        self.view_id
3719    }
3720
3721    pub fn is<T: 'static>(&self) -> bool {
3722        TypeId::of::<T>() == self.view_type
3723    }
3724
3725    pub fn is_focused(&self, cx: &AppContext) -> bool {
3726        cx.focused_view_id(self.window_id)
3727            .map_or(false, |focused_id| focused_id == self.view_id)
3728    }
3729
3730    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
3731        if self.is::<T>() {
3732            let result = Some(ViewHandle {
3733                window_id: self.window_id,
3734                view_id: self.view_id,
3735                ref_counts: self.ref_counts.clone(),
3736                view_type: PhantomData,
3737                #[cfg(any(test, feature = "test-support"))]
3738                handle_id: self.handle_id,
3739            });
3740            unsafe {
3741                Arc::decrement_strong_count(&self.ref_counts);
3742            }
3743            std::mem::forget(self);
3744            result
3745        } else {
3746            None
3747        }
3748    }
3749
3750    pub fn downgrade(&self) -> AnyWeakViewHandle {
3751        AnyWeakViewHandle {
3752            window_id: self.window_id,
3753            view_id: self.view_id,
3754            view_type: self.view_type,
3755        }
3756    }
3757
3758    pub fn view_type(&self) -> TypeId {
3759        self.view_type
3760    }
3761}
3762
3763impl Clone for AnyViewHandle {
3764    fn clone(&self) -> Self {
3765        Self::new(
3766            self.window_id,
3767            self.view_id,
3768            self.view_type,
3769            self.ref_counts.clone(),
3770        )
3771    }
3772}
3773
3774impl From<&AnyViewHandle> for AnyViewHandle {
3775    fn from(handle: &AnyViewHandle) -> Self {
3776        handle.clone()
3777    }
3778}
3779
3780impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
3781    fn from(handle: &ViewHandle<T>) -> Self {
3782        Self::new(
3783            handle.window_id,
3784            handle.view_id,
3785            TypeId::of::<T>(),
3786            handle.ref_counts.clone(),
3787        )
3788    }
3789}
3790
3791impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
3792    fn from(handle: ViewHandle<T>) -> Self {
3793        let any_handle = AnyViewHandle {
3794            window_id: handle.window_id,
3795            view_id: handle.view_id,
3796            view_type: TypeId::of::<T>(),
3797            ref_counts: handle.ref_counts.clone(),
3798            #[cfg(any(test, feature = "test-support"))]
3799            handle_id: handle.handle_id,
3800        };
3801        unsafe {
3802            Arc::decrement_strong_count(&handle.ref_counts);
3803        }
3804        std::mem::forget(handle);
3805        any_handle
3806    }
3807}
3808
3809impl Drop for AnyViewHandle {
3810    fn drop(&mut self) {
3811        self.ref_counts
3812            .lock()
3813            .dec_view(self.window_id, self.view_id);
3814        #[cfg(any(test, feature = "test-support"))]
3815        self.ref_counts
3816            .lock()
3817            .leak_detector
3818            .lock()
3819            .handle_dropped(self.view_id, self.handle_id);
3820    }
3821}
3822
3823pub struct AnyModelHandle {
3824    model_id: usize,
3825    model_type: TypeId,
3826    ref_counts: Arc<Mutex<RefCounts>>,
3827
3828    #[cfg(any(test, feature = "test-support"))]
3829    handle_id: usize,
3830}
3831
3832impl AnyModelHandle {
3833    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
3834        ref_counts.lock().inc_model(model_id);
3835
3836        #[cfg(any(test, feature = "test-support"))]
3837        let handle_id = ref_counts
3838            .lock()
3839            .leak_detector
3840            .lock()
3841            .handle_created(None, model_id);
3842
3843        Self {
3844            model_id,
3845            model_type,
3846            ref_counts,
3847
3848            #[cfg(any(test, feature = "test-support"))]
3849            handle_id,
3850        }
3851    }
3852
3853    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
3854        if self.is::<T>() {
3855            let result = Some(ModelHandle {
3856                model_id: self.model_id,
3857                model_type: PhantomData,
3858                ref_counts: self.ref_counts.clone(),
3859
3860                #[cfg(any(test, feature = "test-support"))]
3861                handle_id: self.handle_id,
3862            });
3863            unsafe {
3864                Arc::decrement_strong_count(&self.ref_counts);
3865            }
3866            std::mem::forget(self);
3867            result
3868        } else {
3869            None
3870        }
3871    }
3872
3873    pub fn downgrade(&self) -> AnyWeakModelHandle {
3874        AnyWeakModelHandle {
3875            model_id: self.model_id,
3876            model_type: self.model_type,
3877        }
3878    }
3879
3880    pub fn is<T: Entity>(&self) -> bool {
3881        self.model_type == TypeId::of::<T>()
3882    }
3883
3884    pub fn model_type(&self) -> TypeId {
3885        self.model_type
3886    }
3887}
3888
3889impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
3890    fn from(handle: ModelHandle<T>) -> Self {
3891        Self::new(
3892            handle.model_id,
3893            TypeId::of::<T>(),
3894            handle.ref_counts.clone(),
3895        )
3896    }
3897}
3898
3899impl Clone for AnyModelHandle {
3900    fn clone(&self) -> Self {
3901        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
3902    }
3903}
3904
3905impl Drop for AnyModelHandle {
3906    fn drop(&mut self) {
3907        let mut ref_counts = self.ref_counts.lock();
3908        ref_counts.dec_model(self.model_id);
3909
3910        #[cfg(any(test, feature = "test-support"))]
3911        ref_counts
3912            .leak_detector
3913            .lock()
3914            .handle_dropped(self.model_id, self.handle_id);
3915    }
3916}
3917
3918pub struct AnyWeakModelHandle {
3919    model_id: usize,
3920    model_type: TypeId,
3921}
3922
3923impl AnyWeakModelHandle {
3924    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
3925        cx.upgrade_any_model_handle(self)
3926    }
3927}
3928
3929impl<T: Entity> From<WeakModelHandle<T>> for AnyWeakModelHandle {
3930    fn from(handle: WeakModelHandle<T>) -> Self {
3931        AnyWeakModelHandle {
3932            model_id: handle.model_id,
3933            model_type: TypeId::of::<T>(),
3934        }
3935    }
3936}
3937
3938pub struct WeakViewHandle<T> {
3939    window_id: usize,
3940    view_id: usize,
3941    view_type: PhantomData<T>,
3942}
3943
3944impl<T: View> WeakViewHandle<T> {
3945    fn new(window_id: usize, view_id: usize) -> Self {
3946        Self {
3947            window_id,
3948            view_id,
3949            view_type: PhantomData,
3950        }
3951    }
3952
3953    pub fn id(&self) -> usize {
3954        self.view_id
3955    }
3956
3957    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
3958        cx.upgrade_view_handle(self)
3959    }
3960}
3961
3962impl<T> Clone for WeakViewHandle<T> {
3963    fn clone(&self) -> Self {
3964        Self {
3965            window_id: self.window_id,
3966            view_id: self.view_id,
3967            view_type: PhantomData,
3968        }
3969    }
3970}
3971
3972impl<T> PartialEq for WeakViewHandle<T> {
3973    fn eq(&self, other: &Self) -> bool {
3974        self.window_id == other.window_id && self.view_id == other.view_id
3975    }
3976}
3977
3978impl<T> Eq for WeakViewHandle<T> {}
3979
3980impl<T> Hash for WeakViewHandle<T> {
3981    fn hash<H: Hasher>(&self, state: &mut H) {
3982        self.window_id.hash(state);
3983        self.view_id.hash(state);
3984    }
3985}
3986
3987pub struct AnyWeakViewHandle {
3988    window_id: usize,
3989    view_id: usize,
3990    view_type: TypeId,
3991}
3992
3993impl AnyWeakViewHandle {
3994    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<AnyViewHandle> {
3995        cx.upgrade_any_view_handle(self)
3996    }
3997}
3998
3999impl<T: View> From<WeakViewHandle<T>> for AnyWeakViewHandle {
4000    fn from(handle: WeakViewHandle<T>) -> Self {
4001        AnyWeakViewHandle {
4002            window_id: handle.window_id,
4003            view_id: handle.view_id,
4004            view_type: TypeId::of::<T>(),
4005        }
4006    }
4007}
4008
4009#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4010pub struct ElementStateId {
4011    view_id: usize,
4012    element_id: usize,
4013    tag: TypeId,
4014}
4015
4016pub struct ElementStateHandle<T> {
4017    value_type: PhantomData<T>,
4018    id: ElementStateId,
4019    ref_counts: Weak<Mutex<RefCounts>>,
4020}
4021
4022impl<T: 'static> ElementStateHandle<T> {
4023    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4024        ref_counts.lock().inc_element_state(id, frame_id);
4025        Self {
4026            value_type: PhantomData,
4027            id,
4028            ref_counts: Arc::downgrade(ref_counts),
4029        }
4030    }
4031
4032    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
4033        cx.element_states
4034            .get(&self.id)
4035            .unwrap()
4036            .downcast_ref()
4037            .unwrap()
4038    }
4039
4040    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
4041    where
4042        C: DerefMut<Target = MutableAppContext>,
4043    {
4044        let mut element_state = cx.deref_mut().cx.element_states.remove(&self.id).unwrap();
4045        let result = f(element_state.downcast_mut().unwrap(), cx);
4046        cx.deref_mut()
4047            .cx
4048            .element_states
4049            .insert(self.id, element_state);
4050        result
4051    }
4052}
4053
4054impl<T> Drop for ElementStateHandle<T> {
4055    fn drop(&mut self) {
4056        if let Some(ref_counts) = self.ref_counts.upgrade() {
4057            ref_counts.lock().dec_element_state(self.id);
4058        }
4059    }
4060}
4061
4062pub struct CursorStyleHandle {
4063    id: usize,
4064    next_cursor_style_handle_id: Arc<AtomicUsize>,
4065    platform: Arc<dyn Platform>,
4066}
4067
4068impl Drop for CursorStyleHandle {
4069    fn drop(&mut self) {
4070        if self.id + 1 == self.next_cursor_style_handle_id.load(SeqCst) {
4071            self.platform.set_cursor_style(CursorStyle::Arrow);
4072        }
4073    }
4074}
4075
4076#[must_use]
4077pub enum Subscription {
4078    Subscription {
4079        id: usize,
4080        entity_id: usize,
4081        subscriptions:
4082            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, Option<SubscriptionCallback>>>>>>,
4083    },
4084    GlobalSubscription {
4085        id: usize,
4086        type_id: TypeId,
4087        subscriptions: Option<
4088            Weak<Mutex<HashMap<TypeId, BTreeMap<usize, Option<GlobalSubscriptionCallback>>>>>,
4089        >,
4090    },
4091    Observation {
4092        id: usize,
4093        entity_id: usize,
4094        observations:
4095            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, Option<ObservationCallback>>>>>>,
4096    },
4097    ReleaseObservation {
4098        id: usize,
4099        entity_id: usize,
4100        observations:
4101            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>>,
4102    },
4103}
4104
4105impl Subscription {
4106    pub fn detach(&mut self) {
4107        match self {
4108            Subscription::Subscription { subscriptions, .. } => {
4109                subscriptions.take();
4110            }
4111            Subscription::GlobalSubscription { subscriptions, .. } => {
4112                subscriptions.take();
4113            }
4114            Subscription::Observation { observations, .. } => {
4115                observations.take();
4116            }
4117            Subscription::ReleaseObservation { observations, .. } => {
4118                observations.take();
4119            }
4120        }
4121    }
4122}
4123
4124impl Drop for Subscription {
4125    fn drop(&mut self) {
4126        match self {
4127            Subscription::Subscription {
4128                id,
4129                entity_id,
4130                subscriptions,
4131            } => {
4132                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
4133                    match subscriptions
4134                        .lock()
4135                        .entry(*entity_id)
4136                        .or_default()
4137                        .entry(*id)
4138                    {
4139                        btree_map::Entry::Vacant(entry) => {
4140                            entry.insert(None);
4141                        }
4142                        btree_map::Entry::Occupied(entry) => {
4143                            entry.remove();
4144                        }
4145                    }
4146                }
4147            }
4148            Subscription::GlobalSubscription {
4149                id,
4150                type_id,
4151                subscriptions,
4152            } => {
4153                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
4154                    match subscriptions.lock().entry(*type_id).or_default().entry(*id) {
4155                        btree_map::Entry::Vacant(entry) => {
4156                            entry.insert(None);
4157                        }
4158                        btree_map::Entry::Occupied(entry) => {
4159                            entry.remove();
4160                        }
4161                    }
4162                }
4163            }
4164            Subscription::Observation {
4165                id,
4166                entity_id,
4167                observations,
4168            } => {
4169                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4170                    match observations
4171                        .lock()
4172                        .entry(*entity_id)
4173                        .or_default()
4174                        .entry(*id)
4175                    {
4176                        btree_map::Entry::Vacant(entry) => {
4177                            entry.insert(None);
4178                        }
4179                        btree_map::Entry::Occupied(entry) => {
4180                            entry.remove();
4181                        }
4182                    }
4183                }
4184            }
4185            Subscription::ReleaseObservation {
4186                id,
4187                entity_id,
4188                observations,
4189            } => {
4190                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4191                    if let Some(observations) = observations.lock().get_mut(entity_id) {
4192                        observations.remove(id);
4193                    }
4194                }
4195            }
4196        }
4197    }
4198}
4199
4200lazy_static! {
4201    static ref LEAK_BACKTRACE: bool =
4202        std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty());
4203}
4204
4205#[cfg(any(test, feature = "test-support"))]
4206#[derive(Default)]
4207pub struct LeakDetector {
4208    next_handle_id: usize,
4209    handle_backtraces: HashMap<
4210        usize,
4211        (
4212            Option<&'static str>,
4213            HashMap<usize, Option<backtrace::Backtrace>>,
4214        ),
4215    >,
4216}
4217
4218#[cfg(any(test, feature = "test-support"))]
4219impl LeakDetector {
4220    fn handle_created(&mut self, type_name: Option<&'static str>, entity_id: usize) -> usize {
4221        let handle_id = post_inc(&mut self.next_handle_id);
4222        let entry = self.handle_backtraces.entry(entity_id).or_default();
4223        let backtrace = if *LEAK_BACKTRACE {
4224            Some(backtrace::Backtrace::new_unresolved())
4225        } else {
4226            None
4227        };
4228        if let Some(type_name) = type_name {
4229            entry.0.get_or_insert(type_name);
4230        }
4231        entry.1.insert(handle_id, backtrace);
4232        handle_id
4233    }
4234
4235    fn handle_dropped(&mut self, entity_id: usize, handle_id: usize) {
4236        if let Some((_, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
4237            assert!(backtraces.remove(&handle_id).is_some());
4238            if backtraces.is_empty() {
4239                self.handle_backtraces.remove(&entity_id);
4240            }
4241        }
4242    }
4243
4244    pub fn detect(&mut self) {
4245        let mut found_leaks = false;
4246        for (id, (type_name, backtraces)) in self.handle_backtraces.iter_mut() {
4247            eprintln!(
4248                "leaked {} handles to {:?} {}",
4249                backtraces.len(),
4250                type_name.unwrap_or("entity"),
4251                id
4252            );
4253            for trace in backtraces.values_mut() {
4254                if let Some(trace) = trace {
4255                    trace.resolve();
4256                    eprintln!("{:?}", crate::util::CwdBacktrace(trace));
4257                }
4258            }
4259            found_leaks = true;
4260        }
4261
4262        let hint = if *LEAK_BACKTRACE {
4263            ""
4264        } else {
4265            " – set LEAK_BACKTRACE=1 for more information"
4266        };
4267        assert!(!found_leaks, "detected leaked handles{}", hint);
4268    }
4269}
4270
4271#[derive(Default)]
4272struct RefCounts {
4273    entity_counts: HashMap<usize, usize>,
4274    element_state_counts: HashMap<ElementStateId, ElementStateRefCount>,
4275    dropped_models: HashSet<usize>,
4276    dropped_views: HashSet<(usize, usize)>,
4277    dropped_element_states: HashSet<ElementStateId>,
4278
4279    #[cfg(any(test, feature = "test-support"))]
4280    leak_detector: Arc<Mutex<LeakDetector>>,
4281}
4282
4283struct ElementStateRefCount {
4284    ref_count: usize,
4285    frame_id: usize,
4286}
4287
4288impl RefCounts {
4289    fn inc_model(&mut self, model_id: usize) {
4290        match self.entity_counts.entry(model_id) {
4291            Entry::Occupied(mut entry) => {
4292                *entry.get_mut() += 1;
4293            }
4294            Entry::Vacant(entry) => {
4295                entry.insert(1);
4296                self.dropped_models.remove(&model_id);
4297            }
4298        }
4299    }
4300
4301    fn inc_view(&mut self, window_id: usize, view_id: usize) {
4302        match self.entity_counts.entry(view_id) {
4303            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
4304            Entry::Vacant(entry) => {
4305                entry.insert(1);
4306                self.dropped_views.remove(&(window_id, view_id));
4307            }
4308        }
4309    }
4310
4311    fn inc_element_state(&mut self, id: ElementStateId, frame_id: usize) {
4312        match self.element_state_counts.entry(id) {
4313            Entry::Occupied(mut entry) => {
4314                let entry = entry.get_mut();
4315                if entry.frame_id == frame_id || entry.ref_count >= 2 {
4316                    panic!("used the same element state more than once in the same frame");
4317                }
4318                entry.ref_count += 1;
4319                entry.frame_id = frame_id;
4320            }
4321            Entry::Vacant(entry) => {
4322                entry.insert(ElementStateRefCount {
4323                    ref_count: 1,
4324                    frame_id,
4325                });
4326                self.dropped_element_states.remove(&id);
4327            }
4328        }
4329    }
4330
4331    fn dec_model(&mut self, model_id: usize) {
4332        let count = self.entity_counts.get_mut(&model_id).unwrap();
4333        *count -= 1;
4334        if *count == 0 {
4335            self.entity_counts.remove(&model_id);
4336            self.dropped_models.insert(model_id);
4337        }
4338    }
4339
4340    fn dec_view(&mut self, window_id: usize, view_id: usize) {
4341        let count = self.entity_counts.get_mut(&view_id).unwrap();
4342        *count -= 1;
4343        if *count == 0 {
4344            self.entity_counts.remove(&view_id);
4345            self.dropped_views.insert((window_id, view_id));
4346        }
4347    }
4348
4349    fn dec_element_state(&mut self, id: ElementStateId) {
4350        let entry = self.element_state_counts.get_mut(&id).unwrap();
4351        entry.ref_count -= 1;
4352        if entry.ref_count == 0 {
4353            self.element_state_counts.remove(&id);
4354            self.dropped_element_states.insert(id);
4355        }
4356    }
4357
4358    fn is_entity_alive(&self, entity_id: usize) -> bool {
4359        self.entity_counts.contains_key(&entity_id)
4360    }
4361
4362    fn take_dropped(
4363        &mut self,
4364    ) -> (
4365        HashSet<usize>,
4366        HashSet<(usize, usize)>,
4367        HashSet<ElementStateId>,
4368    ) {
4369        (
4370            std::mem::take(&mut self.dropped_models),
4371            std::mem::take(&mut self.dropped_views),
4372            std::mem::take(&mut self.dropped_element_states),
4373        )
4374    }
4375}
4376
4377#[cfg(test)]
4378mod tests {
4379    use super::*;
4380    use crate::elements::*;
4381    use smol::future::poll_once;
4382    use std::{
4383        cell::Cell,
4384        sync::atomic::{AtomicUsize, Ordering::SeqCst},
4385    };
4386
4387    #[crate::test(self)]
4388    fn test_model_handles(cx: &mut MutableAppContext) {
4389        struct Model {
4390            other: Option<ModelHandle<Model>>,
4391            events: Vec<String>,
4392        }
4393
4394        impl Entity for Model {
4395            type Event = usize;
4396        }
4397
4398        impl Model {
4399            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
4400                if let Some(other) = other.as_ref() {
4401                    cx.observe(other, |me, _, _| {
4402                        me.events.push("notified".into());
4403                    })
4404                    .detach();
4405                    cx.subscribe(other, |me, _, event, _| {
4406                        me.events.push(format!("observed event {}", event));
4407                    })
4408                    .detach();
4409                }
4410
4411                Self {
4412                    other,
4413                    events: Vec::new(),
4414                }
4415            }
4416        }
4417
4418        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
4419        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
4420        assert_eq!(cx.cx.models.len(), 2);
4421
4422        handle_1.update(cx, |model, cx| {
4423            model.events.push("updated".into());
4424            cx.emit(1);
4425            cx.notify();
4426            cx.emit(2);
4427        });
4428        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4429        assert_eq!(
4430            handle_2.read(cx).events,
4431            vec![
4432                "observed event 1".to_string(),
4433                "notified".to_string(),
4434                "observed event 2".to_string(),
4435            ]
4436        );
4437
4438        handle_2.update(cx, |model, _| {
4439            drop(handle_1);
4440            model.other.take();
4441        });
4442
4443        assert_eq!(cx.cx.models.len(), 1);
4444        assert!(cx.subscriptions.lock().is_empty());
4445        assert!(cx.observations.lock().is_empty());
4446    }
4447
4448    #[crate::test(self)]
4449    fn test_model_events(cx: &mut MutableAppContext) {
4450        #[derive(Default)]
4451        struct Model {
4452            events: Vec<usize>,
4453        }
4454
4455        impl Entity for Model {
4456            type Event = usize;
4457        }
4458
4459        let handle_1 = cx.add_model(|_| Model::default());
4460        let handle_2 = cx.add_model(|_| Model::default());
4461
4462        handle_1.update(cx, |_, cx| {
4463            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
4464                model.events.push(*event);
4465
4466                cx.subscribe(&emitter, |model, _, event, _| {
4467                    model.events.push(*event * 2);
4468                })
4469                .detach();
4470            })
4471            .detach();
4472        });
4473
4474        handle_2.update(cx, |_, c| c.emit(7));
4475        assert_eq!(handle_1.read(cx).events, vec![7]);
4476
4477        handle_2.update(cx, |_, c| c.emit(5));
4478        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4479    }
4480
4481    #[crate::test(self)]
4482    fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
4483        #[derive(Default)]
4484        struct Model;
4485
4486        impl Entity for Model {
4487            type Event = ();
4488        }
4489
4490        let events = Rc::new(RefCell::new(Vec::new()));
4491        cx.add_model(|cx| {
4492            drop(cx.subscribe(&cx.handle(), {
4493                let events = events.clone();
4494                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
4495            }));
4496            cx.subscribe(&cx.handle(), {
4497                let events = events.clone();
4498                move |_, _, _, _| events.borrow_mut().push("before emit")
4499            })
4500            .detach();
4501            cx.emit(());
4502            cx.subscribe(&cx.handle(), {
4503                let events = events.clone();
4504                move |_, _, _, _| events.borrow_mut().push("after emit")
4505            })
4506            .detach();
4507            Model
4508        });
4509        assert_eq!(*events.borrow(), ["before emit"]);
4510    }
4511
4512    #[crate::test(self)]
4513    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
4514        #[derive(Default)]
4515        struct Model {
4516            count: usize,
4517            events: Vec<usize>,
4518        }
4519
4520        impl Entity for Model {
4521            type Event = ();
4522        }
4523
4524        let handle_1 = cx.add_model(|_| Model::default());
4525        let handle_2 = cx.add_model(|_| Model::default());
4526
4527        handle_1.update(cx, |_, c| {
4528            c.observe(&handle_2, move |model, observed, c| {
4529                model.events.push(observed.read(c).count);
4530                c.observe(&observed, |model, observed, c| {
4531                    model.events.push(observed.read(c).count * 2);
4532                })
4533                .detach();
4534            })
4535            .detach();
4536        });
4537
4538        handle_2.update(cx, |model, c| {
4539            model.count = 7;
4540            c.notify()
4541        });
4542        assert_eq!(handle_1.read(cx).events, vec![7]);
4543
4544        handle_2.update(cx, |model, c| {
4545            model.count = 5;
4546            c.notify()
4547        });
4548        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
4549    }
4550
4551    #[crate::test(self)]
4552    fn test_view_handles(cx: &mut MutableAppContext) {
4553        struct View {
4554            other: Option<ViewHandle<View>>,
4555            events: Vec<String>,
4556        }
4557
4558        impl Entity for View {
4559            type Event = usize;
4560        }
4561
4562        impl super::View for View {
4563            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4564                Empty::new().boxed()
4565            }
4566
4567            fn ui_name() -> &'static str {
4568                "View"
4569            }
4570        }
4571
4572        impl View {
4573            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
4574                if let Some(other) = other.as_ref() {
4575                    cx.subscribe(other, |me, _, event, _| {
4576                        me.events.push(format!("observed event {}", event));
4577                    })
4578                    .detach();
4579                }
4580                Self {
4581                    other,
4582                    events: Vec::new(),
4583                }
4584            }
4585        }
4586
4587        let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
4588        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
4589        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
4590        assert_eq!(cx.cx.views.len(), 3);
4591
4592        handle_1.update(cx, |view, cx| {
4593            view.events.push("updated".into());
4594            cx.emit(1);
4595            cx.emit(2);
4596        });
4597        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4598        assert_eq!(
4599            handle_2.read(cx).events,
4600            vec![
4601                "observed event 1".to_string(),
4602                "observed event 2".to_string(),
4603            ]
4604        );
4605
4606        handle_2.update(cx, |view, _| {
4607            drop(handle_1);
4608            view.other.take();
4609        });
4610
4611        assert_eq!(cx.cx.views.len(), 2);
4612        assert!(cx.subscriptions.lock().is_empty());
4613        assert!(cx.observations.lock().is_empty());
4614    }
4615
4616    #[crate::test(self)]
4617    fn test_add_window(cx: &mut MutableAppContext) {
4618        struct View {
4619            mouse_down_count: Arc<AtomicUsize>,
4620        }
4621
4622        impl Entity for View {
4623            type Event = ();
4624        }
4625
4626        impl super::View for View {
4627            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4628                let mouse_down_count = self.mouse_down_count.clone();
4629                EventHandler::new(Empty::new().boxed())
4630                    .on_mouse_down(move |_| {
4631                        mouse_down_count.fetch_add(1, SeqCst);
4632                        true
4633                    })
4634                    .boxed()
4635            }
4636
4637            fn ui_name() -> &'static str {
4638                "View"
4639            }
4640        }
4641
4642        let mouse_down_count = Arc::new(AtomicUsize::new(0));
4643        let (window_id, _) = cx.add_window(Default::default(), |_| View {
4644            mouse_down_count: mouse_down_count.clone(),
4645        });
4646        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
4647        // Ensure window's root element is in a valid lifecycle state.
4648        presenter.borrow_mut().dispatch_event(
4649            Event::LeftMouseDown {
4650                position: Default::default(),
4651                ctrl: false,
4652                alt: false,
4653                shift: false,
4654                cmd: false,
4655                click_count: 1,
4656            },
4657            cx,
4658        );
4659        assert_eq!(mouse_down_count.load(SeqCst), 1);
4660    }
4661
4662    #[crate::test(self)]
4663    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
4664        struct Model {
4665            released: Rc<Cell<bool>>,
4666        }
4667
4668        struct View {
4669            released: Rc<Cell<bool>>,
4670        }
4671
4672        impl Entity for Model {
4673            type Event = ();
4674
4675            fn release(&mut self, _: &mut MutableAppContext) {
4676                self.released.set(true);
4677            }
4678        }
4679
4680        impl Entity for View {
4681            type Event = ();
4682
4683            fn release(&mut self, _: &mut MutableAppContext) {
4684                self.released.set(true);
4685            }
4686        }
4687
4688        impl super::View for View {
4689            fn ui_name() -> &'static str {
4690                "View"
4691            }
4692
4693            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4694                Empty::new().boxed()
4695            }
4696        }
4697
4698        let model_released = Rc::new(Cell::new(false));
4699        let model_release_observed = Rc::new(Cell::new(false));
4700        let view_released = Rc::new(Cell::new(false));
4701        let view_release_observed = Rc::new(Cell::new(false));
4702
4703        let model = cx.add_model(|_| Model {
4704            released: model_released.clone(),
4705        });
4706        let (window_id, view) = cx.add_window(Default::default(), |_| View {
4707            released: view_released.clone(),
4708        });
4709        assert!(!model_released.get());
4710        assert!(!view_released.get());
4711
4712        cx.observe_release(&model, {
4713            let model_release_observed = model_release_observed.clone();
4714            move |_, _| model_release_observed.set(true)
4715        })
4716        .detach();
4717        cx.observe_release(&view, {
4718            let view_release_observed = view_release_observed.clone();
4719            move |_, _| view_release_observed.set(true)
4720        })
4721        .detach();
4722
4723        cx.update(move |_| {
4724            drop(model);
4725        });
4726        assert!(model_released.get());
4727        assert!(model_release_observed.get());
4728
4729        drop(view);
4730        cx.remove_window(window_id);
4731        assert!(view_released.get());
4732        assert!(view_release_observed.get());
4733    }
4734
4735    #[crate::test(self)]
4736    fn test_view_events(cx: &mut MutableAppContext) {
4737        #[derive(Default)]
4738        struct View {
4739            events: Vec<usize>,
4740        }
4741
4742        impl Entity for View {
4743            type Event = usize;
4744        }
4745
4746        impl super::View for View {
4747            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4748                Empty::new().boxed()
4749            }
4750
4751            fn ui_name() -> &'static str {
4752                "View"
4753            }
4754        }
4755
4756        struct Model;
4757
4758        impl Entity for Model {
4759            type Event = usize;
4760        }
4761
4762        let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
4763        let handle_2 = cx.add_view(window_id, |_| View::default());
4764        let handle_3 = cx.add_model(|_| Model);
4765
4766        handle_1.update(cx, |_, cx| {
4767            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
4768                me.events.push(*event);
4769
4770                cx.subscribe(&emitter, |me, _, event, _| {
4771                    me.events.push(*event * 2);
4772                })
4773                .detach();
4774            })
4775            .detach();
4776
4777            cx.subscribe(&handle_3, |me, _, event, _| {
4778                me.events.push(*event);
4779            })
4780            .detach();
4781        });
4782
4783        handle_2.update(cx, |_, c| c.emit(7));
4784        assert_eq!(handle_1.read(cx).events, vec![7]);
4785
4786        handle_2.update(cx, |_, c| c.emit(5));
4787        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4788
4789        handle_3.update(cx, |_, c| c.emit(9));
4790        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
4791    }
4792
4793    #[crate::test(self)]
4794    fn test_global_events(cx: &mut MutableAppContext) {
4795        #[derive(Clone, Debug, Eq, PartialEq)]
4796        struct GlobalEvent(u64);
4797
4798        let events = Rc::new(RefCell::new(Vec::new()));
4799        let first_subscription;
4800        let second_subscription;
4801
4802        {
4803            let events = events.clone();
4804            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
4805                events.borrow_mut().push(("First", e.clone()));
4806            });
4807        }
4808
4809        {
4810            let events = events.clone();
4811            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
4812                events.borrow_mut().push(("Second", e.clone()));
4813            });
4814        }
4815
4816        cx.update(|cx| {
4817            cx.emit_global(GlobalEvent(1));
4818            cx.emit_global(GlobalEvent(2));
4819        });
4820
4821        drop(first_subscription);
4822
4823        cx.update(|cx| {
4824            cx.emit_global(GlobalEvent(3));
4825        });
4826
4827        drop(second_subscription);
4828
4829        cx.update(|cx| {
4830            cx.emit_global(GlobalEvent(4));
4831        });
4832
4833        assert_eq!(
4834            &*events.borrow(),
4835            &[
4836                ("First", GlobalEvent(1)),
4837                ("Second", GlobalEvent(1)),
4838                ("First", GlobalEvent(2)),
4839                ("Second", GlobalEvent(2)),
4840                ("Second", GlobalEvent(3)),
4841            ]
4842        );
4843    }
4844
4845    #[crate::test(self)]
4846    fn test_global_events_emitted_before_subscription(cx: &mut MutableAppContext) {
4847        let events = Rc::new(RefCell::new(Vec::new()));
4848        cx.update(|cx| {
4849            {
4850                let events = events.clone();
4851                drop(cx.subscribe_global(move |_: &(), _| {
4852                    events.borrow_mut().push("dropped before emit");
4853                }));
4854            }
4855
4856            {
4857                let events = events.clone();
4858                cx.subscribe_global(move |_: &(), _| {
4859                    events.borrow_mut().push("before emit");
4860                })
4861                .detach();
4862            }
4863
4864            cx.emit_global(());
4865
4866            {
4867                let events = events.clone();
4868                cx.subscribe_global(move |_: &(), _| {
4869                    events.borrow_mut().push("after emit");
4870                })
4871                .detach();
4872            }
4873        });
4874
4875        assert_eq!(*events.borrow(), ["before emit"]);
4876    }
4877
4878    #[crate::test(self)]
4879    fn test_global_nested_events(cx: &mut MutableAppContext) {
4880        #[derive(Clone, Debug, Eq, PartialEq)]
4881        struct GlobalEvent(u64);
4882
4883        let events = Rc::new(RefCell::new(Vec::new()));
4884
4885        {
4886            let events = events.clone();
4887            cx.subscribe_global(move |e: &GlobalEvent, cx| {
4888                events.borrow_mut().push(("Outer", e.clone()));
4889
4890                let events = events.clone();
4891                cx.subscribe_global(move |e: &GlobalEvent, _| {
4892                    events.borrow_mut().push(("Inner", e.clone()));
4893                })
4894                .detach();
4895            })
4896            .detach();
4897        }
4898
4899        cx.update(|cx| {
4900            cx.emit_global(GlobalEvent(1));
4901            cx.emit_global(GlobalEvent(2));
4902            cx.emit_global(GlobalEvent(3));
4903        });
4904
4905        assert_eq!(
4906            &*events.borrow(),
4907            &[
4908                ("Outer", GlobalEvent(1)),
4909                ("Outer", GlobalEvent(2)),
4910                ("Inner", GlobalEvent(2)),
4911                ("Outer", GlobalEvent(3)),
4912                ("Inner", GlobalEvent(3)),
4913                ("Inner", GlobalEvent(3)),
4914            ]
4915        );
4916    }
4917
4918    #[crate::test(self)]
4919    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
4920        struct View;
4921
4922        impl Entity for View {
4923            type Event = ();
4924        }
4925
4926        impl super::View for View {
4927            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4928                Empty::new().boxed()
4929            }
4930
4931            fn ui_name() -> &'static str {
4932                "View"
4933            }
4934        }
4935
4936        struct Model;
4937
4938        impl Entity for Model {
4939            type Event = ();
4940        }
4941
4942        let (window_id, _) = cx.add_window(Default::default(), |_| View);
4943        let observing_view = cx.add_view(window_id, |_| View);
4944        let emitting_view = cx.add_view(window_id, |_| View);
4945        let observing_model = cx.add_model(|_| Model);
4946        let observed_model = cx.add_model(|_| Model);
4947
4948        observing_view.update(cx, |_, cx| {
4949            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
4950            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4951        });
4952        observing_model.update(cx, |_, cx| {
4953            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4954        });
4955
4956        cx.update(|_| {
4957            drop(observing_view);
4958            drop(observing_model);
4959        });
4960
4961        emitting_view.update(cx, |_, cx| cx.emit(()));
4962        observed_model.update(cx, |_, cx| cx.emit(()));
4963    }
4964
4965    #[crate::test(self)]
4966    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
4967        #[derive(Default)]
4968        struct TestView;
4969
4970        impl Entity for TestView {
4971            type Event = ();
4972        }
4973
4974        impl View for TestView {
4975            fn ui_name() -> &'static str {
4976                "TestView"
4977            }
4978
4979            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4980                Empty::new().boxed()
4981            }
4982        }
4983
4984        let events = Rc::new(RefCell::new(Vec::new()));
4985        cx.add_window(Default::default(), |cx| {
4986            drop(cx.subscribe(&cx.handle(), {
4987                let events = events.clone();
4988                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
4989            }));
4990            cx.subscribe(&cx.handle(), {
4991                let events = events.clone();
4992                move |_, _, _, _| events.borrow_mut().push("before emit")
4993            })
4994            .detach();
4995            cx.emit(());
4996            cx.subscribe(&cx.handle(), {
4997                let events = events.clone();
4998                move |_, _, _, _| events.borrow_mut().push("after emit")
4999            })
5000            .detach();
5001            TestView
5002        });
5003        assert_eq!(*events.borrow(), ["before emit"]);
5004    }
5005
5006    #[crate::test(self)]
5007    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
5008        #[derive(Default)]
5009        struct View {
5010            events: Vec<usize>,
5011        }
5012
5013        impl Entity for View {
5014            type Event = usize;
5015        }
5016
5017        impl super::View for View {
5018            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5019                Empty::new().boxed()
5020            }
5021
5022            fn ui_name() -> &'static str {
5023                "View"
5024            }
5025        }
5026
5027        #[derive(Default)]
5028        struct Model {
5029            count: usize,
5030        }
5031
5032        impl Entity for Model {
5033            type Event = ();
5034        }
5035
5036        let (_, view) = cx.add_window(Default::default(), |_| View::default());
5037        let model = cx.add_model(|_| Model::default());
5038
5039        view.update(cx, |_, c| {
5040            c.observe(&model, |me, observed, c| {
5041                me.events.push(observed.read(c).count)
5042            })
5043            .detach();
5044        });
5045
5046        model.update(cx, |model, c| {
5047            model.count = 11;
5048            c.notify();
5049        });
5050        assert_eq!(view.read(cx).events, vec![11]);
5051    }
5052
5053    #[crate::test(self)]
5054    fn test_dropping_observers(cx: &mut MutableAppContext) {
5055        struct View;
5056
5057        impl Entity for View {
5058            type Event = ();
5059        }
5060
5061        impl super::View for View {
5062            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5063                Empty::new().boxed()
5064            }
5065
5066            fn ui_name() -> &'static str {
5067                "View"
5068            }
5069        }
5070
5071        struct Model;
5072
5073        impl Entity for Model {
5074            type Event = ();
5075        }
5076
5077        let (window_id, _) = cx.add_window(Default::default(), |_| View);
5078        let observing_view = cx.add_view(window_id, |_| View);
5079        let observing_model = cx.add_model(|_| Model);
5080        let observed_model = cx.add_model(|_| Model);
5081
5082        observing_view.update(cx, |_, cx| {
5083            cx.observe(&observed_model, |_, _, _| {}).detach();
5084        });
5085        observing_model.update(cx, |_, cx| {
5086            cx.observe(&observed_model, |_, _, _| {}).detach();
5087        });
5088
5089        cx.update(|_| {
5090            drop(observing_view);
5091            drop(observing_model);
5092        });
5093
5094        observed_model.update(cx, |_, cx| cx.notify());
5095    }
5096
5097    #[crate::test(self)]
5098    fn test_dropping_subscriptions_during_callback(cx: &mut MutableAppContext) {
5099        struct Model;
5100
5101        impl Entity for Model {
5102            type Event = u64;
5103        }
5104
5105        // Events
5106        let observing_model = cx.add_model(|_| Model);
5107        let observed_model = cx.add_model(|_| Model);
5108
5109        let events = Rc::new(RefCell::new(Vec::new()));
5110
5111        observing_model.update(cx, |_, cx| {
5112            let events = events.clone();
5113            let subscription = Rc::new(RefCell::new(None));
5114            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
5115                let subscription = subscription.clone();
5116                move |_, _, e, _| {
5117                    subscription.borrow_mut().take();
5118                    events.borrow_mut().push(e.clone());
5119                }
5120            }));
5121        });
5122
5123        observed_model.update(cx, |_, cx| {
5124            cx.emit(1);
5125            cx.emit(2);
5126        });
5127
5128        assert_eq!(*events.borrow(), [1]);
5129
5130        // Global Events
5131        #[derive(Clone, Debug, Eq, PartialEq)]
5132        struct GlobalEvent(u64);
5133
5134        let events = Rc::new(RefCell::new(Vec::new()));
5135
5136        {
5137            let events = events.clone();
5138            let subscription = Rc::new(RefCell::new(None));
5139            *subscription.borrow_mut() = Some(cx.subscribe_global({
5140                let subscription = subscription.clone();
5141                move |e: &GlobalEvent, _| {
5142                    subscription.borrow_mut().take();
5143                    events.borrow_mut().push(e.clone());
5144                }
5145            }));
5146        }
5147
5148        cx.update(|cx| {
5149            cx.emit_global(GlobalEvent(1));
5150            cx.emit_global(GlobalEvent(2));
5151        });
5152
5153        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
5154
5155        // Model Observation
5156        let observing_model = cx.add_model(|_| Model);
5157        let observed_model = cx.add_model(|_| Model);
5158
5159        let observation_count = Rc::new(RefCell::new(0));
5160
5161        observing_model.update(cx, |_, cx| {
5162            let observation_count = observation_count.clone();
5163            let subscription = Rc::new(RefCell::new(None));
5164            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
5165                let subscription = subscription.clone();
5166                move |_, _, _| {
5167                    subscription.borrow_mut().take();
5168                    *observation_count.borrow_mut() += 1;
5169                }
5170            }));
5171        });
5172
5173        observed_model.update(cx, |_, cx| {
5174            cx.notify();
5175        });
5176
5177        observed_model.update(cx, |_, cx| {
5178            cx.notify();
5179        });
5180
5181        assert_eq!(*observation_count.borrow(), 1);
5182
5183        // View Observation
5184        struct View;
5185
5186        impl Entity for View {
5187            type Event = ();
5188        }
5189
5190        impl super::View for View {
5191            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5192                Empty::new().boxed()
5193            }
5194
5195            fn ui_name() -> &'static str {
5196                "View"
5197            }
5198        }
5199
5200        let (window_id, _) = cx.add_window(Default::default(), |_| View);
5201        let observing_view = cx.add_view(window_id, |_| View);
5202        let observed_view = cx.add_view(window_id, |_| View);
5203
5204        let observation_count = Rc::new(RefCell::new(0));
5205        observing_view.update(cx, |_, cx| {
5206            let observation_count = observation_count.clone();
5207            let subscription = Rc::new(RefCell::new(None));
5208            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
5209                let subscription = subscription.clone();
5210                move |_, _, _| {
5211                    subscription.borrow_mut().take();
5212                    *observation_count.borrow_mut() += 1;
5213                }
5214            }));
5215        });
5216
5217        observed_view.update(cx, |_, cx| {
5218            cx.notify();
5219        });
5220
5221        observed_view.update(cx, |_, cx| {
5222            cx.notify();
5223        });
5224
5225        assert_eq!(*observation_count.borrow(), 1);
5226    }
5227
5228    #[crate::test(self)]
5229    fn test_focus(cx: &mut MutableAppContext) {
5230        struct View {
5231            name: String,
5232            events: Arc<Mutex<Vec<String>>>,
5233        }
5234
5235        impl Entity for View {
5236            type Event = ();
5237        }
5238
5239        impl super::View for View {
5240            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5241                Empty::new().boxed()
5242            }
5243
5244            fn ui_name() -> &'static str {
5245                "View"
5246            }
5247
5248            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
5249                self.events.lock().push(format!("{} focused", &self.name));
5250            }
5251
5252            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
5253                self.events.lock().push(format!("{} blurred", &self.name));
5254            }
5255        }
5256
5257        let events: Arc<Mutex<Vec<String>>> = Default::default();
5258        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
5259            events: events.clone(),
5260            name: "view 1".to_string(),
5261        });
5262        let view_2 = cx.add_view(window_id, |_| View {
5263            events: events.clone(),
5264            name: "view 2".to_string(),
5265        });
5266
5267        view_1.update(cx, |_, cx| cx.focus(&view_2));
5268        view_1.update(cx, |_, cx| cx.focus(&view_1));
5269        view_1.update(cx, |_, cx| cx.focus(&view_2));
5270        view_1.update(cx, |_, _| drop(view_2));
5271
5272        assert_eq!(
5273            *events.lock(),
5274            [
5275                "view 1 focused".to_string(),
5276                "view 1 blurred".to_string(),
5277                "view 2 focused".to_string(),
5278                "view 2 blurred".to_string(),
5279                "view 1 focused".to_string(),
5280                "view 1 blurred".to_string(),
5281                "view 2 focused".to_string(),
5282                "view 1 focused".to_string(),
5283            ],
5284        );
5285    }
5286
5287    #[crate::test(self)]
5288    fn test_dispatch_action(cx: &mut MutableAppContext) {
5289        struct ViewA {
5290            id: usize,
5291        }
5292
5293        impl Entity for ViewA {
5294            type Event = ();
5295        }
5296
5297        impl View for ViewA {
5298            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5299                Empty::new().boxed()
5300            }
5301
5302            fn ui_name() -> &'static str {
5303                "View"
5304            }
5305        }
5306
5307        struct ViewB {
5308            id: usize,
5309        }
5310
5311        impl Entity for ViewB {
5312            type Event = ();
5313        }
5314
5315        impl View for ViewB {
5316            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5317                Empty::new().boxed()
5318            }
5319
5320            fn ui_name() -> &'static str {
5321                "View"
5322            }
5323        }
5324
5325        action!(Action, &'static str);
5326
5327        let actions = Rc::new(RefCell::new(Vec::new()));
5328
5329        {
5330            let actions = actions.clone();
5331            cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
5332                actions.borrow_mut().push("global".to_string());
5333            });
5334        }
5335
5336        {
5337            let actions = actions.clone();
5338            cx.add_action(move |view: &mut ViewA, action: &Action, cx| {
5339                assert_eq!(action.0, "bar");
5340                cx.propagate_action();
5341                actions.borrow_mut().push(format!("{} a", view.id));
5342            });
5343        }
5344
5345        {
5346            let actions = actions.clone();
5347            cx.add_action(move |view: &mut ViewA, _: &Action, cx| {
5348                if view.id != 1 {
5349                    cx.add_view(|cx| {
5350                        cx.propagate_action(); // Still works on a nested ViewContext
5351                        ViewB { id: 5 }
5352                    });
5353                }
5354                actions.borrow_mut().push(format!("{} b", view.id));
5355            });
5356        }
5357
5358        {
5359            let actions = actions.clone();
5360            cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
5361                cx.propagate_action();
5362                actions.borrow_mut().push(format!("{} c", view.id));
5363            });
5364        }
5365
5366        {
5367            let actions = actions.clone();
5368            cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
5369                cx.propagate_action();
5370                actions.borrow_mut().push(format!("{} d", view.id));
5371            });
5372        }
5373
5374        {
5375            let actions = actions.clone();
5376            cx.capture_action(move |view: &mut ViewA, _: &Action, cx| {
5377                cx.propagate_action();
5378                actions.borrow_mut().push(format!("{} capture", view.id));
5379            });
5380        }
5381
5382        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
5383        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
5384        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
5385        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
5386
5387        cx.dispatch_action(
5388            window_id,
5389            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
5390            &Action("bar"),
5391        );
5392
5393        assert_eq!(
5394            *actions.borrow(),
5395            vec![
5396                "1 capture",
5397                "3 capture",
5398                "4 d",
5399                "4 c",
5400                "3 b",
5401                "3 a",
5402                "2 d",
5403                "2 c",
5404                "1 b"
5405            ]
5406        );
5407
5408        // Remove view_1, which doesn't propagate the action
5409        actions.borrow_mut().clear();
5410        cx.dispatch_action(
5411            window_id,
5412            vec![view_2.id(), view_3.id(), view_4.id()],
5413            &Action("bar"),
5414        );
5415
5416        assert_eq!(
5417            *actions.borrow(),
5418            vec![
5419                "3 capture",
5420                "4 d",
5421                "4 c",
5422                "3 b",
5423                "3 a",
5424                "2 d",
5425                "2 c",
5426                "global"
5427            ]
5428        );
5429    }
5430
5431    #[crate::test(self)]
5432    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
5433        action!(Action, &'static str);
5434
5435        struct View {
5436            id: usize,
5437            keymap_context: keymap::Context,
5438        }
5439
5440        impl Entity for View {
5441            type Event = ();
5442        }
5443
5444        impl super::View for View {
5445            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5446                Empty::new().boxed()
5447            }
5448
5449            fn ui_name() -> &'static str {
5450                "View"
5451            }
5452
5453            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
5454                self.keymap_context.clone()
5455            }
5456        }
5457
5458        impl View {
5459            fn new(id: usize) -> Self {
5460                View {
5461                    id,
5462                    keymap_context: keymap::Context::default(),
5463                }
5464            }
5465        }
5466
5467        let mut view_1 = View::new(1);
5468        let mut view_2 = View::new(2);
5469        let mut view_3 = View::new(3);
5470        view_1.keymap_context.set.insert("a".into());
5471        view_2.keymap_context.set.insert("a".into());
5472        view_2.keymap_context.set.insert("b".into());
5473        view_3.keymap_context.set.insert("a".into());
5474        view_3.keymap_context.set.insert("b".into());
5475        view_3.keymap_context.set.insert("c".into());
5476
5477        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
5478        let view_2 = cx.add_view(window_id, |_| view_2);
5479        let view_3 = cx.add_view(window_id, |_| view_3);
5480
5481        // This keymap's only binding dispatches an action on view 2 because that view will have
5482        // "a" and "b" in its context, but not "c".
5483        cx.add_bindings(vec![keymap::Binding::new(
5484            "a",
5485            Action("a"),
5486            Some("a && b && !c"),
5487        )]);
5488
5489        cx.add_bindings(vec![keymap::Binding::new("b", Action("b"), None)]);
5490
5491        let actions = Rc::new(RefCell::new(Vec::new()));
5492        {
5493            let actions = actions.clone();
5494            cx.add_action(move |view: &mut View, action: &Action, cx| {
5495                if action.0 == "a" {
5496                    actions.borrow_mut().push(format!("{} a", view.id));
5497                } else {
5498                    actions
5499                        .borrow_mut()
5500                        .push(format!("{} {}", view.id, action.0));
5501                    cx.propagate_action();
5502                }
5503            });
5504        }
5505        {
5506            let actions = actions.clone();
5507            cx.add_global_action(move |action: &Action, _| {
5508                actions.borrow_mut().push(format!("global {}", action.0));
5509            });
5510        }
5511
5512        cx.dispatch_keystroke(
5513            window_id,
5514            vec![view_1.id(), view_2.id(), view_3.id()],
5515            &Keystroke::parse("a").unwrap(),
5516        )
5517        .unwrap();
5518
5519        assert_eq!(&*actions.borrow(), &["2 a"]);
5520
5521        actions.borrow_mut().clear();
5522        cx.dispatch_keystroke(
5523            window_id,
5524            vec![view_1.id(), view_2.id(), view_3.id()],
5525            &Keystroke::parse("b").unwrap(),
5526        )
5527        .unwrap();
5528
5529        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
5530    }
5531
5532    #[crate::test(self)]
5533    async fn test_model_condition(cx: &mut TestAppContext) {
5534        struct Counter(usize);
5535
5536        impl super::Entity for Counter {
5537            type Event = ();
5538        }
5539
5540        impl Counter {
5541            fn inc(&mut self, cx: &mut ModelContext<Self>) {
5542                self.0 += 1;
5543                cx.notify();
5544            }
5545        }
5546
5547        let model = cx.add_model(|_| Counter(0));
5548
5549        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
5550        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
5551        smol::pin!(condition1, condition2);
5552
5553        model.update(cx, |model, cx| model.inc(cx));
5554        assert_eq!(poll_once(&mut condition1).await, None);
5555        assert_eq!(poll_once(&mut condition2).await, None);
5556
5557        model.update(cx, |model, cx| model.inc(cx));
5558        assert_eq!(poll_once(&mut condition1).await, Some(()));
5559        assert_eq!(poll_once(&mut condition2).await, None);
5560
5561        model.update(cx, |model, cx| model.inc(cx));
5562        assert_eq!(poll_once(&mut condition2).await, Some(()));
5563
5564        model.update(cx, |_, cx| cx.notify());
5565    }
5566
5567    #[crate::test(self)]
5568    #[should_panic]
5569    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
5570        struct Model;
5571
5572        impl super::Entity for Model {
5573            type Event = ();
5574        }
5575
5576        let model = cx.add_model(|_| Model);
5577        model.condition(&cx, |_, _| false).await;
5578    }
5579
5580    #[crate::test(self)]
5581    #[should_panic(expected = "model dropped with pending condition")]
5582    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
5583        struct Model;
5584
5585        impl super::Entity for Model {
5586            type Event = ();
5587        }
5588
5589        let model = cx.add_model(|_| Model);
5590        let condition = model.condition(&cx, |_, _| false);
5591        cx.update(|_| drop(model));
5592        condition.await;
5593    }
5594
5595    #[crate::test(self)]
5596    async fn test_view_condition(cx: &mut TestAppContext) {
5597        struct Counter(usize);
5598
5599        impl super::Entity for Counter {
5600            type Event = ();
5601        }
5602
5603        impl super::View for Counter {
5604            fn ui_name() -> &'static str {
5605                "test view"
5606            }
5607
5608            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5609                Empty::new().boxed()
5610            }
5611        }
5612
5613        impl Counter {
5614            fn inc(&mut self, cx: &mut ViewContext<Self>) {
5615                self.0 += 1;
5616                cx.notify();
5617            }
5618        }
5619
5620        let (_, view) = cx.add_window(|_| Counter(0));
5621
5622        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
5623        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
5624        smol::pin!(condition1, condition2);
5625
5626        view.update(cx, |view, cx| view.inc(cx));
5627        assert_eq!(poll_once(&mut condition1).await, None);
5628        assert_eq!(poll_once(&mut condition2).await, None);
5629
5630        view.update(cx, |view, cx| view.inc(cx));
5631        assert_eq!(poll_once(&mut condition1).await, Some(()));
5632        assert_eq!(poll_once(&mut condition2).await, None);
5633
5634        view.update(cx, |view, cx| view.inc(cx));
5635        assert_eq!(poll_once(&mut condition2).await, Some(()));
5636        view.update(cx, |_, cx| cx.notify());
5637    }
5638
5639    #[crate::test(self)]
5640    #[should_panic]
5641    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
5642        struct View;
5643
5644        impl super::Entity for View {
5645            type Event = ();
5646        }
5647
5648        impl super::View for View {
5649            fn ui_name() -> &'static str {
5650                "test view"
5651            }
5652
5653            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5654                Empty::new().boxed()
5655            }
5656        }
5657
5658        let (_, view) = cx.add_window(|_| View);
5659        view.condition(&cx, |_, _| false).await;
5660    }
5661
5662    #[crate::test(self)]
5663    #[should_panic(expected = "view dropped with pending condition")]
5664    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
5665        struct View;
5666
5667        impl super::Entity for View {
5668            type Event = ();
5669        }
5670
5671        impl super::View for View {
5672            fn ui_name() -> &'static str {
5673                "test view"
5674            }
5675
5676            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5677                Empty::new().boxed()
5678            }
5679        }
5680
5681        let window_id = cx.add_window(|_| View).0;
5682        let view = cx.add_view(window_id, |_| View);
5683
5684        let condition = view.condition(&cx, |_, _| false);
5685        cx.update(|_| drop(view));
5686        condition.await;
5687    }
5688
5689    #[crate::test(self)]
5690    fn test_refresh_windows(cx: &mut MutableAppContext) {
5691        struct View(usize);
5692
5693        impl super::Entity for View {
5694            type Event = ();
5695        }
5696
5697        impl super::View for View {
5698            fn ui_name() -> &'static str {
5699                "test view"
5700            }
5701
5702            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5703                Empty::new().named(format!("render count: {}", post_inc(&mut self.0)))
5704            }
5705        }
5706
5707        let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
5708        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
5709
5710        assert_eq!(
5711            presenter.borrow().rendered_views[&root_view.id()].name(),
5712            Some("render count: 0")
5713        );
5714
5715        let view = cx.add_view(window_id, |cx| {
5716            cx.refresh_windows();
5717            View(0)
5718        });
5719
5720        assert_eq!(
5721            presenter.borrow().rendered_views[&root_view.id()].name(),
5722            Some("render count: 1")
5723        );
5724        assert_eq!(
5725            presenter.borrow().rendered_views[&view.id()].name(),
5726            Some("render count: 0")
5727        );
5728
5729        cx.update(|cx| cx.refresh_windows());
5730        assert_eq!(
5731            presenter.borrow().rendered_views[&root_view.id()].name(),
5732            Some("render count: 2")
5733        );
5734        assert_eq!(
5735            presenter.borrow().rendered_views[&view.id()].name(),
5736            Some("render count: 1")
5737        );
5738
5739        cx.update(|cx| {
5740            cx.refresh_windows();
5741            drop(view);
5742        });
5743        assert_eq!(
5744            presenter.borrow().rendered_views[&root_view.id()].name(),
5745            Some("render count: 3")
5746        );
5747        assert_eq!(presenter.borrow().rendered_views.len(), 1);
5748    }
5749}