app.rs

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