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 global<T: 'static>(&self) -> &T {
2125        self.globals
2126            .get(&TypeId::of::<T>())
2127            .expect("no app state has been added for this type")
2128            .downcast_ref()
2129            .unwrap()
2130    }
2131}
2132
2133impl ReadModel for AppContext {
2134    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2135        if let Some(model) = self.models.get(&handle.model_id) {
2136            model
2137                .as_any()
2138                .downcast_ref()
2139                .expect("downcast should be type safe")
2140        } else {
2141            panic!("circular model reference");
2142        }
2143    }
2144}
2145
2146impl UpgradeModelHandle for AppContext {
2147    fn upgrade_model_handle<T: Entity>(
2148        &self,
2149        handle: &WeakModelHandle<T>,
2150    ) -> Option<ModelHandle<T>> {
2151        if self.models.contains_key(&handle.model_id) {
2152            Some(ModelHandle::new(handle.model_id, &self.ref_counts))
2153        } else {
2154            None
2155        }
2156    }
2157
2158    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2159        self.models.contains_key(&handle.model_id)
2160    }
2161
2162    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2163        if self.models.contains_key(&handle.model_id) {
2164            Some(AnyModelHandle::new(
2165                handle.model_id,
2166                handle.model_type,
2167                self.ref_counts.clone(),
2168            ))
2169        } else {
2170            None
2171        }
2172    }
2173}
2174
2175impl UpgradeViewHandle for AppContext {
2176    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2177        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2178            Some(ViewHandle::new(
2179                handle.window_id,
2180                handle.view_id,
2181                &self.ref_counts,
2182            ))
2183        } else {
2184            None
2185        }
2186    }
2187
2188    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
2189        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2190            Some(AnyViewHandle::new(
2191                handle.window_id,
2192                handle.view_id,
2193                handle.view_type,
2194                self.ref_counts.clone(),
2195            ))
2196        } else {
2197            None
2198        }
2199    }
2200}
2201
2202impl ReadView for AppContext {
2203    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2204        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
2205            view.as_any()
2206                .downcast_ref()
2207                .expect("downcast should be type safe")
2208        } else {
2209            panic!("circular view reference");
2210        }
2211    }
2212}
2213
2214struct Window {
2215    root_view: AnyViewHandle,
2216    focused_view_id: Option<usize>,
2217    invalidation: Option<WindowInvalidation>,
2218}
2219
2220#[derive(Default, Clone)]
2221pub struct WindowInvalidation {
2222    pub updated: HashSet<usize>,
2223    pub removed: Vec<usize>,
2224}
2225
2226pub enum Effect {
2227    Event {
2228        entity_id: usize,
2229        payload: Box<dyn Any>,
2230    },
2231    GlobalEvent {
2232        payload: Box<dyn Any>,
2233    },
2234    ModelNotification {
2235        model_id: usize,
2236    },
2237    ViewNotification {
2238        window_id: usize,
2239        view_id: usize,
2240    },
2241    Deferred(Box<dyn FnOnce(&mut MutableAppContext)>),
2242    ModelRelease {
2243        model_id: usize,
2244        model: Box<dyn AnyModel>,
2245    },
2246    ViewRelease {
2247        view_id: usize,
2248        view: Box<dyn AnyView>,
2249    },
2250    Focus {
2251        window_id: usize,
2252        view_id: Option<usize>,
2253    },
2254    ResizeWindow {
2255        window_id: usize,
2256    },
2257    RefreshWindows,
2258}
2259
2260impl Debug for Effect {
2261    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2262        match self {
2263            Effect::Event { entity_id, .. } => f
2264                .debug_struct("Effect::Event")
2265                .field("entity_id", entity_id)
2266                .finish(),
2267            Effect::GlobalEvent { payload, .. } => f
2268                .debug_struct("Effect::GlobalEvent")
2269                .field("type_id", &(&*payload).type_id())
2270                .finish(),
2271            Effect::ModelNotification { model_id } => f
2272                .debug_struct("Effect::ModelNotification")
2273                .field("model_id", model_id)
2274                .finish(),
2275            Effect::ViewNotification { window_id, view_id } => f
2276                .debug_struct("Effect::ViewNotification")
2277                .field("window_id", window_id)
2278                .field("view_id", view_id)
2279                .finish(),
2280            Effect::Deferred(_) => f.debug_struct("Effect::Deferred").finish(),
2281            Effect::ModelRelease { model_id, .. } => f
2282                .debug_struct("Effect::ModelRelease")
2283                .field("model_id", model_id)
2284                .finish(),
2285            Effect::ViewRelease { view_id, .. } => f
2286                .debug_struct("Effect::ViewRelease")
2287                .field("view_id", view_id)
2288                .finish(),
2289            Effect::Focus { window_id, view_id } => f
2290                .debug_struct("Effect::Focus")
2291                .field("window_id", window_id)
2292                .field("view_id", view_id)
2293                .finish(),
2294            Effect::ResizeWindow { window_id } => f
2295                .debug_struct("Effect::RefreshWindow")
2296                .field("window_id", window_id)
2297                .finish(),
2298            Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
2299        }
2300    }
2301}
2302
2303pub trait AnyModel {
2304    fn as_any(&self) -> &dyn Any;
2305    fn as_any_mut(&mut self) -> &mut dyn Any;
2306    fn release(&mut self, cx: &mut MutableAppContext);
2307    fn app_will_quit(
2308        &mut self,
2309        cx: &mut MutableAppContext,
2310    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2311}
2312
2313impl<T> AnyModel for T
2314where
2315    T: Entity,
2316{
2317    fn as_any(&self) -> &dyn Any {
2318        self
2319    }
2320
2321    fn as_any_mut(&mut self) -> &mut dyn Any {
2322        self
2323    }
2324
2325    fn release(&mut self, cx: &mut MutableAppContext) {
2326        self.release(cx);
2327    }
2328
2329    fn app_will_quit(
2330        &mut self,
2331        cx: &mut MutableAppContext,
2332    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2333        self.app_will_quit(cx)
2334    }
2335}
2336
2337pub trait AnyView {
2338    fn as_any(&self) -> &dyn Any;
2339    fn as_any_mut(&mut self) -> &mut dyn Any;
2340    fn release(&mut self, cx: &mut MutableAppContext);
2341    fn app_will_quit(
2342        &mut self,
2343        cx: &mut MutableAppContext,
2344    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2345    fn ui_name(&self) -> &'static str;
2346    fn render<'a>(
2347        &mut self,
2348        window_id: usize,
2349        view_id: usize,
2350        titlebar_height: f32,
2351        refreshing: bool,
2352        cx: &mut MutableAppContext,
2353    ) -> ElementBox;
2354    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
2355    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
2356    fn keymap_context(&self, cx: &AppContext) -> keymap::Context;
2357}
2358
2359impl<T> AnyView for T
2360where
2361    T: View,
2362{
2363    fn as_any(&self) -> &dyn Any {
2364        self
2365    }
2366
2367    fn as_any_mut(&mut self) -> &mut dyn Any {
2368        self
2369    }
2370
2371    fn release(&mut self, cx: &mut MutableAppContext) {
2372        self.release(cx);
2373    }
2374
2375    fn app_will_quit(
2376        &mut self,
2377        cx: &mut MutableAppContext,
2378    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2379        self.app_will_quit(cx)
2380    }
2381
2382    fn ui_name(&self) -> &'static str {
2383        T::ui_name()
2384    }
2385
2386    fn render<'a>(
2387        &mut self,
2388        window_id: usize,
2389        view_id: usize,
2390        titlebar_height: f32,
2391        refreshing: bool,
2392        cx: &mut MutableAppContext,
2393    ) -> ElementBox {
2394        View::render(
2395            self,
2396            &mut RenderContext {
2397                window_id,
2398                view_id,
2399                app: cx,
2400                view_type: PhantomData::<T>,
2401                titlebar_height,
2402                refreshing,
2403            },
2404        )
2405    }
2406
2407    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
2408        let mut cx = ViewContext::new(cx, window_id, view_id);
2409        View::on_focus(self, &mut cx);
2410    }
2411
2412    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
2413        let mut cx = ViewContext::new(cx, window_id, view_id);
2414        View::on_blur(self, &mut cx);
2415    }
2416
2417    fn keymap_context(&self, cx: &AppContext) -> keymap::Context {
2418        View::keymap_context(self, cx)
2419    }
2420}
2421
2422pub struct ModelContext<'a, T: ?Sized> {
2423    app: &'a mut MutableAppContext,
2424    model_id: usize,
2425    model_type: PhantomData<T>,
2426    halt_stream: bool,
2427}
2428
2429impl<'a, T: Entity> ModelContext<'a, T> {
2430    fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
2431        Self {
2432            app,
2433            model_id,
2434            model_type: PhantomData,
2435            halt_stream: false,
2436        }
2437    }
2438
2439    pub fn background(&self) -> &Arc<executor::Background> {
2440        &self.app.cx.background
2441    }
2442
2443    pub fn halt_stream(&mut self) {
2444        self.halt_stream = true;
2445    }
2446
2447    pub fn model_id(&self) -> usize {
2448        self.model_id
2449    }
2450
2451    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2452    where
2453        S: Entity,
2454        F: FnOnce(&mut ModelContext<S>) -> S,
2455    {
2456        self.app.add_model(build_model)
2457    }
2458
2459    pub fn emit(&mut self, payload: T::Event) {
2460        self.app.pending_effects.push_back(Effect::Event {
2461            entity_id: self.model_id,
2462            payload: Box::new(payload),
2463        });
2464    }
2465
2466    pub fn notify(&mut self) {
2467        self.app.notify_model(self.model_id);
2468    }
2469
2470    pub fn subscribe<S: Entity, F>(
2471        &mut self,
2472        handle: &ModelHandle<S>,
2473        mut callback: F,
2474    ) -> Subscription
2475    where
2476        S::Event: 'static,
2477        F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
2478    {
2479        let subscriber = self.weak_handle();
2480        self.app
2481            .subscribe_internal(handle, move |emitter, event, cx| {
2482                if let Some(subscriber) = subscriber.upgrade(cx) {
2483                    subscriber.update(cx, |subscriber, cx| {
2484                        callback(subscriber, emitter, event, cx);
2485                    });
2486                    true
2487                } else {
2488                    false
2489                }
2490            })
2491    }
2492
2493    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
2494    where
2495        S: Entity,
2496        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
2497    {
2498        let observer = self.weak_handle();
2499        self.app.observe_internal(handle, move |observed, cx| {
2500            if let Some(observer) = observer.upgrade(cx) {
2501                observer.update(cx, |observer, cx| {
2502                    callback(observer, observed, cx);
2503                });
2504                true
2505            } else {
2506                false
2507            }
2508        })
2509    }
2510
2511    pub fn observe_release<S, F>(
2512        &mut self,
2513        handle: &ModelHandle<S>,
2514        mut callback: F,
2515    ) -> Subscription
2516    where
2517        S: Entity,
2518        F: 'static + FnMut(&mut T, &S, &mut ModelContext<T>),
2519    {
2520        let observer = self.weak_handle();
2521        self.app.observe_release(handle, move |released, cx| {
2522            if let Some(observer) = observer.upgrade(cx) {
2523                observer.update(cx, |observer, cx| {
2524                    callback(observer, released, cx);
2525                });
2526            }
2527        })
2528    }
2529
2530    pub fn handle(&self) -> ModelHandle<T> {
2531        ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
2532    }
2533
2534    pub fn weak_handle(&self) -> WeakModelHandle<T> {
2535        WeakModelHandle::new(self.model_id)
2536    }
2537
2538    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2539    where
2540        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
2541        Fut: 'static + Future<Output = S>,
2542        S: 'static,
2543    {
2544        let handle = self.handle();
2545        self.app.spawn(|cx| f(handle, cx))
2546    }
2547
2548    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
2549    where
2550        F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
2551        Fut: 'static + Future<Output = S>,
2552        S: 'static,
2553    {
2554        let handle = self.weak_handle();
2555        self.app.spawn(|cx| f(handle, cx))
2556    }
2557}
2558
2559impl<M> AsRef<AppContext> for ModelContext<'_, M> {
2560    fn as_ref(&self) -> &AppContext {
2561        &self.app.cx
2562    }
2563}
2564
2565impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
2566    fn as_mut(&mut self) -> &mut MutableAppContext {
2567        self.app
2568    }
2569}
2570
2571impl<M> ReadModel for ModelContext<'_, M> {
2572    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2573        self.app.read_model(handle)
2574    }
2575}
2576
2577impl<M> UpdateModel for ModelContext<'_, M> {
2578    fn update_model<T: Entity, V>(
2579        &mut self,
2580        handle: &ModelHandle<T>,
2581        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
2582    ) -> V {
2583        self.app.update_model(handle, update)
2584    }
2585}
2586
2587impl<M> UpgradeModelHandle for ModelContext<'_, M> {
2588    fn upgrade_model_handle<T: Entity>(
2589        &self,
2590        handle: &WeakModelHandle<T>,
2591    ) -> Option<ModelHandle<T>> {
2592        self.cx.upgrade_model_handle(handle)
2593    }
2594
2595    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2596        self.cx.model_handle_is_upgradable(handle)
2597    }
2598
2599    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2600        self.cx.upgrade_any_model_handle(handle)
2601    }
2602}
2603
2604impl<M> Deref for ModelContext<'_, M> {
2605    type Target = MutableAppContext;
2606
2607    fn deref(&self) -> &Self::Target {
2608        &self.app
2609    }
2610}
2611
2612impl<M> DerefMut for ModelContext<'_, M> {
2613    fn deref_mut(&mut self) -> &mut Self::Target {
2614        &mut self.app
2615    }
2616}
2617
2618pub struct ViewContext<'a, T: ?Sized> {
2619    app: &'a mut MutableAppContext,
2620    window_id: usize,
2621    view_id: usize,
2622    view_type: PhantomData<T>,
2623}
2624
2625impl<'a, T: View> ViewContext<'a, T> {
2626    fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
2627        Self {
2628            app,
2629            window_id,
2630            view_id,
2631            view_type: PhantomData,
2632        }
2633    }
2634
2635    pub fn handle(&self) -> ViewHandle<T> {
2636        ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
2637    }
2638
2639    pub fn weak_handle(&self) -> WeakViewHandle<T> {
2640        WeakViewHandle::new(self.window_id, self.view_id)
2641    }
2642
2643    pub fn window_id(&self) -> usize {
2644        self.window_id
2645    }
2646
2647    pub fn view_id(&self) -> usize {
2648        self.view_id
2649    }
2650
2651    pub fn foreground(&self) -> &Rc<executor::Foreground> {
2652        self.app.foreground()
2653    }
2654
2655    pub fn background_executor(&self) -> &Arc<executor::Background> {
2656        &self.app.cx.background
2657    }
2658
2659    pub fn platform(&self) -> Arc<dyn Platform> {
2660        self.app.platform()
2661    }
2662
2663    pub fn prompt(
2664        &self,
2665        level: PromptLevel,
2666        msg: &str,
2667        answers: &[&str],
2668    ) -> oneshot::Receiver<usize> {
2669        self.app.prompt(self.window_id, level, msg, answers)
2670    }
2671
2672    pub fn prompt_for_paths(
2673        &self,
2674        options: PathPromptOptions,
2675    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2676        self.app.prompt_for_paths(options)
2677    }
2678
2679    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
2680        self.app.prompt_for_new_path(directory)
2681    }
2682
2683    pub fn debug_elements(&self) -> crate::json::Value {
2684        self.app.debug_elements(self.window_id).unwrap()
2685    }
2686
2687    pub fn focus<S>(&mut self, handle: S)
2688    where
2689        S: Into<AnyViewHandle>,
2690    {
2691        let handle = handle.into();
2692        self.app.pending_effects.push_back(Effect::Focus {
2693            window_id: handle.window_id,
2694            view_id: Some(handle.view_id),
2695        });
2696    }
2697
2698    pub fn focus_self(&mut self) {
2699        self.app.pending_effects.push_back(Effect::Focus {
2700            window_id: self.window_id,
2701            view_id: Some(self.view_id),
2702        });
2703    }
2704
2705    pub fn blur(&mut self) {
2706        self.app.pending_effects.push_back(Effect::Focus {
2707            window_id: self.window_id,
2708            view_id: None,
2709        });
2710    }
2711
2712    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2713    where
2714        S: Entity,
2715        F: FnOnce(&mut ModelContext<S>) -> S,
2716    {
2717        self.app.add_model(build_model)
2718    }
2719
2720    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
2721    where
2722        S: View,
2723        F: FnOnce(&mut ViewContext<S>) -> S,
2724    {
2725        self.app.add_view(self.window_id, build_view)
2726    }
2727
2728    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
2729    where
2730        S: View,
2731        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
2732    {
2733        self.app.add_option_view(self.window_id, build_view)
2734    }
2735
2736    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
2737    where
2738        E: Entity,
2739        E::Event: 'static,
2740        H: Handle<E>,
2741        F: 'static + FnMut(&mut T, H, &E::Event, &mut ViewContext<T>),
2742    {
2743        let subscriber = self.weak_handle();
2744        self.app
2745            .subscribe_internal(handle, move |emitter, event, cx| {
2746                if let Some(subscriber) = subscriber.upgrade(cx) {
2747                    subscriber.update(cx, |subscriber, cx| {
2748                        callback(subscriber, emitter, event, cx);
2749                    });
2750                    true
2751                } else {
2752                    false
2753                }
2754            })
2755    }
2756
2757    pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2758    where
2759        E: Entity,
2760        H: Handle<E>,
2761        F: 'static + FnMut(&mut T, H, &mut ViewContext<T>),
2762    {
2763        let observer = self.weak_handle();
2764        self.app.observe_internal(handle, move |observed, cx| {
2765            if let Some(observer) = observer.upgrade(cx) {
2766                observer.update(cx, |observer, cx| {
2767                    callback(observer, observed, cx);
2768                });
2769                true
2770            } else {
2771                false
2772            }
2773        })
2774    }
2775
2776    pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2777    where
2778        E: Entity,
2779        H: Handle<E>,
2780        F: 'static + FnMut(&mut T, &E, &mut ViewContext<T>),
2781    {
2782        let observer = self.weak_handle();
2783        self.app.observe_release(handle, move |released, cx| {
2784            if let Some(observer) = observer.upgrade(cx) {
2785                observer.update(cx, |observer, cx| {
2786                    callback(observer, released, cx);
2787                });
2788            }
2789        })
2790    }
2791
2792    pub fn emit(&mut self, payload: T::Event) {
2793        self.app.pending_effects.push_back(Effect::Event {
2794            entity_id: self.view_id,
2795            payload: Box::new(payload),
2796        });
2797    }
2798
2799    pub fn notify(&mut self) {
2800        self.app.notify_view(self.window_id, self.view_id);
2801    }
2802
2803    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>)) {
2804        let handle = self.handle();
2805        self.app.defer(Box::new(move |cx| {
2806            handle.update(cx, |view, cx| {
2807                callback(view, cx);
2808            })
2809        }))
2810    }
2811
2812    pub fn propagate_action(&mut self) {
2813        self.app.halt_action_dispatch = false;
2814    }
2815
2816    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2817    where
2818        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
2819        Fut: 'static + Future<Output = S>,
2820        S: 'static,
2821    {
2822        let handle = self.handle();
2823        self.app.spawn(|cx| f(handle, cx))
2824    }
2825
2826    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
2827    where
2828        F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut,
2829        Fut: 'static + Future<Output = S>,
2830        S: 'static,
2831    {
2832        let handle = self.weak_handle();
2833        self.app.spawn(|cx| f(handle, cx))
2834    }
2835}
2836
2837pub struct RenderContext<'a, T: View> {
2838    pub app: &'a mut MutableAppContext,
2839    pub titlebar_height: f32,
2840    pub refreshing: bool,
2841    window_id: usize,
2842    view_id: usize,
2843    view_type: PhantomData<T>,
2844}
2845
2846impl<'a, T: View> RenderContext<'a, T> {
2847    pub fn handle(&self) -> WeakViewHandle<T> {
2848        WeakViewHandle::new(self.window_id, self.view_id)
2849    }
2850
2851    pub fn view_id(&self) -> usize {
2852        self.view_id
2853    }
2854}
2855
2856impl AsRef<AppContext> for &AppContext {
2857    fn as_ref(&self) -> &AppContext {
2858        self
2859    }
2860}
2861
2862impl<V: View> Deref for RenderContext<'_, V> {
2863    type Target = MutableAppContext;
2864
2865    fn deref(&self) -> &Self::Target {
2866        self.app
2867    }
2868}
2869
2870impl<V: View> DerefMut for RenderContext<'_, V> {
2871    fn deref_mut(&mut self) -> &mut Self::Target {
2872        self.app
2873    }
2874}
2875
2876impl<V: View> ReadModel for RenderContext<'_, V> {
2877    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2878        self.app.read_model(handle)
2879    }
2880}
2881
2882impl<V: View> UpdateModel for RenderContext<'_, V> {
2883    fn update_model<T: Entity, O>(
2884        &mut self,
2885        handle: &ModelHandle<T>,
2886        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
2887    ) -> O {
2888        self.app.update_model(handle, update)
2889    }
2890}
2891
2892impl<V: View> ReadView for RenderContext<'_, V> {
2893    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2894        self.app.read_view(handle)
2895    }
2896}
2897
2898impl<V: View> ElementStateContext for RenderContext<'_, V> {
2899    fn current_view_id(&self) -> usize {
2900        self.view_id
2901    }
2902}
2903
2904impl<M> AsRef<AppContext> for ViewContext<'_, M> {
2905    fn as_ref(&self) -> &AppContext {
2906        &self.app.cx
2907    }
2908}
2909
2910impl<M> Deref for ViewContext<'_, M> {
2911    type Target = MutableAppContext;
2912
2913    fn deref(&self) -> &Self::Target {
2914        &self.app
2915    }
2916}
2917
2918impl<M> DerefMut for ViewContext<'_, M> {
2919    fn deref_mut(&mut self) -> &mut Self::Target {
2920        &mut self.app
2921    }
2922}
2923
2924impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
2925    fn as_mut(&mut self) -> &mut MutableAppContext {
2926        self.app
2927    }
2928}
2929
2930impl<V> ReadModel for ViewContext<'_, V> {
2931    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2932        self.app.read_model(handle)
2933    }
2934}
2935
2936impl<V> UpgradeModelHandle for ViewContext<'_, V> {
2937    fn upgrade_model_handle<T: Entity>(
2938        &self,
2939        handle: &WeakModelHandle<T>,
2940    ) -> Option<ModelHandle<T>> {
2941        self.cx.upgrade_model_handle(handle)
2942    }
2943
2944    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2945        self.cx.model_handle_is_upgradable(handle)
2946    }
2947
2948    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2949        self.cx.upgrade_any_model_handle(handle)
2950    }
2951}
2952
2953impl<V> UpgradeViewHandle for ViewContext<'_, V> {
2954    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2955        self.cx.upgrade_view_handle(handle)
2956    }
2957
2958    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
2959        self.cx.upgrade_any_view_handle(handle)
2960    }
2961}
2962
2963impl<V: View> UpdateModel for ViewContext<'_, V> {
2964    fn update_model<T: Entity, O>(
2965        &mut self,
2966        handle: &ModelHandle<T>,
2967        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
2968    ) -> O {
2969        self.app.update_model(handle, update)
2970    }
2971}
2972
2973impl<V: View> ReadView for ViewContext<'_, V> {
2974    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2975        self.app.read_view(handle)
2976    }
2977}
2978
2979impl<V: View> UpdateView for ViewContext<'_, V> {
2980    fn update_view<T, S>(
2981        &mut self,
2982        handle: &ViewHandle<T>,
2983        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
2984    ) -> S
2985    where
2986        T: View,
2987    {
2988        self.app.update_view(handle, update)
2989    }
2990}
2991
2992impl<V: View> ElementStateContext for ViewContext<'_, V> {
2993    fn current_view_id(&self) -> usize {
2994        self.view_id
2995    }
2996}
2997
2998pub trait Handle<T> {
2999    type Weak: 'static;
3000    fn id(&self) -> usize;
3001    fn location(&self) -> EntityLocation;
3002    fn downgrade(&self) -> Self::Weak;
3003    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3004    where
3005        Self: Sized;
3006}
3007
3008#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
3009pub enum EntityLocation {
3010    Model(usize),
3011    View(usize, usize),
3012}
3013
3014pub struct ModelHandle<T: Entity> {
3015    model_id: usize,
3016    model_type: PhantomData<T>,
3017    ref_counts: Arc<Mutex<RefCounts>>,
3018
3019    #[cfg(any(test, feature = "test-support"))]
3020    handle_id: usize,
3021}
3022
3023impl<T: Entity> ModelHandle<T> {
3024    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3025        ref_counts.lock().inc_model(model_id);
3026
3027        #[cfg(any(test, feature = "test-support"))]
3028        let handle_id = ref_counts
3029            .lock()
3030            .leak_detector
3031            .lock()
3032            .handle_created(Some(type_name::<T>()), model_id);
3033
3034        Self {
3035            model_id,
3036            model_type: PhantomData,
3037            ref_counts: ref_counts.clone(),
3038
3039            #[cfg(any(test, feature = "test-support"))]
3040            handle_id,
3041        }
3042    }
3043
3044    pub fn downgrade(&self) -> WeakModelHandle<T> {
3045        WeakModelHandle::new(self.model_id)
3046    }
3047
3048    pub fn id(&self) -> usize {
3049        self.model_id
3050    }
3051
3052    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
3053        cx.read_model(self)
3054    }
3055
3056    pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
3057    where
3058        C: ReadModelWith,
3059        F: FnOnce(&T, &AppContext) -> S,
3060    {
3061        let mut read = Some(read);
3062        cx.read_model_with(self, &mut |model, cx| {
3063            let read = read.take().unwrap();
3064            read(model, cx)
3065        })
3066    }
3067
3068    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3069    where
3070        C: UpdateModel,
3071        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
3072    {
3073        let mut update = Some(update);
3074        cx.update_model(self, &mut |model, cx| {
3075            let update = update.take().unwrap();
3076            update(model, cx)
3077        })
3078    }
3079
3080    #[cfg(any(test, feature = "test-support"))]
3081    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
3082        use postage::prelude::{Sink as _, Stream as _};
3083
3084        let (mut tx, mut rx) = postage::mpsc::channel(1);
3085        let mut cx = cx.cx.borrow_mut();
3086        let subscription = cx.observe(self, move |_, _| {
3087            tx.try_send(()).ok();
3088        });
3089
3090        let duration = if std::env::var("CI").is_ok() {
3091            Duration::from_secs(5)
3092        } else {
3093            Duration::from_secs(1)
3094        };
3095
3096        async move {
3097            let notification = crate::util::timeout(duration, rx.recv())
3098                .await
3099                .expect("next notification timed out");
3100            drop(subscription);
3101            notification.expect("model dropped while test was waiting for its next notification")
3102        }
3103    }
3104
3105    #[cfg(any(test, feature = "test-support"))]
3106    pub fn next_event(&self, cx: &TestAppContext) -> impl Future<Output = T::Event>
3107    where
3108        T::Event: Clone,
3109    {
3110        use postage::prelude::{Sink as _, Stream as _};
3111
3112        let (mut tx, mut rx) = postage::mpsc::channel(1);
3113        let mut cx = cx.cx.borrow_mut();
3114        let subscription = cx.subscribe(self, move |_, event, _| {
3115            tx.blocking_send(event.clone()).ok();
3116        });
3117
3118        let duration = if std::env::var("CI").is_ok() {
3119            Duration::from_secs(5)
3120        } else {
3121            Duration::from_secs(1)
3122        };
3123
3124        async move {
3125            let event = crate::util::timeout(duration, rx.recv())
3126                .await
3127                .expect("next event timed out");
3128            drop(subscription);
3129            event.expect("model dropped while test was waiting for its next event")
3130        }
3131    }
3132
3133    #[cfg(any(test, feature = "test-support"))]
3134    pub fn condition(
3135        &self,
3136        cx: &TestAppContext,
3137        mut predicate: impl FnMut(&T, &AppContext) -> bool,
3138    ) -> impl Future<Output = ()> {
3139        use postage::prelude::{Sink as _, Stream as _};
3140
3141        let (tx, mut rx) = postage::mpsc::channel(1024);
3142
3143        let mut cx = cx.cx.borrow_mut();
3144        let subscriptions = (
3145            cx.observe(self, {
3146                let mut tx = tx.clone();
3147                move |_, _| {
3148                    tx.blocking_send(()).ok();
3149                }
3150            }),
3151            cx.subscribe(self, {
3152                let mut tx = tx.clone();
3153                move |_, _, _| {
3154                    tx.blocking_send(()).ok();
3155                }
3156            }),
3157        );
3158
3159        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
3160        let handle = self.downgrade();
3161        let duration = if std::env::var("CI").is_ok() {
3162            Duration::from_secs(5)
3163        } else {
3164            Duration::from_secs(1)
3165        };
3166
3167        async move {
3168            crate::util::timeout(duration, async move {
3169                loop {
3170                    {
3171                        let cx = cx.borrow();
3172                        let cx = cx.as_ref();
3173                        if predicate(
3174                            handle
3175                                .upgrade(cx)
3176                                .expect("model dropped with pending condition")
3177                                .read(cx),
3178                            cx,
3179                        ) {
3180                            break;
3181                        }
3182                    }
3183
3184                    cx.borrow().foreground().start_waiting();
3185                    rx.recv()
3186                        .await
3187                        .expect("model dropped with pending condition");
3188                    cx.borrow().foreground().finish_waiting();
3189                }
3190            })
3191            .await
3192            .expect("condition timed out");
3193            drop(subscriptions);
3194        }
3195    }
3196}
3197
3198impl<T: Entity> Clone for ModelHandle<T> {
3199    fn clone(&self) -> Self {
3200        Self::new(self.model_id, &self.ref_counts)
3201    }
3202}
3203
3204impl<T: Entity> PartialEq for ModelHandle<T> {
3205    fn eq(&self, other: &Self) -> bool {
3206        self.model_id == other.model_id
3207    }
3208}
3209
3210impl<T: Entity> Eq for ModelHandle<T> {}
3211
3212impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
3213    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
3214        self.model_id == other.model_id
3215    }
3216}
3217
3218impl<T: Entity> Hash for ModelHandle<T> {
3219    fn hash<H: Hasher>(&self, state: &mut H) {
3220        self.model_id.hash(state);
3221    }
3222}
3223
3224impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
3225    fn borrow(&self) -> &usize {
3226        &self.model_id
3227    }
3228}
3229
3230impl<T: Entity> Debug for ModelHandle<T> {
3231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3232        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
3233            .field(&self.model_id)
3234            .finish()
3235    }
3236}
3237
3238unsafe impl<T: Entity> Send for ModelHandle<T> {}
3239unsafe impl<T: Entity> Sync for ModelHandle<T> {}
3240
3241impl<T: Entity> Drop for ModelHandle<T> {
3242    fn drop(&mut self) {
3243        let mut ref_counts = self.ref_counts.lock();
3244        ref_counts.dec_model(self.model_id);
3245
3246        #[cfg(any(test, feature = "test-support"))]
3247        ref_counts
3248            .leak_detector
3249            .lock()
3250            .handle_dropped(self.model_id, self.handle_id);
3251    }
3252}
3253
3254impl<T: Entity> Handle<T> for ModelHandle<T> {
3255    type Weak = WeakModelHandle<T>;
3256
3257    fn id(&self) -> usize {
3258        self.model_id
3259    }
3260
3261    fn location(&self) -> EntityLocation {
3262        EntityLocation::Model(self.model_id)
3263    }
3264
3265    fn downgrade(&self) -> Self::Weak {
3266        self.downgrade()
3267    }
3268
3269    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3270    where
3271        Self: Sized,
3272    {
3273        weak.upgrade(cx)
3274    }
3275}
3276
3277pub struct WeakModelHandle<T> {
3278    model_id: usize,
3279    model_type: PhantomData<T>,
3280}
3281
3282unsafe impl<T> Send for WeakModelHandle<T> {}
3283unsafe impl<T> Sync for WeakModelHandle<T> {}
3284
3285impl<T: Entity> WeakModelHandle<T> {
3286    fn new(model_id: usize) -> Self {
3287        Self {
3288            model_id,
3289            model_type: PhantomData,
3290        }
3291    }
3292
3293    pub fn id(&self) -> usize {
3294        self.model_id
3295    }
3296
3297    pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
3298        cx.model_handle_is_upgradable(self)
3299    }
3300
3301    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
3302        cx.upgrade_model_handle(self)
3303    }
3304}
3305
3306impl<T> Hash for WeakModelHandle<T> {
3307    fn hash<H: Hasher>(&self, state: &mut H) {
3308        self.model_id.hash(state)
3309    }
3310}
3311
3312impl<T> PartialEq for WeakModelHandle<T> {
3313    fn eq(&self, other: &Self) -> bool {
3314        self.model_id == other.model_id
3315    }
3316}
3317
3318impl<T> Eq for WeakModelHandle<T> {}
3319
3320impl<T> Clone for WeakModelHandle<T> {
3321    fn clone(&self) -> Self {
3322        Self {
3323            model_id: self.model_id,
3324            model_type: PhantomData,
3325        }
3326    }
3327}
3328
3329impl<T> Copy for WeakModelHandle<T> {}
3330
3331pub struct ViewHandle<T> {
3332    window_id: usize,
3333    view_id: usize,
3334    view_type: PhantomData<T>,
3335    ref_counts: Arc<Mutex<RefCounts>>,
3336    #[cfg(any(test, feature = "test-support"))]
3337    handle_id: usize,
3338}
3339
3340impl<T: View> ViewHandle<T> {
3341    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3342        ref_counts.lock().inc_view(window_id, view_id);
3343        #[cfg(any(test, feature = "test-support"))]
3344        let handle_id = ref_counts
3345            .lock()
3346            .leak_detector
3347            .lock()
3348            .handle_created(Some(type_name::<T>()), view_id);
3349
3350        Self {
3351            window_id,
3352            view_id,
3353            view_type: PhantomData,
3354            ref_counts: ref_counts.clone(),
3355
3356            #[cfg(any(test, feature = "test-support"))]
3357            handle_id,
3358        }
3359    }
3360
3361    pub fn downgrade(&self) -> WeakViewHandle<T> {
3362        WeakViewHandle::new(self.window_id, self.view_id)
3363    }
3364
3365    pub fn window_id(&self) -> usize {
3366        self.window_id
3367    }
3368
3369    pub fn id(&self) -> usize {
3370        self.view_id
3371    }
3372
3373    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
3374        cx.read_view(self)
3375    }
3376
3377    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3378    where
3379        C: ReadViewWith,
3380        F: FnOnce(&T, &AppContext) -> S,
3381    {
3382        let mut read = Some(read);
3383        cx.read_view_with(self, &mut |view, cx| {
3384            let read = read.take().unwrap();
3385            read(view, cx)
3386        })
3387    }
3388
3389    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3390    where
3391        C: UpdateView,
3392        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
3393    {
3394        let mut update = Some(update);
3395        cx.update_view(self, &mut |view, cx| {
3396            let update = update.take().unwrap();
3397            update(view, cx)
3398        })
3399    }
3400
3401    pub fn defer<C, F>(&self, cx: &mut C, update: F)
3402    where
3403        C: AsMut<MutableAppContext>,
3404        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
3405    {
3406        let this = self.clone();
3407        cx.as_mut().defer(Box::new(move |cx| {
3408            this.update(cx, |view, cx| update(view, cx));
3409        }));
3410    }
3411
3412    pub fn is_focused(&self, cx: &AppContext) -> bool {
3413        cx.focused_view_id(self.window_id)
3414            .map_or(false, |focused_id| focused_id == self.view_id)
3415    }
3416
3417    #[cfg(any(test, feature = "test-support"))]
3418    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
3419        use postage::prelude::{Sink as _, Stream as _};
3420
3421        let (mut tx, mut rx) = postage::mpsc::channel(1);
3422        let mut cx = cx.cx.borrow_mut();
3423        let subscription = cx.observe(self, move |_, _| {
3424            tx.try_send(()).ok();
3425        });
3426
3427        let duration = if std::env::var("CI").is_ok() {
3428            Duration::from_secs(5)
3429        } else {
3430            Duration::from_secs(1)
3431        };
3432
3433        async move {
3434            let notification = crate::util::timeout(duration, rx.recv())
3435                .await
3436                .expect("next notification timed out");
3437            drop(subscription);
3438            notification.expect("model dropped while test was waiting for its next notification")
3439        }
3440    }
3441
3442    #[cfg(any(test, feature = "test-support"))]
3443    pub fn condition(
3444        &self,
3445        cx: &TestAppContext,
3446        mut predicate: impl FnMut(&T, &AppContext) -> bool,
3447    ) -> impl Future<Output = ()> {
3448        use postage::prelude::{Sink as _, Stream as _};
3449
3450        let (tx, mut rx) = postage::mpsc::channel(1024);
3451
3452        let mut cx = cx.cx.borrow_mut();
3453        let subscriptions = self.update(&mut *cx, |_, cx| {
3454            (
3455                cx.observe(self, {
3456                    let mut tx = tx.clone();
3457                    move |_, _, _| {
3458                        tx.blocking_send(()).ok();
3459                    }
3460                }),
3461                cx.subscribe(self, {
3462                    let mut tx = tx.clone();
3463                    move |_, _, _, _| {
3464                        tx.blocking_send(()).ok();
3465                    }
3466                }),
3467            )
3468        });
3469
3470        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
3471        let handle = self.downgrade();
3472        let duration = if std::env::var("CI").is_ok() {
3473            Duration::from_secs(2)
3474        } else {
3475            Duration::from_millis(500)
3476        };
3477
3478        async move {
3479            crate::util::timeout(duration, async move {
3480                loop {
3481                    {
3482                        let cx = cx.borrow();
3483                        let cx = cx.as_ref();
3484                        if predicate(
3485                            handle
3486                                .upgrade(cx)
3487                                .expect("view dropped with pending condition")
3488                                .read(cx),
3489                            cx,
3490                        ) {
3491                            break;
3492                        }
3493                    }
3494
3495                    cx.borrow().foreground().start_waiting();
3496                    rx.recv()
3497                        .await
3498                        .expect("view dropped with pending condition");
3499                    cx.borrow().foreground().finish_waiting();
3500                }
3501            })
3502            .await
3503            .expect("condition timed out");
3504            drop(subscriptions);
3505        }
3506    }
3507}
3508
3509impl<T: View> Clone for ViewHandle<T> {
3510    fn clone(&self) -> Self {
3511        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
3512    }
3513}
3514
3515impl<T> PartialEq for ViewHandle<T> {
3516    fn eq(&self, other: &Self) -> bool {
3517        self.window_id == other.window_id && self.view_id == other.view_id
3518    }
3519}
3520
3521impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
3522    fn eq(&self, other: &WeakViewHandle<T>) -> bool {
3523        self.window_id == other.window_id && self.view_id == other.view_id
3524    }
3525}
3526
3527impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
3528    fn eq(&self, other: &ViewHandle<T>) -> bool {
3529        self.window_id == other.window_id && self.view_id == other.view_id
3530    }
3531}
3532
3533impl<T> Eq for ViewHandle<T> {}
3534
3535impl<T> Debug for ViewHandle<T> {
3536    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3537        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
3538            .field("window_id", &self.window_id)
3539            .field("view_id", &self.view_id)
3540            .finish()
3541    }
3542}
3543
3544impl<T> Drop for ViewHandle<T> {
3545    fn drop(&mut self) {
3546        self.ref_counts
3547            .lock()
3548            .dec_view(self.window_id, self.view_id);
3549        #[cfg(any(test, feature = "test-support"))]
3550        self.ref_counts
3551            .lock()
3552            .leak_detector
3553            .lock()
3554            .handle_dropped(self.view_id, self.handle_id);
3555    }
3556}
3557
3558impl<T: View> Handle<T> for ViewHandle<T> {
3559    type Weak = WeakViewHandle<T>;
3560
3561    fn id(&self) -> usize {
3562        self.view_id
3563    }
3564
3565    fn location(&self) -> EntityLocation {
3566        EntityLocation::View(self.window_id, self.view_id)
3567    }
3568
3569    fn downgrade(&self) -> Self::Weak {
3570        self.downgrade()
3571    }
3572
3573    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3574    where
3575        Self: Sized,
3576    {
3577        weak.upgrade(cx)
3578    }
3579}
3580
3581pub struct AnyViewHandle {
3582    window_id: usize,
3583    view_id: usize,
3584    view_type: TypeId,
3585    ref_counts: Arc<Mutex<RefCounts>>,
3586
3587    #[cfg(any(test, feature = "test-support"))]
3588    handle_id: usize,
3589}
3590
3591impl AnyViewHandle {
3592    fn new(
3593        window_id: usize,
3594        view_id: usize,
3595        view_type: TypeId,
3596        ref_counts: Arc<Mutex<RefCounts>>,
3597    ) -> Self {
3598        ref_counts.lock().inc_view(window_id, view_id);
3599
3600        #[cfg(any(test, feature = "test-support"))]
3601        let handle_id = ref_counts
3602            .lock()
3603            .leak_detector
3604            .lock()
3605            .handle_created(None, view_id);
3606
3607        Self {
3608            window_id,
3609            view_id,
3610            view_type,
3611            ref_counts,
3612            #[cfg(any(test, feature = "test-support"))]
3613            handle_id,
3614        }
3615    }
3616
3617    pub fn id(&self) -> usize {
3618        self.view_id
3619    }
3620
3621    pub fn is<T: 'static>(&self) -> bool {
3622        TypeId::of::<T>() == self.view_type
3623    }
3624
3625    pub fn is_focused(&self, cx: &AppContext) -> bool {
3626        cx.focused_view_id(self.window_id)
3627            .map_or(false, |focused_id| focused_id == self.view_id)
3628    }
3629
3630    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
3631        if self.is::<T>() {
3632            let result = Some(ViewHandle {
3633                window_id: self.window_id,
3634                view_id: self.view_id,
3635                ref_counts: self.ref_counts.clone(),
3636                view_type: PhantomData,
3637                #[cfg(any(test, feature = "test-support"))]
3638                handle_id: self.handle_id,
3639            });
3640            unsafe {
3641                Arc::decrement_strong_count(&self.ref_counts);
3642            }
3643            std::mem::forget(self);
3644            result
3645        } else {
3646            None
3647        }
3648    }
3649
3650    pub fn downgrade(&self) -> AnyWeakViewHandle {
3651        AnyWeakViewHandle {
3652            window_id: self.window_id,
3653            view_id: self.view_id,
3654            view_type: self.view_type,
3655        }
3656    }
3657}
3658
3659impl Clone for AnyViewHandle {
3660    fn clone(&self) -> Self {
3661        Self::new(
3662            self.window_id,
3663            self.view_id,
3664            self.view_type,
3665            self.ref_counts.clone(),
3666        )
3667    }
3668}
3669
3670impl From<&AnyViewHandle> for AnyViewHandle {
3671    fn from(handle: &AnyViewHandle) -> Self {
3672        handle.clone()
3673    }
3674}
3675
3676impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
3677    fn from(handle: &ViewHandle<T>) -> Self {
3678        Self::new(
3679            handle.window_id,
3680            handle.view_id,
3681            TypeId::of::<T>(),
3682            handle.ref_counts.clone(),
3683        )
3684    }
3685}
3686
3687impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
3688    fn from(handle: ViewHandle<T>) -> Self {
3689        let any_handle = AnyViewHandle {
3690            window_id: handle.window_id,
3691            view_id: handle.view_id,
3692            view_type: TypeId::of::<T>(),
3693            ref_counts: handle.ref_counts.clone(),
3694            #[cfg(any(test, feature = "test-support"))]
3695            handle_id: handle.handle_id,
3696        };
3697        unsafe {
3698            Arc::decrement_strong_count(&handle.ref_counts);
3699        }
3700        std::mem::forget(handle);
3701        any_handle
3702    }
3703}
3704
3705impl Drop for AnyViewHandle {
3706    fn drop(&mut self) {
3707        self.ref_counts
3708            .lock()
3709            .dec_view(self.window_id, self.view_id);
3710        #[cfg(any(test, feature = "test-support"))]
3711        self.ref_counts
3712            .lock()
3713            .leak_detector
3714            .lock()
3715            .handle_dropped(self.view_id, self.handle_id);
3716    }
3717}
3718
3719pub struct AnyModelHandle {
3720    model_id: usize,
3721    model_type: TypeId,
3722    ref_counts: Arc<Mutex<RefCounts>>,
3723
3724    #[cfg(any(test, feature = "test-support"))]
3725    handle_id: usize,
3726}
3727
3728impl AnyModelHandle {
3729    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
3730        ref_counts.lock().inc_model(model_id);
3731
3732        #[cfg(any(test, feature = "test-support"))]
3733        let handle_id = ref_counts
3734            .lock()
3735            .leak_detector
3736            .lock()
3737            .handle_created(None, model_id);
3738
3739        Self {
3740            model_id,
3741            model_type,
3742            ref_counts,
3743
3744            #[cfg(any(test, feature = "test-support"))]
3745            handle_id,
3746        }
3747    }
3748
3749    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
3750        if self.is::<T>() {
3751            let result = Some(ModelHandle {
3752                model_id: self.model_id,
3753                model_type: PhantomData,
3754                ref_counts: self.ref_counts.clone(),
3755
3756                #[cfg(any(test, feature = "test-support"))]
3757                handle_id: self.handle_id,
3758            });
3759            unsafe {
3760                Arc::decrement_strong_count(&self.ref_counts);
3761            }
3762            std::mem::forget(self);
3763            result
3764        } else {
3765            None
3766        }
3767    }
3768
3769    pub fn downgrade(&self) -> AnyWeakModelHandle {
3770        AnyWeakModelHandle {
3771            model_id: self.model_id,
3772            model_type: self.model_type,
3773        }
3774    }
3775
3776    pub fn is<T: Entity>(&self) -> bool {
3777        self.model_type == TypeId::of::<T>()
3778    }
3779
3780    pub fn model_type(&self) -> TypeId {
3781        self.model_type
3782    }
3783}
3784
3785impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
3786    fn from(handle: ModelHandle<T>) -> Self {
3787        Self::new(
3788            handle.model_id,
3789            TypeId::of::<T>(),
3790            handle.ref_counts.clone(),
3791        )
3792    }
3793}
3794
3795impl Clone for AnyModelHandle {
3796    fn clone(&self) -> Self {
3797        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
3798    }
3799}
3800
3801impl Drop for AnyModelHandle {
3802    fn drop(&mut self) {
3803        let mut ref_counts = self.ref_counts.lock();
3804        ref_counts.dec_model(self.model_id);
3805
3806        #[cfg(any(test, feature = "test-support"))]
3807        ref_counts
3808            .leak_detector
3809            .lock()
3810            .handle_dropped(self.model_id, self.handle_id);
3811    }
3812}
3813
3814pub struct AnyWeakModelHandle {
3815    model_id: usize,
3816    model_type: TypeId,
3817}
3818
3819impl AnyWeakModelHandle {
3820    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
3821        cx.upgrade_any_model_handle(self)
3822    }
3823}
3824
3825impl<T: Entity> From<WeakModelHandle<T>> for AnyWeakModelHandle {
3826    fn from(handle: WeakModelHandle<T>) -> Self {
3827        AnyWeakModelHandle {
3828            model_id: handle.model_id,
3829            model_type: TypeId::of::<T>(),
3830        }
3831    }
3832}
3833
3834pub struct WeakViewHandle<T> {
3835    window_id: usize,
3836    view_id: usize,
3837    view_type: PhantomData<T>,
3838}
3839
3840impl<T: View> WeakViewHandle<T> {
3841    fn new(window_id: usize, view_id: usize) -> Self {
3842        Self {
3843            window_id,
3844            view_id,
3845            view_type: PhantomData,
3846        }
3847    }
3848
3849    pub fn id(&self) -> usize {
3850        self.view_id
3851    }
3852
3853    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
3854        cx.upgrade_view_handle(self)
3855    }
3856}
3857
3858impl<T> Clone for WeakViewHandle<T> {
3859    fn clone(&self) -> Self {
3860        Self {
3861            window_id: self.window_id,
3862            view_id: self.view_id,
3863            view_type: PhantomData,
3864        }
3865    }
3866}
3867
3868impl<T> PartialEq for WeakViewHandle<T> {
3869    fn eq(&self, other: &Self) -> bool {
3870        self.window_id == other.window_id && self.view_id == other.view_id
3871    }
3872}
3873
3874impl<T> Eq for WeakViewHandle<T> {}
3875
3876impl<T> Hash for WeakViewHandle<T> {
3877    fn hash<H: Hasher>(&self, state: &mut H) {
3878        self.window_id.hash(state);
3879        self.view_id.hash(state);
3880    }
3881}
3882
3883pub struct AnyWeakViewHandle {
3884    window_id: usize,
3885    view_id: usize,
3886    view_type: TypeId,
3887}
3888
3889impl AnyWeakViewHandle {
3890    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<AnyViewHandle> {
3891        cx.upgrade_any_view_handle(self)
3892    }
3893}
3894
3895impl<T: View> From<WeakViewHandle<T>> for AnyWeakViewHandle {
3896    fn from(handle: WeakViewHandle<T>) -> Self {
3897        AnyWeakViewHandle {
3898            window_id: handle.window_id,
3899            view_id: handle.view_id,
3900            view_type: TypeId::of::<T>(),
3901        }
3902    }
3903}
3904
3905#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3906pub struct ElementStateId {
3907    view_id: usize,
3908    element_id: usize,
3909    tag: TypeId,
3910}
3911
3912pub struct ElementStateHandle<T> {
3913    value_type: PhantomData<T>,
3914    id: ElementStateId,
3915    ref_counts: Weak<Mutex<RefCounts>>,
3916}
3917
3918impl<T: 'static> ElementStateHandle<T> {
3919    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3920        ref_counts.lock().inc_element_state(id, frame_id);
3921        Self {
3922            value_type: PhantomData,
3923            id,
3924            ref_counts: Arc::downgrade(ref_counts),
3925        }
3926    }
3927
3928    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3929        cx.element_states
3930            .get(&self.id)
3931            .unwrap()
3932            .downcast_ref()
3933            .unwrap()
3934    }
3935
3936    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
3937    where
3938        C: DerefMut<Target = MutableAppContext>,
3939    {
3940        let mut element_state = cx.deref_mut().cx.element_states.remove(&self.id).unwrap();
3941        let result = f(element_state.downcast_mut().unwrap(), cx);
3942        cx.deref_mut()
3943            .cx
3944            .element_states
3945            .insert(self.id, element_state);
3946        result
3947    }
3948}
3949
3950impl<T> Drop for ElementStateHandle<T> {
3951    fn drop(&mut self) {
3952        if let Some(ref_counts) = self.ref_counts.upgrade() {
3953            ref_counts.lock().dec_element_state(self.id);
3954        }
3955    }
3956}
3957
3958pub struct CursorStyleHandle {
3959    id: usize,
3960    next_cursor_style_handle_id: Arc<AtomicUsize>,
3961    platform: Arc<dyn Platform>,
3962}
3963
3964impl Drop for CursorStyleHandle {
3965    fn drop(&mut self) {
3966        if self.id + 1 == self.next_cursor_style_handle_id.load(SeqCst) {
3967            self.platform.set_cursor_style(CursorStyle::Arrow);
3968        }
3969    }
3970}
3971
3972#[must_use]
3973pub enum Subscription {
3974    Subscription {
3975        id: usize,
3976        entity_id: usize,
3977        subscriptions:
3978            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, Option<SubscriptionCallback>>>>>>,
3979    },
3980    GlobalSubscription {
3981        id: usize,
3982        type_id: TypeId,
3983        subscriptions: Option<
3984            Weak<Mutex<HashMap<TypeId, BTreeMap<usize, Option<GlobalSubscriptionCallback>>>>>,
3985        >,
3986    },
3987    Observation {
3988        id: usize,
3989        entity_id: usize,
3990        observations:
3991            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, Option<ObservationCallback>>>>>>,
3992    },
3993    ReleaseObservation {
3994        id: usize,
3995        entity_id: usize,
3996        observations:
3997            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>>,
3998    },
3999}
4000
4001impl Subscription {
4002    pub fn detach(&mut self) {
4003        match self {
4004            Subscription::Subscription { subscriptions, .. } => {
4005                subscriptions.take();
4006            }
4007            Subscription::GlobalSubscription { subscriptions, .. } => {
4008                subscriptions.take();
4009            }
4010            Subscription::Observation { observations, .. } => {
4011                observations.take();
4012            }
4013            Subscription::ReleaseObservation { observations, .. } => {
4014                observations.take();
4015            }
4016        }
4017    }
4018}
4019
4020impl Drop for Subscription {
4021    fn drop(&mut self) {
4022        match self {
4023            Subscription::Subscription {
4024                id,
4025                entity_id,
4026                subscriptions,
4027            } => {
4028                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
4029                    match subscriptions
4030                        .lock()
4031                        .entry(*entity_id)
4032                        .or_default()
4033                        .entry(*id)
4034                    {
4035                        collections::btree_map::Entry::Vacant(entry) => {
4036                            entry.insert(None);
4037                        }
4038                        collections::btree_map::Entry::Occupied(entry) => {
4039                            entry.remove();
4040                        }
4041                    }
4042                }
4043            }
4044            Subscription::GlobalSubscription {
4045                id,
4046                type_id,
4047                subscriptions,
4048            } => {
4049                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
4050                    match subscriptions.lock().entry(*type_id).or_default().entry(*id) {
4051                        collections::btree_map::Entry::Vacant(entry) => {
4052                            entry.insert(None);
4053                        }
4054                        collections::btree_map::Entry::Occupied(entry) => {
4055                            entry.remove();
4056                        }
4057                    }
4058                }
4059            }
4060            Subscription::Observation {
4061                id,
4062                entity_id,
4063                observations,
4064            } => {
4065                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4066                    match observations
4067                        .lock()
4068                        .entry(*entity_id)
4069                        .or_default()
4070                        .entry(*id)
4071                    {
4072                        collections::btree_map::Entry::Vacant(entry) => {
4073                            entry.insert(None);
4074                        }
4075                        collections::btree_map::Entry::Occupied(entry) => {
4076                            entry.remove();
4077                        }
4078                    }
4079                }
4080            }
4081            Subscription::ReleaseObservation {
4082                id,
4083                entity_id,
4084                observations,
4085            } => {
4086                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4087                    if let Some(observations) = observations.lock().get_mut(entity_id) {
4088                        observations.remove(id);
4089                    }
4090                }
4091            }
4092        }
4093    }
4094}
4095
4096lazy_static! {
4097    static ref LEAK_BACKTRACE: bool =
4098        std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty());
4099}
4100
4101#[cfg(any(test, feature = "test-support"))]
4102#[derive(Default)]
4103pub struct LeakDetector {
4104    next_handle_id: usize,
4105    handle_backtraces: HashMap<
4106        usize,
4107        (
4108            Option<&'static str>,
4109            HashMap<usize, Option<backtrace::Backtrace>>,
4110        ),
4111    >,
4112}
4113
4114#[cfg(any(test, feature = "test-support"))]
4115impl LeakDetector {
4116    fn handle_created(&mut self, type_name: Option<&'static str>, entity_id: usize) -> usize {
4117        let handle_id = post_inc(&mut self.next_handle_id);
4118        let entry = self.handle_backtraces.entry(entity_id).or_default();
4119        let backtrace = if *LEAK_BACKTRACE {
4120            Some(backtrace::Backtrace::new_unresolved())
4121        } else {
4122            None
4123        };
4124        if let Some(type_name) = type_name {
4125            entry.0.get_or_insert(type_name);
4126        }
4127        entry.1.insert(handle_id, backtrace);
4128        handle_id
4129    }
4130
4131    fn handle_dropped(&mut self, entity_id: usize, handle_id: usize) {
4132        if let Some((_, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
4133            assert!(backtraces.remove(&handle_id).is_some());
4134            if backtraces.is_empty() {
4135                self.handle_backtraces.remove(&entity_id);
4136            }
4137        }
4138    }
4139
4140    pub fn detect(&mut self) {
4141        let mut found_leaks = false;
4142        for (id, (type_name, backtraces)) in self.handle_backtraces.iter_mut() {
4143            eprintln!(
4144                "leaked {} handles to {:?} {}",
4145                backtraces.len(),
4146                type_name.unwrap_or("entity"),
4147                id
4148            );
4149            for trace in backtraces.values_mut() {
4150                if let Some(trace) = trace {
4151                    trace.resolve();
4152                    eprintln!("{:?}", crate::util::CwdBacktrace(trace));
4153                }
4154            }
4155            found_leaks = true;
4156        }
4157
4158        let hint = if *LEAK_BACKTRACE {
4159            ""
4160        } else {
4161            " – set LEAK_BACKTRACE=1 for more information"
4162        };
4163        assert!(!found_leaks, "detected leaked handles{}", hint);
4164    }
4165}
4166
4167#[derive(Default)]
4168struct RefCounts {
4169    entity_counts: HashMap<usize, usize>,
4170    element_state_counts: HashMap<ElementStateId, ElementStateRefCount>,
4171    dropped_models: HashSet<usize>,
4172    dropped_views: HashSet<(usize, usize)>,
4173    dropped_element_states: HashSet<ElementStateId>,
4174
4175    #[cfg(any(test, feature = "test-support"))]
4176    leak_detector: Arc<Mutex<LeakDetector>>,
4177}
4178
4179struct ElementStateRefCount {
4180    ref_count: usize,
4181    frame_id: usize,
4182}
4183
4184impl RefCounts {
4185    fn inc_model(&mut self, model_id: usize) {
4186        match self.entity_counts.entry(model_id) {
4187            Entry::Occupied(mut entry) => {
4188                *entry.get_mut() += 1;
4189            }
4190            Entry::Vacant(entry) => {
4191                entry.insert(1);
4192                self.dropped_models.remove(&model_id);
4193            }
4194        }
4195    }
4196
4197    fn inc_view(&mut self, window_id: usize, view_id: usize) {
4198        match self.entity_counts.entry(view_id) {
4199            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
4200            Entry::Vacant(entry) => {
4201                entry.insert(1);
4202                self.dropped_views.remove(&(window_id, view_id));
4203            }
4204        }
4205    }
4206
4207    fn inc_element_state(&mut self, id: ElementStateId, frame_id: usize) {
4208        match self.element_state_counts.entry(id) {
4209            Entry::Occupied(mut entry) => {
4210                let entry = entry.get_mut();
4211                if entry.frame_id == frame_id || entry.ref_count >= 2 {
4212                    panic!("used the same element state more than once in the same frame");
4213                }
4214                entry.ref_count += 1;
4215                entry.frame_id = frame_id;
4216            }
4217            Entry::Vacant(entry) => {
4218                entry.insert(ElementStateRefCount {
4219                    ref_count: 1,
4220                    frame_id,
4221                });
4222                self.dropped_element_states.remove(&id);
4223            }
4224        }
4225    }
4226
4227    fn dec_model(&mut self, model_id: usize) {
4228        let count = self.entity_counts.get_mut(&model_id).unwrap();
4229        *count -= 1;
4230        if *count == 0 {
4231            self.entity_counts.remove(&model_id);
4232            self.dropped_models.insert(model_id);
4233        }
4234    }
4235
4236    fn dec_view(&mut self, window_id: usize, view_id: usize) {
4237        let count = self.entity_counts.get_mut(&view_id).unwrap();
4238        *count -= 1;
4239        if *count == 0 {
4240            self.entity_counts.remove(&view_id);
4241            self.dropped_views.insert((window_id, view_id));
4242        }
4243    }
4244
4245    fn dec_element_state(&mut self, id: ElementStateId) {
4246        let entry = self.element_state_counts.get_mut(&id).unwrap();
4247        entry.ref_count -= 1;
4248        if entry.ref_count == 0 {
4249            self.element_state_counts.remove(&id);
4250            self.dropped_element_states.insert(id);
4251        }
4252    }
4253
4254    fn is_entity_alive(&self, entity_id: usize) -> bool {
4255        self.entity_counts.contains_key(&entity_id)
4256    }
4257
4258    fn take_dropped(
4259        &mut self,
4260    ) -> (
4261        HashSet<usize>,
4262        HashSet<(usize, usize)>,
4263        HashSet<ElementStateId>,
4264    ) {
4265        (
4266            std::mem::take(&mut self.dropped_models),
4267            std::mem::take(&mut self.dropped_views),
4268            std::mem::take(&mut self.dropped_element_states),
4269        )
4270    }
4271}
4272
4273#[cfg(test)]
4274mod tests {
4275    use super::*;
4276    use crate::elements::*;
4277    use smol::future::poll_once;
4278    use std::{
4279        cell::Cell,
4280        sync::atomic::{AtomicUsize, Ordering::SeqCst},
4281    };
4282
4283    #[crate::test(self)]
4284    fn test_model_handles(cx: &mut MutableAppContext) {
4285        struct Model {
4286            other: Option<ModelHandle<Model>>,
4287            events: Vec<String>,
4288        }
4289
4290        impl Entity for Model {
4291            type Event = usize;
4292        }
4293
4294        impl Model {
4295            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
4296                if let Some(other) = other.as_ref() {
4297                    cx.observe(other, |me, _, _| {
4298                        me.events.push("notified".into());
4299                    })
4300                    .detach();
4301                    cx.subscribe(other, |me, _, event, _| {
4302                        me.events.push(format!("observed event {}", event));
4303                    })
4304                    .detach();
4305                }
4306
4307                Self {
4308                    other,
4309                    events: Vec::new(),
4310                }
4311            }
4312        }
4313
4314        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
4315        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
4316        assert_eq!(cx.cx.models.len(), 2);
4317
4318        handle_1.update(cx, |model, cx| {
4319            model.events.push("updated".into());
4320            cx.emit(1);
4321            cx.notify();
4322            cx.emit(2);
4323        });
4324        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4325        assert_eq!(
4326            handle_2.read(cx).events,
4327            vec![
4328                "observed event 1".to_string(),
4329                "notified".to_string(),
4330                "observed event 2".to_string(),
4331            ]
4332        );
4333
4334        handle_2.update(cx, |model, _| {
4335            drop(handle_1);
4336            model.other.take();
4337        });
4338
4339        assert_eq!(cx.cx.models.len(), 1);
4340        assert!(cx.subscriptions.lock().is_empty());
4341        assert!(cx.observations.lock().is_empty());
4342    }
4343
4344    #[crate::test(self)]
4345    fn test_model_events(cx: &mut MutableAppContext) {
4346        #[derive(Default)]
4347        struct Model {
4348            events: Vec<usize>,
4349        }
4350
4351        impl Entity for Model {
4352            type Event = usize;
4353        }
4354
4355        let handle_1 = cx.add_model(|_| Model::default());
4356        let handle_2 = cx.add_model(|_| Model::default());
4357        handle_1.update(cx, |_, cx| {
4358            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
4359                model.events.push(*event);
4360
4361                cx.subscribe(&emitter, |model, _, event, _| {
4362                    model.events.push(*event * 2);
4363                })
4364                .detach();
4365            })
4366            .detach();
4367        });
4368
4369        handle_2.update(cx, |_, c| c.emit(7));
4370        assert_eq!(handle_1.read(cx).events, vec![7]);
4371
4372        handle_2.update(cx, |_, c| c.emit(5));
4373        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4374    }
4375
4376    #[crate::test(self)]
4377    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
4378        #[derive(Default)]
4379        struct Model {
4380            count: usize,
4381            events: Vec<usize>,
4382        }
4383
4384        impl Entity for Model {
4385            type Event = ();
4386        }
4387
4388        let handle_1 = cx.add_model(|_| Model::default());
4389        let handle_2 = cx.add_model(|_| Model::default());
4390
4391        handle_1.update(cx, |_, c| {
4392            c.observe(&handle_2, move |model, observed, c| {
4393                model.events.push(observed.read(c).count);
4394                c.observe(&observed, |model, observed, c| {
4395                    model.events.push(observed.read(c).count * 2);
4396                })
4397                .detach();
4398            })
4399            .detach();
4400        });
4401
4402        handle_2.update(cx, |model, c| {
4403            model.count = 7;
4404            c.notify()
4405        });
4406        assert_eq!(handle_1.read(cx).events, vec![7]);
4407
4408        handle_2.update(cx, |model, c| {
4409            model.count = 5;
4410            c.notify()
4411        });
4412        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
4413    }
4414
4415    #[crate::test(self)]
4416    fn test_view_handles(cx: &mut MutableAppContext) {
4417        struct View {
4418            other: Option<ViewHandle<View>>,
4419            events: Vec<String>,
4420        }
4421
4422        impl Entity for View {
4423            type Event = usize;
4424        }
4425
4426        impl super::View for View {
4427            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4428                Empty::new().boxed()
4429            }
4430
4431            fn ui_name() -> &'static str {
4432                "View"
4433            }
4434        }
4435
4436        impl View {
4437            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
4438                if let Some(other) = other.as_ref() {
4439                    cx.subscribe(other, |me, _, event, _| {
4440                        me.events.push(format!("observed event {}", event));
4441                    })
4442                    .detach();
4443                }
4444                Self {
4445                    other,
4446                    events: Vec::new(),
4447                }
4448            }
4449        }
4450
4451        let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
4452        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
4453        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
4454        assert_eq!(cx.cx.views.len(), 3);
4455
4456        handle_1.update(cx, |view, cx| {
4457            view.events.push("updated".into());
4458            cx.emit(1);
4459            cx.emit(2);
4460        });
4461        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4462        assert_eq!(
4463            handle_2.read(cx).events,
4464            vec![
4465                "observed event 1".to_string(),
4466                "observed event 2".to_string(),
4467            ]
4468        );
4469
4470        handle_2.update(cx, |view, _| {
4471            drop(handle_1);
4472            view.other.take();
4473        });
4474
4475        assert_eq!(cx.cx.views.len(), 2);
4476        assert!(cx.subscriptions.lock().is_empty());
4477        assert!(cx.observations.lock().is_empty());
4478    }
4479
4480    #[crate::test(self)]
4481    fn test_add_window(cx: &mut MutableAppContext) {
4482        struct View {
4483            mouse_down_count: Arc<AtomicUsize>,
4484        }
4485
4486        impl Entity for View {
4487            type Event = ();
4488        }
4489
4490        impl super::View for View {
4491            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4492                let mouse_down_count = self.mouse_down_count.clone();
4493                EventHandler::new(Empty::new().boxed())
4494                    .on_mouse_down(move |_| {
4495                        mouse_down_count.fetch_add(1, SeqCst);
4496                        true
4497                    })
4498                    .boxed()
4499            }
4500
4501            fn ui_name() -> &'static str {
4502                "View"
4503            }
4504        }
4505
4506        let mouse_down_count = Arc::new(AtomicUsize::new(0));
4507        let (window_id, _) = cx.add_window(Default::default(), |_| View {
4508            mouse_down_count: mouse_down_count.clone(),
4509        });
4510        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
4511        // Ensure window's root element is in a valid lifecycle state.
4512        presenter.borrow_mut().dispatch_event(
4513            Event::LeftMouseDown {
4514                position: Default::default(),
4515                ctrl: false,
4516                alt: false,
4517                shift: false,
4518                cmd: false,
4519                click_count: 1,
4520            },
4521            cx,
4522        );
4523        assert_eq!(mouse_down_count.load(SeqCst), 1);
4524    }
4525
4526    #[crate::test(self)]
4527    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
4528        struct Model {
4529            released: Rc<Cell<bool>>,
4530        }
4531
4532        struct View {
4533            released: Rc<Cell<bool>>,
4534        }
4535
4536        impl Entity for Model {
4537            type Event = ();
4538
4539            fn release(&mut self, _: &mut MutableAppContext) {
4540                self.released.set(true);
4541            }
4542        }
4543
4544        impl Entity for View {
4545            type Event = ();
4546
4547            fn release(&mut self, _: &mut MutableAppContext) {
4548                self.released.set(true);
4549            }
4550        }
4551
4552        impl super::View for View {
4553            fn ui_name() -> &'static str {
4554                "View"
4555            }
4556
4557            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4558                Empty::new().boxed()
4559            }
4560        }
4561
4562        let model_released = Rc::new(Cell::new(false));
4563        let model_release_observed = Rc::new(Cell::new(false));
4564        let view_released = Rc::new(Cell::new(false));
4565        let view_release_observed = Rc::new(Cell::new(false));
4566
4567        let model = cx.add_model(|_| Model {
4568            released: model_released.clone(),
4569        });
4570        let (window_id, view) = cx.add_window(Default::default(), |_| View {
4571            released: view_released.clone(),
4572        });
4573        assert!(!model_released.get());
4574        assert!(!view_released.get());
4575
4576        cx.observe_release(&model, {
4577            let model_release_observed = model_release_observed.clone();
4578            move |_, _| model_release_observed.set(true)
4579        })
4580        .detach();
4581        cx.observe_release(&view, {
4582            let view_release_observed = view_release_observed.clone();
4583            move |_, _| view_release_observed.set(true)
4584        })
4585        .detach();
4586
4587        cx.update(move |_| {
4588            drop(model);
4589        });
4590        assert!(model_released.get());
4591        assert!(model_release_observed.get());
4592
4593        drop(view);
4594        cx.remove_window(window_id);
4595        assert!(view_released.get());
4596        assert!(view_release_observed.get());
4597    }
4598
4599    #[crate::test(self)]
4600    fn test_view_events(cx: &mut MutableAppContext) {
4601        #[derive(Default)]
4602        struct View {
4603            events: Vec<usize>,
4604        }
4605
4606        impl Entity for View {
4607            type Event = usize;
4608        }
4609
4610        impl super::View for View {
4611            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4612                Empty::new().boxed()
4613            }
4614
4615            fn ui_name() -> &'static str {
4616                "View"
4617            }
4618        }
4619
4620        struct Model;
4621
4622        impl Entity for Model {
4623            type Event = usize;
4624        }
4625
4626        let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
4627        let handle_2 = cx.add_view(window_id, |_| View::default());
4628        let handle_3 = cx.add_model(|_| Model);
4629
4630        handle_1.update(cx, |_, cx| {
4631            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
4632                me.events.push(*event);
4633
4634                cx.subscribe(&emitter, |me, _, event, _| {
4635                    me.events.push(*event * 2);
4636                })
4637                .detach();
4638            })
4639            .detach();
4640
4641            cx.subscribe(&handle_3, |me, _, event, _| {
4642                me.events.push(*event);
4643            })
4644            .detach();
4645        });
4646
4647        handle_2.update(cx, |_, c| c.emit(7));
4648        assert_eq!(handle_1.read(cx).events, vec![7]);
4649
4650        handle_2.update(cx, |_, c| c.emit(5));
4651        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4652
4653        handle_3.update(cx, |_, c| c.emit(9));
4654        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
4655    }
4656
4657    #[crate::test(self)]
4658    fn test_global_events(cx: &mut MutableAppContext) {
4659        #[derive(Clone, Debug, Eq, PartialEq)]
4660        struct GlobalEvent(u64);
4661
4662        let events = Rc::new(RefCell::new(Vec::new()));
4663        let first_subscription;
4664        let second_subscription;
4665
4666        {
4667            let events = events.clone();
4668            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
4669                events.borrow_mut().push(("First", e.clone()));
4670            });
4671        }
4672
4673        {
4674            let events = events.clone();
4675            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
4676                events.borrow_mut().push(("Second", e.clone()));
4677            });
4678        }
4679
4680        cx.update(|cx| {
4681            cx.emit_global(GlobalEvent(1));
4682            cx.emit_global(GlobalEvent(2));
4683        });
4684
4685        drop(first_subscription);
4686
4687        cx.update(|cx| {
4688            cx.emit_global(GlobalEvent(3));
4689        });
4690
4691        drop(second_subscription);
4692
4693        cx.update(|cx| {
4694            cx.emit_global(GlobalEvent(4));
4695        });
4696
4697        assert_eq!(
4698            &*events.borrow(),
4699            &[
4700                ("First", GlobalEvent(1)),
4701                ("Second", GlobalEvent(1)),
4702                ("First", GlobalEvent(2)),
4703                ("Second", GlobalEvent(2)),
4704                ("Second", GlobalEvent(3)),
4705            ]
4706        );
4707    }
4708
4709    #[crate::test(self)]
4710    fn test_global_nested_events(cx: &mut MutableAppContext) {
4711        #[derive(Clone, Debug, Eq, PartialEq)]
4712        struct GlobalEvent(u64);
4713
4714        let events = Rc::new(RefCell::new(Vec::new()));
4715
4716        {
4717            let events = events.clone();
4718            cx.subscribe_global(move |e: &GlobalEvent, cx| {
4719                events.borrow_mut().push(("Outer", e.clone()));
4720
4721                let events = events.clone();
4722                cx.subscribe_global(move |e: &GlobalEvent, _| {
4723                    events.borrow_mut().push(("Inner", e.clone()));
4724                })
4725                .detach();
4726            })
4727            .detach();
4728        }
4729
4730        cx.update(|cx| {
4731            cx.emit_global(GlobalEvent(1));
4732            cx.emit_global(GlobalEvent(2));
4733            cx.emit_global(GlobalEvent(3));
4734        });
4735
4736        assert_eq!(
4737            &*events.borrow(),
4738            &[
4739                ("Outer", GlobalEvent(1)),
4740                ("Outer", GlobalEvent(2)),
4741                ("Inner", GlobalEvent(2)),
4742                ("Outer", GlobalEvent(3)),
4743                ("Inner", GlobalEvent(3)),
4744                ("Inner", GlobalEvent(3)),
4745            ]
4746        );
4747    }
4748
4749    #[crate::test(self)]
4750    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
4751        struct View;
4752
4753        impl Entity for View {
4754            type Event = ();
4755        }
4756
4757        impl super::View for View {
4758            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4759                Empty::new().boxed()
4760            }
4761
4762            fn ui_name() -> &'static str {
4763                "View"
4764            }
4765        }
4766
4767        struct Model;
4768
4769        impl Entity for Model {
4770            type Event = ();
4771        }
4772
4773        let (window_id, _) = cx.add_window(Default::default(), |_| View);
4774        let observing_view = cx.add_view(window_id, |_| View);
4775        let emitting_view = cx.add_view(window_id, |_| View);
4776        let observing_model = cx.add_model(|_| Model);
4777        let observed_model = cx.add_model(|_| Model);
4778
4779        observing_view.update(cx, |_, cx| {
4780            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
4781            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4782        });
4783        observing_model.update(cx, |_, cx| {
4784            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4785        });
4786
4787        cx.update(|_| {
4788            drop(observing_view);
4789            drop(observing_model);
4790        });
4791
4792        emitting_view.update(cx, |_, cx| cx.emit(()));
4793        observed_model.update(cx, |_, cx| cx.emit(()));
4794    }
4795
4796    #[crate::test(self)]
4797    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
4798        #[derive(Default)]
4799        struct View {
4800            events: Vec<usize>,
4801        }
4802
4803        impl Entity for View {
4804            type Event = usize;
4805        }
4806
4807        impl super::View for View {
4808            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4809                Empty::new().boxed()
4810            }
4811
4812            fn ui_name() -> &'static str {
4813                "View"
4814            }
4815        }
4816
4817        #[derive(Default)]
4818        struct Model {
4819            count: usize,
4820        }
4821
4822        impl Entity for Model {
4823            type Event = ();
4824        }
4825
4826        let (_, view) = cx.add_window(Default::default(), |_| View::default());
4827        let model = cx.add_model(|_| Model::default());
4828
4829        view.update(cx, |_, c| {
4830            c.observe(&model, |me, observed, c| {
4831                me.events.push(observed.read(c).count)
4832            })
4833            .detach();
4834        });
4835
4836        model.update(cx, |model, c| {
4837            model.count = 11;
4838            c.notify();
4839        });
4840        assert_eq!(view.read(cx).events, vec![11]);
4841    }
4842
4843    #[crate::test(self)]
4844    fn test_dropping_observers(cx: &mut MutableAppContext) {
4845        struct View;
4846
4847        impl Entity for View {
4848            type Event = ();
4849        }
4850
4851        impl super::View for View {
4852            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4853                Empty::new().boxed()
4854            }
4855
4856            fn ui_name() -> &'static str {
4857                "View"
4858            }
4859        }
4860
4861        struct Model;
4862
4863        impl Entity for Model {
4864            type Event = ();
4865        }
4866
4867        let (window_id, _) = cx.add_window(Default::default(), |_| View);
4868        let observing_view = cx.add_view(window_id, |_| View);
4869        let observing_model = cx.add_model(|_| Model);
4870        let observed_model = cx.add_model(|_| Model);
4871
4872        observing_view.update(cx, |_, cx| {
4873            cx.observe(&observed_model, |_, _, _| {}).detach();
4874        });
4875        observing_model.update(cx, |_, cx| {
4876            cx.observe(&observed_model, |_, _, _| {}).detach();
4877        });
4878
4879        cx.update(|_| {
4880            drop(observing_view);
4881            drop(observing_model);
4882        });
4883
4884        observed_model.update(cx, |_, cx| cx.notify());
4885    }
4886
4887    #[crate::test(self)]
4888    fn test_dropping_subscriptions_during_callback(cx: &mut MutableAppContext) {
4889        struct Model;
4890
4891        impl Entity for Model {
4892            type Event = u64;
4893        }
4894
4895        // Events
4896        let observing_model = cx.add_model(|_| Model);
4897        let observed_model = cx.add_model(|_| Model);
4898
4899        let events = Rc::new(RefCell::new(Vec::new()));
4900
4901        observing_model.update(cx, |_, cx| {
4902            let events = events.clone();
4903            let subscription = Rc::new(RefCell::new(None));
4904            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
4905                let subscription = subscription.clone();
4906                move |_, _, e, _| {
4907                    subscription.borrow_mut().take();
4908                    events.borrow_mut().push(e.clone());
4909                }
4910            }));
4911        });
4912
4913        observed_model.update(cx, |_, cx| {
4914            cx.emit(1);
4915            cx.emit(2);
4916        });
4917
4918        assert_eq!(*events.borrow(), [1]);
4919
4920        // Global Events
4921        #[derive(Clone, Debug, Eq, PartialEq)]
4922        struct GlobalEvent(u64);
4923
4924        let events = Rc::new(RefCell::new(Vec::new()));
4925
4926        {
4927            let events = events.clone();
4928            let subscription = Rc::new(RefCell::new(None));
4929            *subscription.borrow_mut() = Some(cx.subscribe_global({
4930                let subscription = subscription.clone();
4931                move |e: &GlobalEvent, _| {
4932                    subscription.borrow_mut().take();
4933                    events.borrow_mut().push(e.clone());
4934                }
4935            }));
4936        }
4937
4938        cx.update(|cx| {
4939            cx.emit_global(GlobalEvent(1));
4940            cx.emit_global(GlobalEvent(2));
4941        });
4942
4943        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
4944
4945        // Model Observation
4946        let observing_model = cx.add_model(|_| Model);
4947        let observed_model = cx.add_model(|_| Model);
4948
4949        let observation_count = Rc::new(RefCell::new(0));
4950
4951        observing_model.update(cx, |_, cx| {
4952            let observation_count = observation_count.clone();
4953            let subscription = Rc::new(RefCell::new(None));
4954            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
4955                let subscription = subscription.clone();
4956                move |_, _, _| {
4957                    subscription.borrow_mut().take();
4958                    *observation_count.borrow_mut() += 1;
4959                }
4960            }));
4961        });
4962
4963        observed_model.update(cx, |_, cx| {
4964            cx.notify();
4965        });
4966
4967        observed_model.update(cx, |_, cx| {
4968            cx.notify();
4969        });
4970
4971        assert_eq!(*observation_count.borrow(), 1);
4972
4973        // View Observation
4974        struct View;
4975
4976        impl Entity for View {
4977            type Event = ();
4978        }
4979
4980        impl super::View for View {
4981            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4982                Empty::new().boxed()
4983            }
4984
4985            fn ui_name() -> &'static str {
4986                "View"
4987            }
4988        }
4989
4990        let (window_id, _) = cx.add_window(Default::default(), |_| View);
4991        let observing_view = cx.add_view(window_id, |_| View);
4992        let observed_view = cx.add_view(window_id, |_| View);
4993
4994        let observation_count = Rc::new(RefCell::new(0));
4995        observing_view.update(cx, |_, cx| {
4996            let observation_count = observation_count.clone();
4997            let subscription = Rc::new(RefCell::new(None));
4998            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
4999                let subscription = subscription.clone();
5000                move |_, _, _| {
5001                    subscription.borrow_mut().take();
5002                    *observation_count.borrow_mut() += 1;
5003                }
5004            }));
5005        });
5006
5007        observed_view.update(cx, |_, cx| {
5008            cx.notify();
5009        });
5010
5011        observed_view.update(cx, |_, cx| {
5012            cx.notify();
5013        });
5014
5015        assert_eq!(*observation_count.borrow(), 1);
5016    }
5017
5018    #[crate::test(self)]
5019    fn test_focus(cx: &mut MutableAppContext) {
5020        struct View {
5021            name: String,
5022            events: Arc<Mutex<Vec<String>>>,
5023        }
5024
5025        impl Entity for View {
5026            type Event = ();
5027        }
5028
5029        impl super::View for View {
5030            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5031                Empty::new().boxed()
5032            }
5033
5034            fn ui_name() -> &'static str {
5035                "View"
5036            }
5037
5038            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
5039                self.events.lock().push(format!("{} focused", &self.name));
5040            }
5041
5042            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
5043                self.events.lock().push(format!("{} blurred", &self.name));
5044            }
5045        }
5046
5047        let events: Arc<Mutex<Vec<String>>> = Default::default();
5048        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
5049            events: events.clone(),
5050            name: "view 1".to_string(),
5051        });
5052        let view_2 = cx.add_view(window_id, |_| View {
5053            events: events.clone(),
5054            name: "view 2".to_string(),
5055        });
5056
5057        view_1.update(cx, |_, cx| cx.focus(&view_2));
5058        view_1.update(cx, |_, cx| cx.focus(&view_1));
5059        view_1.update(cx, |_, cx| cx.focus(&view_2));
5060        view_1.update(cx, |_, _| drop(view_2));
5061
5062        assert_eq!(
5063            *events.lock(),
5064            [
5065                "view 1 focused".to_string(),
5066                "view 1 blurred".to_string(),
5067                "view 2 focused".to_string(),
5068                "view 2 blurred".to_string(),
5069                "view 1 focused".to_string(),
5070                "view 1 blurred".to_string(),
5071                "view 2 focused".to_string(),
5072                "view 1 focused".to_string(),
5073            ],
5074        );
5075    }
5076
5077    #[crate::test(self)]
5078    fn test_dispatch_action(cx: &mut MutableAppContext) {
5079        struct ViewA {
5080            id: usize,
5081        }
5082
5083        impl Entity for ViewA {
5084            type Event = ();
5085        }
5086
5087        impl View for ViewA {
5088            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5089                Empty::new().boxed()
5090            }
5091
5092            fn ui_name() -> &'static str {
5093                "View"
5094            }
5095        }
5096
5097        struct ViewB {
5098            id: usize,
5099        }
5100
5101        impl Entity for ViewB {
5102            type Event = ();
5103        }
5104
5105        impl View for ViewB {
5106            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5107                Empty::new().boxed()
5108            }
5109
5110            fn ui_name() -> &'static str {
5111                "View"
5112            }
5113        }
5114
5115        action!(Action, &'static str);
5116
5117        let actions = Rc::new(RefCell::new(Vec::new()));
5118
5119        {
5120            let actions = actions.clone();
5121            cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
5122                actions.borrow_mut().push("global".to_string());
5123            });
5124        }
5125
5126        {
5127            let actions = actions.clone();
5128            cx.add_action(move |view: &mut ViewA, action: &Action, cx| {
5129                assert_eq!(action.0, "bar");
5130                cx.propagate_action();
5131                actions.borrow_mut().push(format!("{} a", view.id));
5132            });
5133        }
5134
5135        {
5136            let actions = actions.clone();
5137            cx.add_action(move |view: &mut ViewA, _: &Action, cx| {
5138                if view.id != 1 {
5139                    cx.add_view(|cx| {
5140                        cx.propagate_action(); // Still works on a nested ViewContext
5141                        ViewB { id: 5 }
5142                    });
5143                }
5144                actions.borrow_mut().push(format!("{} b", view.id));
5145            });
5146        }
5147
5148        {
5149            let actions = actions.clone();
5150            cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
5151                cx.propagate_action();
5152                actions.borrow_mut().push(format!("{} c", 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!("{} d", view.id));
5161            });
5162        }
5163
5164        {
5165            let actions = actions.clone();
5166            cx.capture_action(move |view: &mut ViewA, _: &Action, cx| {
5167                cx.propagate_action();
5168                actions.borrow_mut().push(format!("{} capture", view.id));
5169            });
5170        }
5171
5172        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
5173        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
5174        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
5175        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
5176
5177        cx.dispatch_action(
5178            window_id,
5179            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
5180            &Action("bar"),
5181        );
5182
5183        assert_eq!(
5184            *actions.borrow(),
5185            vec![
5186                "1 capture",
5187                "3 capture",
5188                "4 d",
5189                "4 c",
5190                "3 b",
5191                "3 a",
5192                "2 d",
5193                "2 c",
5194                "1 b"
5195            ]
5196        );
5197
5198        // Remove view_1, which doesn't propagate the action
5199        actions.borrow_mut().clear();
5200        cx.dispatch_action(
5201            window_id,
5202            vec![view_2.id(), view_3.id(), view_4.id()],
5203            &Action("bar"),
5204        );
5205
5206        assert_eq!(
5207            *actions.borrow(),
5208            vec![
5209                "3 capture",
5210                "4 d",
5211                "4 c",
5212                "3 b",
5213                "3 a",
5214                "2 d",
5215                "2 c",
5216                "global"
5217            ]
5218        );
5219    }
5220
5221    #[crate::test(self)]
5222    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
5223        action!(Action, &'static str);
5224
5225        struct View {
5226            id: usize,
5227            keymap_context: keymap::Context,
5228        }
5229
5230        impl Entity for View {
5231            type Event = ();
5232        }
5233
5234        impl super::View for View {
5235            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5236                Empty::new().boxed()
5237            }
5238
5239            fn ui_name() -> &'static str {
5240                "View"
5241            }
5242
5243            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
5244                self.keymap_context.clone()
5245            }
5246        }
5247
5248        impl View {
5249            fn new(id: usize) -> Self {
5250                View {
5251                    id,
5252                    keymap_context: keymap::Context::default(),
5253                }
5254            }
5255        }
5256
5257        let mut view_1 = View::new(1);
5258        let mut view_2 = View::new(2);
5259        let mut view_3 = View::new(3);
5260        view_1.keymap_context.set.insert("a".into());
5261        view_2.keymap_context.set.insert("a".into());
5262        view_2.keymap_context.set.insert("b".into());
5263        view_3.keymap_context.set.insert("a".into());
5264        view_3.keymap_context.set.insert("b".into());
5265        view_3.keymap_context.set.insert("c".into());
5266
5267        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
5268        let view_2 = cx.add_view(window_id, |_| view_2);
5269        let view_3 = cx.add_view(window_id, |_| view_3);
5270
5271        // This keymap's only binding dispatches an action on view 2 because that view will have
5272        // "a" and "b" in its context, but not "c".
5273        cx.add_bindings(vec![keymap::Binding::new(
5274            "a",
5275            Action("a"),
5276            Some("a && b && !c"),
5277        )]);
5278
5279        cx.add_bindings(vec![keymap::Binding::new("b", Action("b"), None)]);
5280
5281        let actions = Rc::new(RefCell::new(Vec::new()));
5282        {
5283            let actions = actions.clone();
5284            cx.add_action(move |view: &mut View, action: &Action, cx| {
5285                if action.0 == "a" {
5286                    actions.borrow_mut().push(format!("{} a", view.id));
5287                } else {
5288                    actions
5289                        .borrow_mut()
5290                        .push(format!("{} {}", view.id, action.0));
5291                    cx.propagate_action();
5292                }
5293            });
5294        }
5295        {
5296            let actions = actions.clone();
5297            cx.add_global_action(move |action: &Action, _| {
5298                actions.borrow_mut().push(format!("global {}", action.0));
5299            });
5300        }
5301
5302        cx.dispatch_keystroke(
5303            window_id,
5304            vec![view_1.id(), view_2.id(), view_3.id()],
5305            &Keystroke::parse("a").unwrap(),
5306        )
5307        .unwrap();
5308
5309        assert_eq!(&*actions.borrow(), &["2 a"]);
5310
5311        actions.borrow_mut().clear();
5312        cx.dispatch_keystroke(
5313            window_id,
5314            vec![view_1.id(), view_2.id(), view_3.id()],
5315            &Keystroke::parse("b").unwrap(),
5316        )
5317        .unwrap();
5318
5319        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
5320    }
5321
5322    #[crate::test(self)]
5323    async fn test_model_condition(cx: &mut TestAppContext) {
5324        struct Counter(usize);
5325
5326        impl super::Entity for Counter {
5327            type Event = ();
5328        }
5329
5330        impl Counter {
5331            fn inc(&mut self, cx: &mut ModelContext<Self>) {
5332                self.0 += 1;
5333                cx.notify();
5334            }
5335        }
5336
5337        let model = cx.add_model(|_| Counter(0));
5338
5339        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
5340        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
5341        smol::pin!(condition1, condition2);
5342
5343        model.update(cx, |model, cx| model.inc(cx));
5344        assert_eq!(poll_once(&mut condition1).await, None);
5345        assert_eq!(poll_once(&mut condition2).await, None);
5346
5347        model.update(cx, |model, cx| model.inc(cx));
5348        assert_eq!(poll_once(&mut condition1).await, Some(()));
5349        assert_eq!(poll_once(&mut condition2).await, None);
5350
5351        model.update(cx, |model, cx| model.inc(cx));
5352        assert_eq!(poll_once(&mut condition2).await, Some(()));
5353
5354        model.update(cx, |_, cx| cx.notify());
5355    }
5356
5357    #[crate::test(self)]
5358    #[should_panic]
5359    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
5360        struct Model;
5361
5362        impl super::Entity for Model {
5363            type Event = ();
5364        }
5365
5366        let model = cx.add_model(|_| Model);
5367        model.condition(&cx, |_, _| false).await;
5368    }
5369
5370    #[crate::test(self)]
5371    #[should_panic(expected = "model dropped with pending condition")]
5372    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
5373        struct Model;
5374
5375        impl super::Entity for Model {
5376            type Event = ();
5377        }
5378
5379        let model = cx.add_model(|_| Model);
5380        let condition = model.condition(&cx, |_, _| false);
5381        cx.update(|_| drop(model));
5382        condition.await;
5383    }
5384
5385    #[crate::test(self)]
5386    async fn test_view_condition(cx: &mut TestAppContext) {
5387        struct Counter(usize);
5388
5389        impl super::Entity for Counter {
5390            type Event = ();
5391        }
5392
5393        impl super::View for Counter {
5394            fn ui_name() -> &'static str {
5395                "test view"
5396            }
5397
5398            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5399                Empty::new().boxed()
5400            }
5401        }
5402
5403        impl Counter {
5404            fn inc(&mut self, cx: &mut ViewContext<Self>) {
5405                self.0 += 1;
5406                cx.notify();
5407            }
5408        }
5409
5410        let (_, view) = cx.add_window(|_| Counter(0));
5411
5412        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
5413        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
5414        smol::pin!(condition1, condition2);
5415
5416        view.update(cx, |view, cx| view.inc(cx));
5417        assert_eq!(poll_once(&mut condition1).await, None);
5418        assert_eq!(poll_once(&mut condition2).await, None);
5419
5420        view.update(cx, |view, cx| view.inc(cx));
5421        assert_eq!(poll_once(&mut condition1).await, Some(()));
5422        assert_eq!(poll_once(&mut condition2).await, None);
5423
5424        view.update(cx, |view, cx| view.inc(cx));
5425        assert_eq!(poll_once(&mut condition2).await, Some(()));
5426        view.update(cx, |_, cx| cx.notify());
5427    }
5428
5429    #[crate::test(self)]
5430    #[should_panic]
5431    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
5432        struct View;
5433
5434        impl super::Entity for View {
5435            type Event = ();
5436        }
5437
5438        impl super::View for View {
5439            fn ui_name() -> &'static str {
5440                "test view"
5441            }
5442
5443            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5444                Empty::new().boxed()
5445            }
5446        }
5447
5448        let (_, view) = cx.add_window(|_| View);
5449        view.condition(&cx, |_, _| false).await;
5450    }
5451
5452    #[crate::test(self)]
5453    #[should_panic(expected = "view dropped with pending condition")]
5454    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
5455        struct View;
5456
5457        impl super::Entity for View {
5458            type Event = ();
5459        }
5460
5461        impl super::View for View {
5462            fn ui_name() -> &'static str {
5463                "test view"
5464            }
5465
5466            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5467                Empty::new().boxed()
5468            }
5469        }
5470
5471        let window_id = cx.add_window(|_| View).0;
5472        let view = cx.add_view(window_id, |_| View);
5473
5474        let condition = view.condition(&cx, |_, _| false);
5475        cx.update(|_| drop(view));
5476        condition.await;
5477    }
5478
5479    #[crate::test(self)]
5480    fn test_refresh_windows(cx: &mut MutableAppContext) {
5481        struct View(usize);
5482
5483        impl super::Entity for View {
5484            type Event = ();
5485        }
5486
5487        impl super::View for View {
5488            fn ui_name() -> &'static str {
5489                "test view"
5490            }
5491
5492            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5493                Empty::new().named(format!("render count: {}", post_inc(&mut self.0)))
5494            }
5495        }
5496
5497        let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
5498        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
5499
5500        assert_eq!(
5501            presenter.borrow().rendered_views[&root_view.id()].name(),
5502            Some("render count: 0")
5503        );
5504
5505        let view = cx.add_view(window_id, |cx| {
5506            cx.refresh_windows();
5507            View(0)
5508        });
5509
5510        assert_eq!(
5511            presenter.borrow().rendered_views[&root_view.id()].name(),
5512            Some("render count: 1")
5513        );
5514        assert_eq!(
5515            presenter.borrow().rendered_views[&view.id()].name(),
5516            Some("render count: 0")
5517        );
5518
5519        cx.update(|cx| cx.refresh_windows());
5520        assert_eq!(
5521            presenter.borrow().rendered_views[&root_view.id()].name(),
5522            Some("render count: 2")
5523        );
5524        assert_eq!(
5525            presenter.borrow().rendered_views[&view.id()].name(),
5526            Some("render count: 1")
5527        );
5528
5529        cx.update(|cx| {
5530            cx.refresh_windows();
5531            drop(view);
5532        });
5533        assert_eq!(
5534            presenter.borrow().rendered_views[&root_view.id()].name(),
5535            Some("render count: 3")
5536        );
5537        assert_eq!(presenter.borrow().rendered_views.len(), 1);
5538    }
5539}