app.rs

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