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