app.rs

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