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 = Rc::downgrade(&presenter);
1639            window.on_event(Box::new(move |event| {
1640                app.update(|cx| {
1641                    if let Some(presenter) = presenter.upgrade() {
1642                        if let Event::KeyDown { keystroke, .. } = &event {
1643                            if cx.dispatch_keystroke(
1644                                window_id,
1645                                presenter.borrow().dispatch_path(cx.as_ref()),
1646                                keystroke,
1647                            ) {
1648                                return;
1649                            }
1650                        }
1651
1652                        presenter.borrow_mut().dispatch_event(event, cx);
1653                    }
1654                })
1655            }));
1656        }
1657
1658        {
1659            let mut app = self.upgrade();
1660            window.on_active_status_change(Box::new(move |is_active| {
1661                app.update(|cx| cx.window_changed_active_status(window_id, is_active))
1662            }));
1663        }
1664
1665        {
1666            let mut app = self.upgrade();
1667            window.on_resize(Box::new(move || {
1668                app.update(|cx| cx.window_was_resized(window_id))
1669            }));
1670        }
1671
1672        {
1673            let mut app = self.upgrade();
1674            window.on_close(Box::new(move || {
1675                app.update(|cx| cx.remove_window(window_id));
1676            }));
1677        }
1678
1679        let scene =
1680            presenter
1681                .borrow_mut()
1682                .build_scene(window.size(), window.scale_factor(), false, self);
1683        window.present_scene(scene);
1684        self.presenters_and_platform_windows
1685            .insert(window_id, (presenter.clone(), window));
1686    }
1687
1688    pub fn build_presenter(&mut self, window_id: usize, titlebar_height: f32) -> Presenter {
1689        Presenter::new(
1690            window_id,
1691            titlebar_height,
1692            self.cx.font_cache.clone(),
1693            TextLayoutCache::new(self.cx.platform.fonts()),
1694            self.assets.clone(),
1695            self,
1696        )
1697    }
1698
1699    pub fn build_render_context<V: View>(
1700        &mut self,
1701        window_id: usize,
1702        view_id: usize,
1703        titlebar_height: f32,
1704        refreshing: bool,
1705    ) -> RenderContext<V> {
1706        RenderContext {
1707            app: self,
1708            titlebar_height,
1709            refreshing,
1710            window_id,
1711            view_id,
1712            view_type: PhantomData,
1713        }
1714    }
1715
1716    pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
1717    where
1718        T: View,
1719        F: FnOnce(&mut ViewContext<T>) -> T,
1720    {
1721        self.add_option_view(window_id, |cx| Some(build_view(cx)))
1722            .unwrap()
1723    }
1724
1725    pub fn add_option_view<T, F>(
1726        &mut self,
1727        window_id: usize,
1728        build_view: F,
1729    ) -> Option<ViewHandle<T>>
1730    where
1731        T: View,
1732        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1733    {
1734        self.update(|this| {
1735            let view_id = post_inc(&mut this.next_entity_id);
1736            let mut cx = ViewContext::new(this, window_id, view_id);
1737            let handle = if let Some(view) = build_view(&mut cx) {
1738                this.cx.views.insert((window_id, view_id), Box::new(view));
1739                if let Some(window) = this.cx.windows.get_mut(&window_id) {
1740                    window
1741                        .invalidation
1742                        .get_or_insert_with(Default::default)
1743                        .updated
1744                        .insert(view_id);
1745                }
1746                Some(ViewHandle::new(window_id, view_id, &this.cx.ref_counts))
1747            } else {
1748                None
1749            };
1750            handle
1751        })
1752    }
1753
1754    fn remove_dropped_entities(&mut self) {
1755        loop {
1756            let (dropped_models, dropped_views, dropped_element_states) =
1757                self.cx.ref_counts.lock().take_dropped();
1758            if dropped_models.is_empty()
1759                && dropped_views.is_empty()
1760                && dropped_element_states.is_empty()
1761            {
1762                break;
1763            }
1764
1765            for model_id in dropped_models {
1766                self.subscriptions.lock().remove(&model_id);
1767                self.observations.lock().remove(&model_id);
1768                let mut model = self.cx.models.remove(&model_id).unwrap();
1769                model.release(self);
1770                self.pending_effects
1771                    .push_back(Effect::ModelRelease { model_id, model });
1772            }
1773
1774            for (window_id, view_id) in dropped_views {
1775                self.subscriptions.lock().remove(&view_id);
1776                self.observations.lock().remove(&view_id);
1777                let mut view = self.cx.views.remove(&(window_id, view_id)).unwrap();
1778                view.release(self);
1779                let change_focus_to = self.cx.windows.get_mut(&window_id).and_then(|window| {
1780                    window
1781                        .invalidation
1782                        .get_or_insert_with(Default::default)
1783                        .removed
1784                        .push(view_id);
1785                    if window.focused_view_id == Some(view_id) {
1786                        Some(window.root_view.id())
1787                    } else {
1788                        None
1789                    }
1790                });
1791
1792                if let Some(view_id) = change_focus_to {
1793                    self.handle_focus_effect(window_id, Some(view_id));
1794                }
1795
1796                self.pending_effects
1797                    .push_back(Effect::ViewRelease { view_id, view });
1798            }
1799
1800            for key in dropped_element_states {
1801                self.cx.element_states.remove(&key);
1802            }
1803        }
1804    }
1805
1806    fn flush_effects(&mut self) {
1807        self.pending_flushes = self.pending_flushes.saturating_sub(1);
1808        let mut after_window_update_callbacks = Vec::new();
1809
1810        if !self.flushing_effects && self.pending_flushes == 0 {
1811            self.flushing_effects = true;
1812
1813            let mut refreshing = false;
1814            loop {
1815                if let Some(effect) = self.pending_effects.pop_front() {
1816                    if let Some(pending_focus_index) = self.pending_focus_index.as_mut() {
1817                        *pending_focus_index = pending_focus_index.saturating_sub(1);
1818                    }
1819                    match effect {
1820                        Effect::Subscription {
1821                            entity_id,
1822                            subscription_id,
1823                            callback,
1824                        } => self.handle_subscription_effect(entity_id, subscription_id, callback),
1825                        Effect::Event { entity_id, payload } => self.emit_event(entity_id, payload),
1826                        Effect::GlobalSubscription {
1827                            type_id,
1828                            subscription_id,
1829                            callback,
1830                        } => self.handle_global_subscription_effect(
1831                            type_id,
1832                            subscription_id,
1833                            callback,
1834                        ),
1835                        Effect::GlobalEvent { payload } => self.emit_global_event(payload),
1836                        Effect::Observation {
1837                            entity_id,
1838                            subscription_id,
1839                            callback,
1840                        } => self.handle_observation_effect(entity_id, subscription_id, callback),
1841                        Effect::ModelNotification { model_id } => {
1842                            self.handle_model_notification_effect(model_id)
1843                        }
1844                        Effect::ViewNotification { window_id, view_id } => {
1845                            self.handle_view_notification_effect(window_id, view_id)
1846                        }
1847                        Effect::GlobalNotification { type_id } => {
1848                            self.handle_global_notification_effect(type_id)
1849                        }
1850                        Effect::Deferred {
1851                            callback,
1852                            after_window_update,
1853                        } => {
1854                            if after_window_update {
1855                                after_window_update_callbacks.push(callback);
1856                            } else {
1857                                callback(self)
1858                            }
1859                        }
1860                        Effect::ModelRelease { model_id, model } => {
1861                            self.handle_entity_release_effect(model_id, model.as_any())
1862                        }
1863                        Effect::ViewRelease { view_id, view } => {
1864                            self.handle_entity_release_effect(view_id, view.as_any())
1865                        }
1866                        Effect::Focus { window_id, view_id } => {
1867                            self.handle_focus_effect(window_id, view_id);
1868                        }
1869                        Effect::FocusObservation {
1870                            view_id,
1871                            subscription_id,
1872                            callback,
1873                        } => {
1874                            self.handle_focus_observation_effect(view_id, subscription_id, callback)
1875                        }
1876                        Effect::ResizeWindow { window_id } => {
1877                            if let Some(window) = self.cx.windows.get_mut(&window_id) {
1878                                window
1879                                    .invalidation
1880                                    .get_or_insert(WindowInvalidation::default());
1881                            }
1882                        }
1883                        Effect::ActivateWindow {
1884                            window_id,
1885                            is_active,
1886                        } => self.handle_activation_effect(window_id, is_active),
1887                        Effect::RefreshWindows => {
1888                            refreshing = true;
1889                        }
1890                    }
1891                    self.pending_notifications.clear();
1892                    self.remove_dropped_entities();
1893                } else {
1894                    self.remove_dropped_entities();
1895                    if refreshing {
1896                        self.perform_window_refresh();
1897                    } else {
1898                        self.update_windows();
1899                    }
1900
1901                    if self.pending_effects.is_empty() {
1902                        for callback in after_window_update_callbacks.drain(..) {
1903                            callback(self);
1904                        }
1905
1906                        if self.pending_effects.is_empty() {
1907                            self.flushing_effects = false;
1908                            self.pending_notifications.clear();
1909                            self.pending_global_notifications.clear();
1910                            break;
1911                        }
1912                    }
1913
1914                    refreshing = false;
1915                }
1916            }
1917        }
1918    }
1919
1920    fn update_windows(&mut self) {
1921        let mut invalidations = HashMap::new();
1922        for (window_id, window) in &mut self.cx.windows {
1923            if let Some(invalidation) = window.invalidation.take() {
1924                invalidations.insert(*window_id, invalidation);
1925            }
1926        }
1927
1928        for (window_id, mut invalidation) in invalidations {
1929            if let Some((presenter, mut window)) =
1930                self.presenters_and_platform_windows.remove(&window_id)
1931            {
1932                {
1933                    let mut presenter = presenter.borrow_mut();
1934                    presenter.invalidate(&mut invalidation, self);
1935                    let scene =
1936                        presenter.build_scene(window.size(), window.scale_factor(), false, self);
1937                    window.present_scene(scene);
1938                }
1939                self.presenters_and_platform_windows
1940                    .insert(window_id, (presenter, window));
1941            }
1942        }
1943    }
1944
1945    fn window_was_resized(&mut self, window_id: usize) {
1946        self.pending_effects
1947            .push_back(Effect::ResizeWindow { window_id });
1948    }
1949
1950    fn window_changed_active_status(&mut self, window_id: usize, is_active: bool) {
1951        self.pending_effects.push_back(Effect::ActivateWindow {
1952            window_id,
1953            is_active,
1954        });
1955    }
1956
1957    pub fn refresh_windows(&mut self) {
1958        self.pending_effects.push_back(Effect::RefreshWindows);
1959    }
1960
1961    fn perform_window_refresh(&mut self) {
1962        let mut presenters = mem::take(&mut self.presenters_and_platform_windows);
1963        for (window_id, (presenter, window)) in &mut presenters {
1964            let mut invalidation = self
1965                .cx
1966                .windows
1967                .get_mut(&window_id)
1968                .unwrap()
1969                .invalidation
1970                .take();
1971            let mut presenter = presenter.borrow_mut();
1972            presenter.refresh(
1973                invalidation.as_mut().unwrap_or(&mut Default::default()),
1974                self,
1975            );
1976            let scene = presenter.build_scene(window.size(), window.scale_factor(), true, self);
1977            window.present_scene(scene);
1978        }
1979        self.presenters_and_platform_windows = presenters;
1980    }
1981
1982    fn handle_subscription_effect(
1983        &mut self,
1984        entity_id: usize,
1985        subscription_id: usize,
1986        callback: SubscriptionCallback,
1987    ) {
1988        match self
1989            .subscriptions
1990            .lock()
1991            .entry(entity_id)
1992            .or_default()
1993            .entry(subscription_id)
1994        {
1995            btree_map::Entry::Vacant(entry) => {
1996                entry.insert(Some(callback));
1997            }
1998            // Subscription was dropped before effect was processed
1999            btree_map::Entry::Occupied(entry) => {
2000                debug_assert!(entry.get().is_none());
2001                entry.remove();
2002            }
2003        }
2004    }
2005
2006    fn emit_event(&mut self, entity_id: usize, payload: Box<dyn Any>) {
2007        let callbacks = self.subscriptions.lock().remove(&entity_id);
2008        if let Some(callbacks) = callbacks {
2009            for (id, callback) in callbacks {
2010                if let Some(mut callback) = callback {
2011                    let alive = callback(payload.as_ref(), self);
2012                    if alive {
2013                        match self
2014                            .subscriptions
2015                            .lock()
2016                            .entry(entity_id)
2017                            .or_default()
2018                            .entry(id)
2019                        {
2020                            btree_map::Entry::Vacant(entry) => {
2021                                entry.insert(Some(callback));
2022                            }
2023                            btree_map::Entry::Occupied(entry) => {
2024                                entry.remove();
2025                            }
2026                        }
2027                    }
2028                }
2029            }
2030        }
2031    }
2032
2033    fn handle_global_subscription_effect(
2034        &mut self,
2035        type_id: TypeId,
2036        subscription_id: usize,
2037        callback: GlobalSubscriptionCallback,
2038    ) {
2039        match self
2040            .global_subscriptions
2041            .lock()
2042            .entry(type_id)
2043            .or_default()
2044            .entry(subscription_id)
2045        {
2046            btree_map::Entry::Vacant(entry) => {
2047                entry.insert(Some(callback));
2048            }
2049            // Subscription was dropped before effect was processed
2050            btree_map::Entry::Occupied(entry) => {
2051                debug_assert!(entry.get().is_none());
2052                entry.remove();
2053            }
2054        }
2055    }
2056
2057    fn emit_global_event(&mut self, payload: Box<dyn Any>) {
2058        let type_id = (&*payload).type_id();
2059        let callbacks = self.global_subscriptions.lock().remove(&type_id);
2060        if let Some(callbacks) = callbacks {
2061            for (id, callback) in callbacks {
2062                if let Some(mut callback) = callback {
2063                    callback(payload.as_ref(), self);
2064                    match self
2065                        .global_subscriptions
2066                        .lock()
2067                        .entry(type_id)
2068                        .or_default()
2069                        .entry(id)
2070                    {
2071                        btree_map::Entry::Vacant(entry) => {
2072                            entry.insert(Some(callback));
2073                        }
2074                        btree_map::Entry::Occupied(entry) => {
2075                            entry.remove();
2076                        }
2077                    }
2078                }
2079            }
2080        }
2081    }
2082
2083    fn handle_observation_effect(
2084        &mut self,
2085        entity_id: usize,
2086        subscription_id: usize,
2087        callback: ObservationCallback,
2088    ) {
2089        match self
2090            .observations
2091            .lock()
2092            .entry(entity_id)
2093            .or_default()
2094            .entry(subscription_id)
2095        {
2096            btree_map::Entry::Vacant(entry) => {
2097                entry.insert(Some(callback));
2098            }
2099            // Observation was dropped before effect was processed
2100            btree_map::Entry::Occupied(entry) => {
2101                debug_assert!(entry.get().is_none());
2102                entry.remove();
2103            }
2104        }
2105    }
2106
2107    fn handle_focus_observation_effect(
2108        &mut self,
2109        view_id: usize,
2110        subscription_id: usize,
2111        callback: FocusObservationCallback,
2112    ) {
2113        match self
2114            .focus_observations
2115            .lock()
2116            .entry(view_id)
2117            .or_default()
2118            .entry(subscription_id)
2119        {
2120            btree_map::Entry::Vacant(entry) => {
2121                entry.insert(Some(callback));
2122            }
2123            // Observation was dropped before effect was processed
2124            btree_map::Entry::Occupied(entry) => {
2125                debug_assert!(entry.get().is_none());
2126                entry.remove();
2127            }
2128        }
2129    }
2130
2131    fn handle_model_notification_effect(&mut self, observed_id: usize) {
2132        let callbacks = self.observations.lock().remove(&observed_id);
2133        if let Some(callbacks) = callbacks {
2134            if self.cx.models.contains_key(&observed_id) {
2135                for (id, callback) in callbacks {
2136                    if let Some(mut callback) = callback {
2137                        let alive = callback(self);
2138                        if alive {
2139                            match self
2140                                .observations
2141                                .lock()
2142                                .entry(observed_id)
2143                                .or_default()
2144                                .entry(id)
2145                            {
2146                                btree_map::Entry::Vacant(entry) => {
2147                                    entry.insert(Some(callback));
2148                                }
2149                                btree_map::Entry::Occupied(entry) => {
2150                                    entry.remove();
2151                                }
2152                            }
2153                        }
2154                    }
2155                }
2156            }
2157        }
2158    }
2159
2160    fn handle_view_notification_effect(
2161        &mut self,
2162        observed_window_id: usize,
2163        observed_view_id: usize,
2164    ) {
2165        if let Some(window) = self.cx.windows.get_mut(&observed_window_id) {
2166            window
2167                .invalidation
2168                .get_or_insert_with(Default::default)
2169                .updated
2170                .insert(observed_view_id);
2171        }
2172
2173        let callbacks = self.observations.lock().remove(&observed_view_id);
2174        if let Some(callbacks) = callbacks {
2175            if self
2176                .cx
2177                .views
2178                .contains_key(&(observed_window_id, observed_view_id))
2179            {
2180                for (id, callback) in callbacks {
2181                    if let Some(mut callback) = callback {
2182                        let alive = callback(self);
2183                        if alive {
2184                            match self
2185                                .observations
2186                                .lock()
2187                                .entry(observed_view_id)
2188                                .or_default()
2189                                .entry(id)
2190                            {
2191                                btree_map::Entry::Vacant(entry) => {
2192                                    entry.insert(Some(callback));
2193                                }
2194                                btree_map::Entry::Occupied(entry) => {
2195                                    entry.remove();
2196                                }
2197                            }
2198                        }
2199                    }
2200                }
2201            }
2202        }
2203    }
2204
2205    fn handle_global_notification_effect(&mut self, observed_type_id: TypeId) {
2206        let callbacks = self.global_observations.lock().remove(&observed_type_id);
2207        if let Some(callbacks) = callbacks {
2208            if let Some(global) = self.cx.globals.remove(&observed_type_id) {
2209                for (id, callback) in callbacks {
2210                    if let Some(mut callback) = callback {
2211                        callback(global.as_ref(), self);
2212                        match self
2213                            .global_observations
2214                            .lock()
2215                            .entry(observed_type_id)
2216                            .or_default()
2217                            .entry(id)
2218                        {
2219                            collections::btree_map::Entry::Vacant(entry) => {
2220                                entry.insert(Some(callback));
2221                            }
2222                            collections::btree_map::Entry::Occupied(entry) => {
2223                                entry.remove();
2224                            }
2225                        }
2226                    }
2227                }
2228                self.cx.globals.insert(observed_type_id, global);
2229            }
2230        }
2231    }
2232
2233    fn handle_entity_release_effect(&mut self, entity_id: usize, entity: &dyn Any) {
2234        let callbacks = self.release_observations.lock().remove(&entity_id);
2235        if let Some(callbacks) = callbacks {
2236            for (_, callback) in callbacks {
2237                callback(entity, self);
2238            }
2239        }
2240    }
2241
2242    fn handle_activation_effect(&mut self, window_id: usize, active: bool) {
2243        if self
2244            .cx
2245            .windows
2246            .get(&window_id)
2247            .map(|w| w.is_active)
2248            .map_or(false, |cur_active| cur_active == active)
2249        {
2250            return;
2251        }
2252
2253        self.update(|this| {
2254            let window = this.cx.windows.get_mut(&window_id)?;
2255            window.is_active = active;
2256            let view_id = window.focused_view_id?;
2257            if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
2258                if active {
2259                    view.on_focus(this, window_id, view_id);
2260                } else {
2261                    view.on_blur(this, window_id, view_id);
2262                }
2263                this.cx.views.insert((window_id, view_id), view);
2264            }
2265
2266            Some(())
2267        });
2268    }
2269
2270    fn handle_focus_effect(&mut self, window_id: usize, focused_id: Option<usize>) {
2271        self.pending_focus_index.take();
2272
2273        if self
2274            .cx
2275            .windows
2276            .get(&window_id)
2277            .map(|w| w.focused_view_id)
2278            .map_or(false, |cur_focused| cur_focused == focused_id)
2279        {
2280            return;
2281        }
2282
2283        self.update(|this| {
2284            let blurred_id = this.cx.windows.get_mut(&window_id).and_then(|window| {
2285                let blurred_id = window.focused_view_id;
2286                window.focused_view_id = focused_id;
2287                blurred_id
2288            });
2289
2290            if let Some(blurred_id) = blurred_id {
2291                if let Some(mut blurred_view) = this.cx.views.remove(&(window_id, blurred_id)) {
2292                    blurred_view.on_blur(this, window_id, blurred_id);
2293                    this.cx.views.insert((window_id, blurred_id), blurred_view);
2294                }
2295            }
2296
2297            if let Some(focused_id) = focused_id {
2298                if let Some(mut focused_view) = this.cx.views.remove(&(window_id, focused_id)) {
2299                    focused_view.on_focus(this, window_id, focused_id);
2300                    this.cx.views.insert((window_id, focused_id), focused_view);
2301
2302                    let callbacks = this.focus_observations.lock().remove(&focused_id);
2303                    if let Some(callbacks) = callbacks {
2304                        for (id, callback) in callbacks {
2305                            if let Some(mut callback) = callback {
2306                                let alive = callback(this);
2307                                if alive {
2308                                    match this
2309                                        .focus_observations
2310                                        .lock()
2311                                        .entry(focused_id)
2312                                        .or_default()
2313                                        .entry(id)
2314                                    {
2315                                        btree_map::Entry::Vacant(entry) => {
2316                                            entry.insert(Some(callback));
2317                                        }
2318                                        btree_map::Entry::Occupied(entry) => {
2319                                            entry.remove();
2320                                        }
2321                                    }
2322                                }
2323                            }
2324                        }
2325                    }
2326                }
2327            }
2328        })
2329    }
2330
2331    fn focus(&mut self, window_id: usize, view_id: Option<usize>) {
2332        if let Some(pending_focus_index) = self.pending_focus_index {
2333            self.pending_effects.remove(pending_focus_index);
2334        }
2335        self.pending_focus_index = Some(self.pending_effects.len());
2336        self.pending_effects
2337            .push_back(Effect::Focus { window_id, view_id });
2338    }
2339
2340    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
2341    where
2342        F: FnOnce(AsyncAppContext) -> Fut,
2343        Fut: 'static + Future<Output = T>,
2344        T: 'static,
2345    {
2346        let future = f(self.to_async());
2347        let cx = self.to_async();
2348        self.foreground.spawn(async move {
2349            let result = future.await;
2350            cx.0.borrow_mut().flush_effects();
2351            result
2352        })
2353    }
2354
2355    pub fn to_async(&self) -> AsyncAppContext {
2356        AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
2357    }
2358
2359    pub fn write_to_clipboard(&self, item: ClipboardItem) {
2360        self.cx.platform.write_to_clipboard(item);
2361    }
2362
2363    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
2364        self.cx.platform.read_from_clipboard()
2365    }
2366
2367    #[cfg(any(test, feature = "test-support"))]
2368    pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
2369        self.cx.ref_counts.lock().leak_detector.clone()
2370    }
2371}
2372
2373impl ReadModel for MutableAppContext {
2374    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2375        if let Some(model) = self.cx.models.get(&handle.model_id) {
2376            model
2377                .as_any()
2378                .downcast_ref()
2379                .expect("downcast is type safe")
2380        } else {
2381            panic!("circular model reference");
2382        }
2383    }
2384}
2385
2386impl UpdateModel for MutableAppContext {
2387    fn update_model<T: Entity, V>(
2388        &mut self,
2389        handle: &ModelHandle<T>,
2390        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
2391    ) -> V {
2392        if let Some(mut model) = self.cx.models.remove(&handle.model_id) {
2393            self.update(|this| {
2394                let mut cx = ModelContext::new(this, handle.model_id);
2395                let result = update(
2396                    model
2397                        .as_any_mut()
2398                        .downcast_mut()
2399                        .expect("downcast is type safe"),
2400                    &mut cx,
2401                );
2402                this.cx.models.insert(handle.model_id, model);
2403                result
2404            })
2405        } else {
2406            panic!("circular model update");
2407        }
2408    }
2409}
2410
2411impl UpgradeModelHandle for MutableAppContext {
2412    fn upgrade_model_handle<T: Entity>(
2413        &self,
2414        handle: &WeakModelHandle<T>,
2415    ) -> Option<ModelHandle<T>> {
2416        self.cx.upgrade_model_handle(handle)
2417    }
2418
2419    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2420        self.cx.model_handle_is_upgradable(handle)
2421    }
2422
2423    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2424        self.cx.upgrade_any_model_handle(handle)
2425    }
2426}
2427
2428impl UpgradeViewHandle for MutableAppContext {
2429    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2430        self.cx.upgrade_view_handle(handle)
2431    }
2432
2433    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
2434        self.cx.upgrade_any_view_handle(handle)
2435    }
2436}
2437
2438impl ReadView for MutableAppContext {
2439    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2440        if let Some(view) = self.cx.views.get(&(handle.window_id, handle.view_id)) {
2441            view.as_any().downcast_ref().expect("downcast is type safe")
2442        } else {
2443            panic!("circular view reference");
2444        }
2445    }
2446}
2447
2448impl UpdateView for MutableAppContext {
2449    fn update_view<T, S>(
2450        &mut self,
2451        handle: &ViewHandle<T>,
2452        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
2453    ) -> S
2454    where
2455        T: View,
2456    {
2457        self.update(|this| {
2458            let mut view = this
2459                .cx
2460                .views
2461                .remove(&(handle.window_id, handle.view_id))
2462                .expect("circular view update");
2463
2464            let mut cx = ViewContext::new(this, handle.window_id, handle.view_id);
2465            let result = update(
2466                view.as_any_mut()
2467                    .downcast_mut()
2468                    .expect("downcast is type safe"),
2469                &mut cx,
2470            );
2471            this.cx
2472                .views
2473                .insert((handle.window_id, handle.view_id), view);
2474            result
2475        })
2476    }
2477}
2478
2479impl AsRef<AppContext> for MutableAppContext {
2480    fn as_ref(&self) -> &AppContext {
2481        &self.cx
2482    }
2483}
2484
2485impl Deref for MutableAppContext {
2486    type Target = AppContext;
2487
2488    fn deref(&self) -> &Self::Target {
2489        &self.cx
2490    }
2491}
2492
2493pub struct AppContext {
2494    models: HashMap<usize, Box<dyn AnyModel>>,
2495    views: HashMap<(usize, usize), Box<dyn AnyView>>,
2496    windows: HashMap<usize, Window>,
2497    globals: HashMap<TypeId, Box<dyn Any>>,
2498    element_states: HashMap<ElementStateId, Box<dyn Any>>,
2499    background: Arc<executor::Background>,
2500    ref_counts: Arc<Mutex<RefCounts>>,
2501    font_cache: Arc<FontCache>,
2502    platform: Arc<dyn Platform>,
2503}
2504
2505impl AppContext {
2506    pub(crate) fn root_view(&self, window_id: usize) -> Option<AnyViewHandle> {
2507        self.windows
2508            .get(&window_id)
2509            .map(|window| window.root_view.clone())
2510    }
2511
2512    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
2513        self.windows
2514            .get(&window_id)
2515            .map(|window| window.root_view.id())
2516    }
2517
2518    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
2519        self.windows
2520            .get(&window_id)
2521            .and_then(|window| window.focused_view_id)
2522    }
2523
2524    pub fn background(&self) -> &Arc<executor::Background> {
2525        &self.background
2526    }
2527
2528    pub fn font_cache(&self) -> &Arc<FontCache> {
2529        &self.font_cache
2530    }
2531
2532    pub fn platform(&self) -> &Arc<dyn Platform> {
2533        &self.platform
2534    }
2535
2536    pub fn has_global<T: 'static>(&self) -> bool {
2537        self.globals.contains_key(&TypeId::of::<T>())
2538    }
2539
2540    pub fn global<T: 'static>(&self) -> &T {
2541        if let Some(global) = self.globals.get(&TypeId::of::<T>()) {
2542            global.downcast_ref().unwrap()
2543        } else {
2544            panic!("no global has been added for {}", type_name::<T>());
2545        }
2546    }
2547}
2548
2549impl ReadModel for AppContext {
2550    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2551        if let Some(model) = self.models.get(&handle.model_id) {
2552            model
2553                .as_any()
2554                .downcast_ref()
2555                .expect("downcast should be type safe")
2556        } else {
2557            panic!("circular model reference");
2558        }
2559    }
2560}
2561
2562impl UpgradeModelHandle for AppContext {
2563    fn upgrade_model_handle<T: Entity>(
2564        &self,
2565        handle: &WeakModelHandle<T>,
2566    ) -> Option<ModelHandle<T>> {
2567        if self.models.contains_key(&handle.model_id) {
2568            Some(ModelHandle::new(handle.model_id, &self.ref_counts))
2569        } else {
2570            None
2571        }
2572    }
2573
2574    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2575        self.models.contains_key(&handle.model_id)
2576    }
2577
2578    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2579        if self.models.contains_key(&handle.model_id) {
2580            Some(AnyModelHandle::new(
2581                handle.model_id,
2582                handle.model_type,
2583                self.ref_counts.clone(),
2584            ))
2585        } else {
2586            None
2587        }
2588    }
2589}
2590
2591impl UpgradeViewHandle for AppContext {
2592    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2593        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2594            Some(ViewHandle::new(
2595                handle.window_id,
2596                handle.view_id,
2597                &self.ref_counts,
2598            ))
2599        } else {
2600            None
2601        }
2602    }
2603
2604    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
2605        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2606            Some(AnyViewHandle::new(
2607                handle.window_id,
2608                handle.view_id,
2609                handle.view_type,
2610                self.ref_counts.clone(),
2611            ))
2612        } else {
2613            None
2614        }
2615    }
2616}
2617
2618impl ReadView for AppContext {
2619    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2620        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
2621            view.as_any()
2622                .downcast_ref()
2623                .expect("downcast should be type safe")
2624        } else {
2625            panic!("circular view reference");
2626        }
2627    }
2628}
2629
2630struct Window {
2631    root_view: AnyViewHandle,
2632    focused_view_id: Option<usize>,
2633    is_active: bool,
2634    invalidation: Option<WindowInvalidation>,
2635}
2636
2637#[derive(Default, Clone)]
2638pub struct WindowInvalidation {
2639    pub updated: HashSet<usize>,
2640    pub removed: Vec<usize>,
2641}
2642
2643pub enum Effect {
2644    Subscription {
2645        entity_id: usize,
2646        subscription_id: usize,
2647        callback: SubscriptionCallback,
2648    },
2649    Event {
2650        entity_id: usize,
2651        payload: Box<dyn Any>,
2652    },
2653    GlobalSubscription {
2654        type_id: TypeId,
2655        subscription_id: usize,
2656        callback: GlobalSubscriptionCallback,
2657    },
2658    GlobalEvent {
2659        payload: Box<dyn Any>,
2660    },
2661    Observation {
2662        entity_id: usize,
2663        subscription_id: usize,
2664        callback: ObservationCallback,
2665    },
2666    ModelNotification {
2667        model_id: usize,
2668    },
2669    ViewNotification {
2670        window_id: usize,
2671        view_id: usize,
2672    },
2673    Deferred {
2674        callback: Box<dyn FnOnce(&mut MutableAppContext)>,
2675        after_window_update: bool,
2676    },
2677    GlobalNotification {
2678        type_id: TypeId,
2679    },
2680    ModelRelease {
2681        model_id: usize,
2682        model: Box<dyn AnyModel>,
2683    },
2684    ViewRelease {
2685        view_id: usize,
2686        view: Box<dyn AnyView>,
2687    },
2688    Focus {
2689        window_id: usize,
2690        view_id: Option<usize>,
2691    },
2692    FocusObservation {
2693        view_id: usize,
2694        subscription_id: usize,
2695        callback: FocusObservationCallback,
2696    },
2697    ResizeWindow {
2698        window_id: usize,
2699    },
2700    ActivateWindow {
2701        window_id: usize,
2702        is_active: bool,
2703    },
2704    RefreshWindows,
2705}
2706
2707impl Debug for Effect {
2708    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2709        match self {
2710            Effect::Subscription {
2711                entity_id,
2712                subscription_id,
2713                ..
2714            } => f
2715                .debug_struct("Effect::Subscribe")
2716                .field("entity_id", entity_id)
2717                .field("subscription_id", subscription_id)
2718                .finish(),
2719            Effect::Event { entity_id, .. } => f
2720                .debug_struct("Effect::Event")
2721                .field("entity_id", entity_id)
2722                .finish(),
2723            Effect::GlobalSubscription {
2724                type_id,
2725                subscription_id,
2726                ..
2727            } => f
2728                .debug_struct("Effect::Subscribe")
2729                .field("type_id", type_id)
2730                .field("subscription_id", subscription_id)
2731                .finish(),
2732            Effect::GlobalEvent { payload, .. } => f
2733                .debug_struct("Effect::GlobalEvent")
2734                .field("type_id", &(&*payload).type_id())
2735                .finish(),
2736            Effect::Observation {
2737                entity_id,
2738                subscription_id,
2739                ..
2740            } => f
2741                .debug_struct("Effect::Observation")
2742                .field("entity_id", entity_id)
2743                .field("subscription_id", subscription_id)
2744                .finish(),
2745            Effect::ModelNotification { model_id } => f
2746                .debug_struct("Effect::ModelNotification")
2747                .field("model_id", model_id)
2748                .finish(),
2749            Effect::ViewNotification { window_id, view_id } => f
2750                .debug_struct("Effect::ViewNotification")
2751                .field("window_id", window_id)
2752                .field("view_id", view_id)
2753                .finish(),
2754            Effect::GlobalNotification { type_id } => f
2755                .debug_struct("Effect::GlobalNotification")
2756                .field("type_id", type_id)
2757                .finish(),
2758            Effect::Deferred { .. } => f.debug_struct("Effect::Deferred").finish(),
2759            Effect::ModelRelease { model_id, .. } => f
2760                .debug_struct("Effect::ModelRelease")
2761                .field("model_id", model_id)
2762                .finish(),
2763            Effect::ViewRelease { view_id, .. } => f
2764                .debug_struct("Effect::ViewRelease")
2765                .field("view_id", view_id)
2766                .finish(),
2767            Effect::Focus { window_id, view_id } => f
2768                .debug_struct("Effect::Focus")
2769                .field("window_id", window_id)
2770                .field("view_id", view_id)
2771                .finish(),
2772            Effect::FocusObservation {
2773                view_id,
2774                subscription_id,
2775                ..
2776            } => f
2777                .debug_struct("Effect::FocusObservation")
2778                .field("view_id", view_id)
2779                .field("subscription_id", subscription_id)
2780                .finish(),
2781            Effect::ResizeWindow { window_id } => f
2782                .debug_struct("Effect::RefreshWindow")
2783                .field("window_id", window_id)
2784                .finish(),
2785            Effect::ActivateWindow {
2786                window_id,
2787                is_active,
2788            } => f
2789                .debug_struct("Effect::ActivateWindow")
2790                .field("window_id", window_id)
2791                .field("is_active", is_active)
2792                .finish(),
2793            Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
2794        }
2795    }
2796}
2797
2798pub trait AnyModel {
2799    fn as_any(&self) -> &dyn Any;
2800    fn as_any_mut(&mut self) -> &mut dyn Any;
2801    fn release(&mut self, cx: &mut MutableAppContext);
2802    fn app_will_quit(
2803        &mut self,
2804        cx: &mut MutableAppContext,
2805    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2806}
2807
2808impl<T> AnyModel for T
2809where
2810    T: Entity,
2811{
2812    fn as_any(&self) -> &dyn Any {
2813        self
2814    }
2815
2816    fn as_any_mut(&mut self) -> &mut dyn Any {
2817        self
2818    }
2819
2820    fn release(&mut self, cx: &mut MutableAppContext) {
2821        self.release(cx);
2822    }
2823
2824    fn app_will_quit(
2825        &mut self,
2826        cx: &mut MutableAppContext,
2827    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2828        self.app_will_quit(cx)
2829    }
2830}
2831
2832pub trait AnyView {
2833    fn as_any(&self) -> &dyn Any;
2834    fn as_any_mut(&mut self) -> &mut dyn Any;
2835    fn release(&mut self, cx: &mut MutableAppContext);
2836    fn app_will_quit(
2837        &mut self,
2838        cx: &mut MutableAppContext,
2839    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2840    fn ui_name(&self) -> &'static str;
2841    fn render<'a>(
2842        &mut self,
2843        window_id: usize,
2844        view_id: usize,
2845        titlebar_height: f32,
2846        refreshing: bool,
2847        cx: &mut MutableAppContext,
2848    ) -> ElementBox;
2849    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
2850    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
2851    fn keymap_context(&self, cx: &AppContext) -> keymap::Context;
2852    fn debug_json(&self, cx: &AppContext) -> serde_json::Value;
2853}
2854
2855impl<T> AnyView for T
2856where
2857    T: View,
2858{
2859    fn as_any(&self) -> &dyn Any {
2860        self
2861    }
2862
2863    fn as_any_mut(&mut self) -> &mut dyn Any {
2864        self
2865    }
2866
2867    fn release(&mut self, cx: &mut MutableAppContext) {
2868        self.release(cx);
2869    }
2870
2871    fn app_will_quit(
2872        &mut self,
2873        cx: &mut MutableAppContext,
2874    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2875        self.app_will_quit(cx)
2876    }
2877
2878    fn ui_name(&self) -> &'static str {
2879        T::ui_name()
2880    }
2881
2882    fn render<'a>(
2883        &mut self,
2884        window_id: usize,
2885        view_id: usize,
2886        titlebar_height: f32,
2887        refreshing: bool,
2888        cx: &mut MutableAppContext,
2889    ) -> ElementBox {
2890        View::render(
2891            self,
2892            &mut RenderContext {
2893                window_id,
2894                view_id,
2895                app: cx,
2896                view_type: PhantomData::<T>,
2897                titlebar_height,
2898                refreshing,
2899            },
2900        )
2901    }
2902
2903    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
2904        let mut cx = ViewContext::new(cx, window_id, view_id);
2905        View::on_focus(self, &mut cx);
2906    }
2907
2908    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
2909        let mut cx = ViewContext::new(cx, window_id, view_id);
2910        View::on_blur(self, &mut cx);
2911    }
2912
2913    fn keymap_context(&self, cx: &AppContext) -> keymap::Context {
2914        View::keymap_context(self, cx)
2915    }
2916
2917    fn debug_json(&self, cx: &AppContext) -> serde_json::Value {
2918        View::debug_json(self, cx)
2919    }
2920}
2921
2922pub struct ModelContext<'a, T: ?Sized> {
2923    app: &'a mut MutableAppContext,
2924    model_id: usize,
2925    model_type: PhantomData<T>,
2926    halt_stream: bool,
2927}
2928
2929impl<'a, T: Entity> ModelContext<'a, T> {
2930    fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
2931        Self {
2932            app,
2933            model_id,
2934            model_type: PhantomData,
2935            halt_stream: false,
2936        }
2937    }
2938
2939    pub fn background(&self) -> &Arc<executor::Background> {
2940        &self.app.cx.background
2941    }
2942
2943    pub fn halt_stream(&mut self) {
2944        self.halt_stream = true;
2945    }
2946
2947    pub fn model_id(&self) -> usize {
2948        self.model_id
2949    }
2950
2951    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2952    where
2953        S: Entity,
2954        F: FnOnce(&mut ModelContext<S>) -> S,
2955    {
2956        self.app.add_model(build_model)
2957    }
2958
2959    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ModelContext<T>)) {
2960        let handle = self.handle();
2961        self.app.defer(move |cx| {
2962            handle.update(cx, |model, cx| {
2963                callback(model, cx);
2964            })
2965        })
2966    }
2967
2968    pub fn emit(&mut self, payload: T::Event) {
2969        self.app.pending_effects.push_back(Effect::Event {
2970            entity_id: self.model_id,
2971            payload: Box::new(payload),
2972        });
2973    }
2974
2975    pub fn notify(&mut self) {
2976        self.app.notify_model(self.model_id);
2977    }
2978
2979    pub fn subscribe<S: Entity, F>(
2980        &mut self,
2981        handle: &ModelHandle<S>,
2982        mut callback: F,
2983    ) -> Subscription
2984    where
2985        S::Event: 'static,
2986        F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
2987    {
2988        let subscriber = self.weak_handle();
2989        self.app
2990            .subscribe_internal(handle, move |emitter, event, cx| {
2991                if let Some(subscriber) = subscriber.upgrade(cx) {
2992                    subscriber.update(cx, |subscriber, cx| {
2993                        callback(subscriber, emitter, event, cx);
2994                    });
2995                    true
2996                } else {
2997                    false
2998                }
2999            })
3000    }
3001
3002    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
3003    where
3004        S: Entity,
3005        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
3006    {
3007        let observer = self.weak_handle();
3008        self.app.observe_internal(handle, move |observed, cx| {
3009            if let Some(observer) = observer.upgrade(cx) {
3010                observer.update(cx, |observer, cx| {
3011                    callback(observer, observed, cx);
3012                });
3013                true
3014            } else {
3015                false
3016            }
3017        })
3018    }
3019
3020    pub fn observe_release<S, F>(
3021        &mut self,
3022        handle: &ModelHandle<S>,
3023        mut callback: F,
3024    ) -> Subscription
3025    where
3026        S: Entity,
3027        F: 'static + FnMut(&mut T, &S, &mut ModelContext<T>),
3028    {
3029        let observer = self.weak_handle();
3030        self.app.observe_release(handle, move |released, cx| {
3031            if let Some(observer) = observer.upgrade(cx) {
3032                observer.update(cx, |observer, cx| {
3033                    callback(observer, released, cx);
3034                });
3035            }
3036        })
3037    }
3038
3039    pub fn handle(&self) -> ModelHandle<T> {
3040        ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
3041    }
3042
3043    pub fn weak_handle(&self) -> WeakModelHandle<T> {
3044        WeakModelHandle::new(self.model_id)
3045    }
3046
3047    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
3048    where
3049        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
3050        Fut: 'static + Future<Output = S>,
3051        S: 'static,
3052    {
3053        let handle = self.handle();
3054        self.app.spawn(|cx| f(handle, cx))
3055    }
3056
3057    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
3058    where
3059        F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
3060        Fut: 'static + Future<Output = S>,
3061        S: 'static,
3062    {
3063        let handle = self.weak_handle();
3064        self.app.spawn(|cx| f(handle, cx))
3065    }
3066}
3067
3068impl<M> AsRef<AppContext> for ModelContext<'_, M> {
3069    fn as_ref(&self) -> &AppContext {
3070        &self.app.cx
3071    }
3072}
3073
3074impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
3075    fn as_mut(&mut self) -> &mut MutableAppContext {
3076        self.app
3077    }
3078}
3079
3080impl<M> ReadModel for ModelContext<'_, M> {
3081    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
3082        self.app.read_model(handle)
3083    }
3084}
3085
3086impl<M> UpdateModel for ModelContext<'_, M> {
3087    fn update_model<T: Entity, V>(
3088        &mut self,
3089        handle: &ModelHandle<T>,
3090        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
3091    ) -> V {
3092        self.app.update_model(handle, update)
3093    }
3094}
3095
3096impl<M> UpgradeModelHandle for ModelContext<'_, M> {
3097    fn upgrade_model_handle<T: Entity>(
3098        &self,
3099        handle: &WeakModelHandle<T>,
3100    ) -> Option<ModelHandle<T>> {
3101        self.cx.upgrade_model_handle(handle)
3102    }
3103
3104    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
3105        self.cx.model_handle_is_upgradable(handle)
3106    }
3107
3108    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
3109        self.cx.upgrade_any_model_handle(handle)
3110    }
3111}
3112
3113impl<M> Deref for ModelContext<'_, M> {
3114    type Target = MutableAppContext;
3115
3116    fn deref(&self) -> &Self::Target {
3117        &self.app
3118    }
3119}
3120
3121impl<M> DerefMut for ModelContext<'_, M> {
3122    fn deref_mut(&mut self) -> &mut Self::Target {
3123        &mut self.app
3124    }
3125}
3126
3127pub struct ViewContext<'a, T: ?Sized> {
3128    app: &'a mut MutableAppContext,
3129    window_id: usize,
3130    view_id: usize,
3131    view_type: PhantomData<T>,
3132}
3133
3134impl<'a, T: View> ViewContext<'a, T> {
3135    fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
3136        Self {
3137            app,
3138            window_id,
3139            view_id,
3140            view_type: PhantomData,
3141        }
3142    }
3143
3144    pub fn handle(&self) -> ViewHandle<T> {
3145        ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
3146    }
3147
3148    pub fn weak_handle(&self) -> WeakViewHandle<T> {
3149        WeakViewHandle::new(self.window_id, self.view_id)
3150    }
3151
3152    pub fn window_id(&self) -> usize {
3153        self.window_id
3154    }
3155
3156    pub fn view_id(&self) -> usize {
3157        self.view_id
3158    }
3159
3160    pub fn foreground(&self) -> &Rc<executor::Foreground> {
3161        self.app.foreground()
3162    }
3163
3164    pub fn background_executor(&self) -> &Arc<executor::Background> {
3165        &self.app.cx.background
3166    }
3167
3168    pub fn platform(&self) -> Arc<dyn Platform> {
3169        self.app.platform()
3170    }
3171
3172    pub fn prompt(
3173        &self,
3174        level: PromptLevel,
3175        msg: &str,
3176        answers: &[&str],
3177    ) -> oneshot::Receiver<usize> {
3178        self.app.prompt(self.window_id, level, msg, answers)
3179    }
3180
3181    pub fn prompt_for_paths(
3182        &self,
3183        options: PathPromptOptions,
3184    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
3185        self.app.prompt_for_paths(options)
3186    }
3187
3188    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
3189        self.app.prompt_for_new_path(directory)
3190    }
3191
3192    pub fn debug_elements(&self) -> crate::json::Value {
3193        self.app.debug_elements(self.window_id).unwrap()
3194    }
3195
3196    pub fn focus<S>(&mut self, handle: S)
3197    where
3198        S: Into<AnyViewHandle>,
3199    {
3200        let handle = handle.into();
3201        self.app.focus(handle.window_id, Some(handle.view_id));
3202    }
3203
3204    pub fn focus_self(&mut self) {
3205        self.app.focus(self.window_id, Some(self.view_id));
3206    }
3207
3208    pub fn blur(&mut self) {
3209        self.app.focus(self.window_id, None);
3210    }
3211
3212    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
3213    where
3214        S: Entity,
3215        F: FnOnce(&mut ModelContext<S>) -> S,
3216    {
3217        self.app.add_model(build_model)
3218    }
3219
3220    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
3221    where
3222        S: View,
3223        F: FnOnce(&mut ViewContext<S>) -> S,
3224    {
3225        self.app.add_view(self.window_id, build_view)
3226    }
3227
3228    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
3229    where
3230        S: View,
3231        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
3232    {
3233        self.app.add_option_view(self.window_id, build_view)
3234    }
3235
3236    pub fn replace_root_view<V, F>(&mut self, build_root_view: F) -> ViewHandle<V>
3237    where
3238        V: View,
3239        F: FnOnce(&mut ViewContext<V>) -> V,
3240    {
3241        let window_id = self.window_id;
3242        self.update(|this| {
3243            let root_view = this.add_view(window_id, build_root_view);
3244            let window = this.cx.windows.get_mut(&window_id).unwrap();
3245            window.root_view = root_view.clone().into();
3246            window.focused_view_id = Some(root_view.id());
3247            root_view
3248        })
3249    }
3250
3251    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
3252    where
3253        E: Entity,
3254        E::Event: 'static,
3255        H: Handle<E>,
3256        F: 'static + FnMut(&mut T, H, &E::Event, &mut ViewContext<T>),
3257    {
3258        let subscriber = self.weak_handle();
3259        self.app
3260            .subscribe_internal(handle, move |emitter, event, cx| {
3261                if let Some(subscriber) = subscriber.upgrade(cx) {
3262                    subscriber.update(cx, |subscriber, cx| {
3263                        callback(subscriber, emitter, event, cx);
3264                    });
3265                    true
3266                } else {
3267                    false
3268                }
3269            })
3270    }
3271
3272    pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3273    where
3274        E: Entity,
3275        H: Handle<E>,
3276        F: 'static + FnMut(&mut T, H, &mut ViewContext<T>),
3277    {
3278        let observer = self.weak_handle();
3279        self.app.observe_internal(handle, move |observed, cx| {
3280            if let Some(observer) = observer.upgrade(cx) {
3281                observer.update(cx, |observer, cx| {
3282                    callback(observer, observed, cx);
3283                });
3284                true
3285            } else {
3286                false
3287            }
3288        })
3289    }
3290
3291    pub fn observe_focus<F, V>(&mut self, handle: &ViewHandle<V>, mut callback: F) -> Subscription
3292    where
3293        F: 'static + FnMut(&mut T, ViewHandle<V>, &mut ViewContext<T>),
3294        V: View,
3295    {
3296        let observer = self.weak_handle();
3297        self.app.observe_focus(handle, move |observed, cx| {
3298            if let Some(observer) = observer.upgrade(cx) {
3299                observer.update(cx, |observer, cx| {
3300                    callback(observer, observed, cx);
3301                });
3302                true
3303            } else {
3304                false
3305            }
3306        })
3307    }
3308
3309    pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3310    where
3311        E: Entity,
3312        H: Handle<E>,
3313        F: 'static + FnMut(&mut T, &E, &mut ViewContext<T>),
3314    {
3315        let observer = self.weak_handle();
3316        self.app.observe_release(handle, move |released, cx| {
3317            if let Some(observer) = observer.upgrade(cx) {
3318                observer.update(cx, |observer, cx| {
3319                    callback(observer, released, cx);
3320                });
3321            }
3322        })
3323    }
3324
3325    pub fn emit(&mut self, payload: T::Event) {
3326        self.app.pending_effects.push_back(Effect::Event {
3327            entity_id: self.view_id,
3328            payload: Box::new(payload),
3329        });
3330    }
3331
3332    pub fn notify(&mut self) {
3333        self.app.notify_view(self.window_id, self.view_id);
3334    }
3335
3336    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>)) {
3337        let handle = self.handle();
3338        self.app.defer(move |cx| {
3339            handle.update(cx, |view, cx| {
3340                callback(view, cx);
3341            })
3342        })
3343    }
3344
3345    pub fn after_window_update(
3346        &mut self,
3347        callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>),
3348    ) {
3349        let handle = self.handle();
3350        self.app.after_window_update(move |cx| {
3351            handle.update(cx, |view, cx| {
3352                callback(view, cx);
3353            })
3354        })
3355    }
3356
3357    pub fn propagate_action(&mut self) {
3358        self.app.halt_action_dispatch = false;
3359    }
3360
3361    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
3362    where
3363        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
3364        Fut: 'static + Future<Output = S>,
3365        S: 'static,
3366    {
3367        let handle = self.handle();
3368        self.app.spawn(|cx| f(handle, cx))
3369    }
3370
3371    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
3372    where
3373        F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut,
3374        Fut: 'static + Future<Output = S>,
3375        S: 'static,
3376    {
3377        let handle = self.weak_handle();
3378        self.app.spawn(|cx| f(handle, cx))
3379    }
3380}
3381
3382pub struct RenderContext<'a, T: View> {
3383    pub app: &'a mut MutableAppContext,
3384    pub titlebar_height: f32,
3385    pub refreshing: bool,
3386    window_id: usize,
3387    view_id: usize,
3388    view_type: PhantomData<T>,
3389}
3390
3391impl<'a, T: View> RenderContext<'a, T> {
3392    pub fn handle(&self) -> WeakViewHandle<T> {
3393        WeakViewHandle::new(self.window_id, self.view_id)
3394    }
3395
3396    pub fn view_id(&self) -> usize {
3397        self.view_id
3398    }
3399}
3400
3401impl AsRef<AppContext> for &AppContext {
3402    fn as_ref(&self) -> &AppContext {
3403        self
3404    }
3405}
3406
3407impl<V: View> Deref for RenderContext<'_, V> {
3408    type Target = MutableAppContext;
3409
3410    fn deref(&self) -> &Self::Target {
3411        self.app
3412    }
3413}
3414
3415impl<V: View> DerefMut for RenderContext<'_, V> {
3416    fn deref_mut(&mut self) -> &mut Self::Target {
3417        self.app
3418    }
3419}
3420
3421impl<V: View> ReadModel for RenderContext<'_, V> {
3422    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
3423        self.app.read_model(handle)
3424    }
3425}
3426
3427impl<V: View> UpdateModel for RenderContext<'_, V> {
3428    fn update_model<T: Entity, O>(
3429        &mut self,
3430        handle: &ModelHandle<T>,
3431        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
3432    ) -> O {
3433        self.app.update_model(handle, update)
3434    }
3435}
3436
3437impl<V: View> ReadView for RenderContext<'_, V> {
3438    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
3439        self.app.read_view(handle)
3440    }
3441}
3442
3443impl<V: View> ElementStateContext for RenderContext<'_, V> {
3444    fn current_view_id(&self) -> usize {
3445        self.view_id
3446    }
3447}
3448
3449impl<M> AsRef<AppContext> for ViewContext<'_, M> {
3450    fn as_ref(&self) -> &AppContext {
3451        &self.app.cx
3452    }
3453}
3454
3455impl<M> Deref for ViewContext<'_, M> {
3456    type Target = MutableAppContext;
3457
3458    fn deref(&self) -> &Self::Target {
3459        &self.app
3460    }
3461}
3462
3463impl<M> DerefMut for ViewContext<'_, M> {
3464    fn deref_mut(&mut self) -> &mut Self::Target {
3465        &mut self.app
3466    }
3467}
3468
3469impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
3470    fn as_mut(&mut self) -> &mut MutableAppContext {
3471        self.app
3472    }
3473}
3474
3475impl<V> ReadModel for ViewContext<'_, V> {
3476    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
3477        self.app.read_model(handle)
3478    }
3479}
3480
3481impl<V> UpgradeModelHandle for ViewContext<'_, V> {
3482    fn upgrade_model_handle<T: Entity>(
3483        &self,
3484        handle: &WeakModelHandle<T>,
3485    ) -> Option<ModelHandle<T>> {
3486        self.cx.upgrade_model_handle(handle)
3487    }
3488
3489    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
3490        self.cx.model_handle_is_upgradable(handle)
3491    }
3492
3493    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
3494        self.cx.upgrade_any_model_handle(handle)
3495    }
3496}
3497
3498impl<V> UpgradeViewHandle for ViewContext<'_, V> {
3499    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
3500        self.cx.upgrade_view_handle(handle)
3501    }
3502
3503    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
3504        self.cx.upgrade_any_view_handle(handle)
3505    }
3506}
3507
3508impl<V: View> UpdateModel for ViewContext<'_, V> {
3509    fn update_model<T: Entity, O>(
3510        &mut self,
3511        handle: &ModelHandle<T>,
3512        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
3513    ) -> O {
3514        self.app.update_model(handle, update)
3515    }
3516}
3517
3518impl<V: View> ReadView for ViewContext<'_, V> {
3519    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
3520        self.app.read_view(handle)
3521    }
3522}
3523
3524impl<V: View> UpdateView for ViewContext<'_, V> {
3525    fn update_view<T, S>(
3526        &mut self,
3527        handle: &ViewHandle<T>,
3528        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
3529    ) -> S
3530    where
3531        T: View,
3532    {
3533        self.app.update_view(handle, update)
3534    }
3535}
3536
3537impl<V: View> ElementStateContext for ViewContext<'_, V> {
3538    fn current_view_id(&self) -> usize {
3539        self.view_id
3540    }
3541}
3542
3543pub trait Handle<T> {
3544    type Weak: 'static;
3545    fn id(&self) -> usize;
3546    fn location(&self) -> EntityLocation;
3547    fn downgrade(&self) -> Self::Weak;
3548    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3549    where
3550        Self: Sized;
3551}
3552
3553pub trait WeakHandle {
3554    fn id(&self) -> usize;
3555}
3556
3557#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
3558pub enum EntityLocation {
3559    Model(usize),
3560    View(usize, usize),
3561}
3562
3563pub struct ModelHandle<T: Entity> {
3564    model_id: usize,
3565    model_type: PhantomData<T>,
3566    ref_counts: Arc<Mutex<RefCounts>>,
3567
3568    #[cfg(any(test, feature = "test-support"))]
3569    handle_id: usize,
3570}
3571
3572impl<T: Entity> ModelHandle<T> {
3573    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3574        ref_counts.lock().inc_model(model_id);
3575
3576        #[cfg(any(test, feature = "test-support"))]
3577        let handle_id = ref_counts
3578            .lock()
3579            .leak_detector
3580            .lock()
3581            .handle_created(Some(type_name::<T>()), model_id);
3582
3583        Self {
3584            model_id,
3585            model_type: PhantomData,
3586            ref_counts: ref_counts.clone(),
3587
3588            #[cfg(any(test, feature = "test-support"))]
3589            handle_id,
3590        }
3591    }
3592
3593    pub fn downgrade(&self) -> WeakModelHandle<T> {
3594        WeakModelHandle::new(self.model_id)
3595    }
3596
3597    pub fn id(&self) -> usize {
3598        self.model_id
3599    }
3600
3601    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
3602        cx.read_model(self)
3603    }
3604
3605    pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
3606    where
3607        C: ReadModelWith,
3608        F: FnOnce(&T, &AppContext) -> S,
3609    {
3610        let mut read = Some(read);
3611        cx.read_model_with(self, &mut |model, cx| {
3612            let read = read.take().unwrap();
3613            read(model, cx)
3614        })
3615    }
3616
3617    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3618    where
3619        C: UpdateModel,
3620        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
3621    {
3622        let mut update = Some(update);
3623        cx.update_model(self, &mut |model, cx| {
3624            let update = update.take().unwrap();
3625            update(model, cx)
3626        })
3627    }
3628
3629    #[cfg(any(test, feature = "test-support"))]
3630    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
3631        let (tx, mut rx) = futures::channel::mpsc::unbounded();
3632        let mut cx = cx.cx.borrow_mut();
3633        let subscription = cx.observe(self, move |_, _| {
3634            tx.unbounded_send(()).ok();
3635        });
3636
3637        let duration = if std::env::var("CI").is_ok() {
3638            Duration::from_secs(5)
3639        } else {
3640            Duration::from_secs(1)
3641        };
3642
3643        async move {
3644            let notification = crate::util::timeout(duration, rx.next())
3645                .await
3646                .expect("next notification timed out");
3647            drop(subscription);
3648            notification.expect("model dropped while test was waiting for its next notification")
3649        }
3650    }
3651
3652    #[cfg(any(test, feature = "test-support"))]
3653    pub fn next_event(&self, cx: &TestAppContext) -> impl Future<Output = T::Event>
3654    where
3655        T::Event: Clone,
3656    {
3657        let (tx, mut rx) = futures::channel::mpsc::unbounded();
3658        let mut cx = cx.cx.borrow_mut();
3659        let subscription = cx.subscribe(self, move |_, event, _| {
3660            tx.unbounded_send(event.clone()).ok();
3661        });
3662
3663        let duration = if std::env::var("CI").is_ok() {
3664            Duration::from_secs(5)
3665        } else {
3666            Duration::from_secs(1)
3667        };
3668
3669        cx.foreground.start_waiting();
3670        async move {
3671            let event = crate::util::timeout(duration, rx.next())
3672                .await
3673                .expect("next event timed out");
3674            drop(subscription);
3675            event.expect("model dropped while test was waiting for its next event")
3676        }
3677    }
3678
3679    #[cfg(any(test, feature = "test-support"))]
3680    pub fn condition(
3681        &self,
3682        cx: &TestAppContext,
3683        mut predicate: impl FnMut(&T, &AppContext) -> bool,
3684    ) -> impl Future<Output = ()> {
3685        let (tx, mut rx) = futures::channel::mpsc::unbounded();
3686
3687        let mut cx = cx.cx.borrow_mut();
3688        let subscriptions = (
3689            cx.observe(self, {
3690                let tx = tx.clone();
3691                move |_, _| {
3692                    tx.unbounded_send(()).ok();
3693                }
3694            }),
3695            cx.subscribe(self, {
3696                let tx = tx.clone();
3697                move |_, _, _| {
3698                    tx.unbounded_send(()).ok();
3699                }
3700            }),
3701        );
3702
3703        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
3704        let handle = self.downgrade();
3705        let duration = if std::env::var("CI").is_ok() {
3706            Duration::from_secs(5)
3707        } else {
3708            Duration::from_secs(1)
3709        };
3710
3711        async move {
3712            crate::util::timeout(duration, async move {
3713                loop {
3714                    {
3715                        let cx = cx.borrow();
3716                        let cx = cx.as_ref();
3717                        if predicate(
3718                            handle
3719                                .upgrade(cx)
3720                                .expect("model dropped with pending condition")
3721                                .read(cx),
3722                            cx,
3723                        ) {
3724                            break;
3725                        }
3726                    }
3727
3728                    cx.borrow().foreground().start_waiting();
3729                    rx.next()
3730                        .await
3731                        .expect("model dropped with pending condition");
3732                    cx.borrow().foreground().finish_waiting();
3733                }
3734            })
3735            .await
3736            .expect("condition timed out");
3737            drop(subscriptions);
3738        }
3739    }
3740}
3741
3742impl<T: Entity> Clone for ModelHandle<T> {
3743    fn clone(&self) -> Self {
3744        Self::new(self.model_id, &self.ref_counts)
3745    }
3746}
3747
3748impl<T: Entity> PartialEq for ModelHandle<T> {
3749    fn eq(&self, other: &Self) -> bool {
3750        self.model_id == other.model_id
3751    }
3752}
3753
3754impl<T: Entity> Eq for ModelHandle<T> {}
3755
3756impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
3757    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
3758        self.model_id == other.model_id
3759    }
3760}
3761
3762impl<T: Entity> Hash for ModelHandle<T> {
3763    fn hash<H: Hasher>(&self, state: &mut H) {
3764        self.model_id.hash(state);
3765    }
3766}
3767
3768impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
3769    fn borrow(&self) -> &usize {
3770        &self.model_id
3771    }
3772}
3773
3774impl<T: Entity> Debug for ModelHandle<T> {
3775    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3776        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
3777            .field(&self.model_id)
3778            .finish()
3779    }
3780}
3781
3782unsafe impl<T: Entity> Send for ModelHandle<T> {}
3783unsafe impl<T: Entity> Sync for ModelHandle<T> {}
3784
3785impl<T: Entity> Drop for ModelHandle<T> {
3786    fn drop(&mut self) {
3787        let mut ref_counts = self.ref_counts.lock();
3788        ref_counts.dec_model(self.model_id);
3789
3790        #[cfg(any(test, feature = "test-support"))]
3791        ref_counts
3792            .leak_detector
3793            .lock()
3794            .handle_dropped(self.model_id, self.handle_id);
3795    }
3796}
3797
3798impl<T: Entity> Handle<T> for ModelHandle<T> {
3799    type Weak = WeakModelHandle<T>;
3800
3801    fn id(&self) -> usize {
3802        self.model_id
3803    }
3804
3805    fn location(&self) -> EntityLocation {
3806        EntityLocation::Model(self.model_id)
3807    }
3808
3809    fn downgrade(&self) -> Self::Weak {
3810        self.downgrade()
3811    }
3812
3813    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3814    where
3815        Self: Sized,
3816    {
3817        weak.upgrade(cx)
3818    }
3819}
3820
3821pub struct WeakModelHandle<T> {
3822    model_id: usize,
3823    model_type: PhantomData<T>,
3824}
3825
3826impl<T> WeakHandle for WeakModelHandle<T> {
3827    fn id(&self) -> usize {
3828        self.model_id
3829    }
3830}
3831
3832unsafe impl<T> Send for WeakModelHandle<T> {}
3833unsafe impl<T> Sync for WeakModelHandle<T> {}
3834
3835impl<T: Entity> WeakModelHandle<T> {
3836    fn new(model_id: usize) -> Self {
3837        Self {
3838            model_id,
3839            model_type: PhantomData,
3840        }
3841    }
3842
3843    pub fn id(&self) -> usize {
3844        self.model_id
3845    }
3846
3847    pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
3848        cx.model_handle_is_upgradable(self)
3849    }
3850
3851    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
3852        cx.upgrade_model_handle(self)
3853    }
3854}
3855
3856impl<T> Hash for WeakModelHandle<T> {
3857    fn hash<H: Hasher>(&self, state: &mut H) {
3858        self.model_id.hash(state)
3859    }
3860}
3861
3862impl<T> PartialEq for WeakModelHandle<T> {
3863    fn eq(&self, other: &Self) -> bool {
3864        self.model_id == other.model_id
3865    }
3866}
3867
3868impl<T> Eq for WeakModelHandle<T> {}
3869
3870impl<T> Clone for WeakModelHandle<T> {
3871    fn clone(&self) -> Self {
3872        Self {
3873            model_id: self.model_id,
3874            model_type: PhantomData,
3875        }
3876    }
3877}
3878
3879impl<T> Copy for WeakModelHandle<T> {}
3880
3881pub struct ViewHandle<T> {
3882    window_id: usize,
3883    view_id: usize,
3884    view_type: PhantomData<T>,
3885    ref_counts: Arc<Mutex<RefCounts>>,
3886    #[cfg(any(test, feature = "test-support"))]
3887    handle_id: usize,
3888}
3889
3890impl<T: View> ViewHandle<T> {
3891    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3892        ref_counts.lock().inc_view(window_id, view_id);
3893        #[cfg(any(test, feature = "test-support"))]
3894        let handle_id = ref_counts
3895            .lock()
3896            .leak_detector
3897            .lock()
3898            .handle_created(Some(type_name::<T>()), view_id);
3899
3900        Self {
3901            window_id,
3902            view_id,
3903            view_type: PhantomData,
3904            ref_counts: ref_counts.clone(),
3905
3906            #[cfg(any(test, feature = "test-support"))]
3907            handle_id,
3908        }
3909    }
3910
3911    pub fn downgrade(&self) -> WeakViewHandle<T> {
3912        WeakViewHandle::new(self.window_id, self.view_id)
3913    }
3914
3915    pub fn window_id(&self) -> usize {
3916        self.window_id
3917    }
3918
3919    pub fn id(&self) -> usize {
3920        self.view_id
3921    }
3922
3923    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
3924        cx.read_view(self)
3925    }
3926
3927    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3928    where
3929        C: ReadViewWith,
3930        F: FnOnce(&T, &AppContext) -> S,
3931    {
3932        let mut read = Some(read);
3933        cx.read_view_with(self, &mut |view, cx| {
3934            let read = read.take().unwrap();
3935            read(view, cx)
3936        })
3937    }
3938
3939    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3940    where
3941        C: UpdateView,
3942        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
3943    {
3944        let mut update = Some(update);
3945        cx.update_view(self, &mut |view, cx| {
3946            let update = update.take().unwrap();
3947            update(view, cx)
3948        })
3949    }
3950
3951    pub fn defer<C, F>(&self, cx: &mut C, update: F)
3952    where
3953        C: AsMut<MutableAppContext>,
3954        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
3955    {
3956        let this = self.clone();
3957        cx.as_mut().defer(move |cx| {
3958            this.update(cx, |view, cx| update(view, cx));
3959        });
3960    }
3961
3962    pub fn is_focused(&self, cx: &AppContext) -> bool {
3963        cx.focused_view_id(self.window_id)
3964            .map_or(false, |focused_id| focused_id == self.view_id)
3965    }
3966
3967    #[cfg(any(test, feature = "test-support"))]
3968    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
3969        use postage::prelude::{Sink as _, Stream as _};
3970
3971        let (mut tx, mut rx) = postage::mpsc::channel(1);
3972        let mut cx = cx.cx.borrow_mut();
3973        let subscription = cx.observe(self, move |_, _| {
3974            tx.try_send(()).ok();
3975        });
3976
3977        let duration = if std::env::var("CI").is_ok() {
3978            Duration::from_secs(5)
3979        } else {
3980            Duration::from_secs(1)
3981        };
3982
3983        async move {
3984            let notification = crate::util::timeout(duration, rx.recv())
3985                .await
3986                .expect("next notification timed out");
3987            drop(subscription);
3988            notification.expect("model dropped while test was waiting for its next notification")
3989        }
3990    }
3991
3992    #[cfg(any(test, feature = "test-support"))]
3993    pub fn condition(
3994        &self,
3995        cx: &TestAppContext,
3996        mut predicate: impl FnMut(&T, &AppContext) -> bool,
3997    ) -> impl Future<Output = ()> {
3998        use postage::prelude::{Sink as _, Stream as _};
3999
4000        let (tx, mut rx) = postage::mpsc::channel(1024);
4001
4002        let mut cx = cx.cx.borrow_mut();
4003        let subscriptions = self.update(&mut *cx, |_, cx| {
4004            (
4005                cx.observe(self, {
4006                    let mut tx = tx.clone();
4007                    move |_, _, _| {
4008                        tx.blocking_send(()).ok();
4009                    }
4010                }),
4011                cx.subscribe(self, {
4012                    let mut tx = tx.clone();
4013                    move |_, _, _, _| {
4014                        tx.blocking_send(()).ok();
4015                    }
4016                }),
4017            )
4018        });
4019
4020        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
4021        let handle = self.downgrade();
4022        let duration = if std::env::var("CI").is_ok() {
4023            Duration::from_secs(2)
4024        } else {
4025            Duration::from_millis(500)
4026        };
4027
4028        async move {
4029            crate::util::timeout(duration, async move {
4030                loop {
4031                    {
4032                        let cx = cx.borrow();
4033                        let cx = cx.as_ref();
4034                        if predicate(
4035                            handle
4036                                .upgrade(cx)
4037                                .expect("view dropped with pending condition")
4038                                .read(cx),
4039                            cx,
4040                        ) {
4041                            break;
4042                        }
4043                    }
4044
4045                    cx.borrow().foreground().start_waiting();
4046                    rx.recv()
4047                        .await
4048                        .expect("view dropped with pending condition");
4049                    cx.borrow().foreground().finish_waiting();
4050                }
4051            })
4052            .await
4053            .expect("condition timed out");
4054            drop(subscriptions);
4055        }
4056    }
4057}
4058
4059impl<T: View> Clone for ViewHandle<T> {
4060    fn clone(&self) -> Self {
4061        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
4062    }
4063}
4064
4065impl<T> PartialEq for ViewHandle<T> {
4066    fn eq(&self, other: &Self) -> bool {
4067        self.window_id == other.window_id && self.view_id == other.view_id
4068    }
4069}
4070
4071impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
4072    fn eq(&self, other: &WeakViewHandle<T>) -> bool {
4073        self.window_id == other.window_id && self.view_id == other.view_id
4074    }
4075}
4076
4077impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
4078    fn eq(&self, other: &ViewHandle<T>) -> bool {
4079        self.window_id == other.window_id && self.view_id == other.view_id
4080    }
4081}
4082
4083impl<T> Eq for ViewHandle<T> {}
4084
4085impl<T> Hash for ViewHandle<T> {
4086    fn hash<H: Hasher>(&self, state: &mut H) {
4087        self.window_id.hash(state);
4088        self.view_id.hash(state);
4089    }
4090}
4091
4092impl<T> Debug for ViewHandle<T> {
4093    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4094        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
4095            .field("window_id", &self.window_id)
4096            .field("view_id", &self.view_id)
4097            .finish()
4098    }
4099}
4100
4101impl<T> Drop for ViewHandle<T> {
4102    fn drop(&mut self) {
4103        self.ref_counts
4104            .lock()
4105            .dec_view(self.window_id, self.view_id);
4106        #[cfg(any(test, feature = "test-support"))]
4107        self.ref_counts
4108            .lock()
4109            .leak_detector
4110            .lock()
4111            .handle_dropped(self.view_id, self.handle_id);
4112    }
4113}
4114
4115impl<T: View> Handle<T> for ViewHandle<T> {
4116    type Weak = WeakViewHandle<T>;
4117
4118    fn id(&self) -> usize {
4119        self.view_id
4120    }
4121
4122    fn location(&self) -> EntityLocation {
4123        EntityLocation::View(self.window_id, self.view_id)
4124    }
4125
4126    fn downgrade(&self) -> Self::Weak {
4127        self.downgrade()
4128    }
4129
4130    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4131    where
4132        Self: Sized,
4133    {
4134        weak.upgrade(cx)
4135    }
4136}
4137
4138pub struct AnyViewHandle {
4139    window_id: usize,
4140    view_id: usize,
4141    view_type: TypeId,
4142    ref_counts: Arc<Mutex<RefCounts>>,
4143
4144    #[cfg(any(test, feature = "test-support"))]
4145    handle_id: usize,
4146}
4147
4148impl AnyViewHandle {
4149    fn new(
4150        window_id: usize,
4151        view_id: usize,
4152        view_type: TypeId,
4153        ref_counts: Arc<Mutex<RefCounts>>,
4154    ) -> Self {
4155        ref_counts.lock().inc_view(window_id, view_id);
4156
4157        #[cfg(any(test, feature = "test-support"))]
4158        let handle_id = ref_counts
4159            .lock()
4160            .leak_detector
4161            .lock()
4162            .handle_created(None, view_id);
4163
4164        Self {
4165            window_id,
4166            view_id,
4167            view_type,
4168            ref_counts,
4169            #[cfg(any(test, feature = "test-support"))]
4170            handle_id,
4171        }
4172    }
4173
4174    pub fn id(&self) -> usize {
4175        self.view_id
4176    }
4177
4178    pub fn is<T: 'static>(&self) -> bool {
4179        TypeId::of::<T>() == self.view_type
4180    }
4181
4182    pub fn is_focused(&self, cx: &AppContext) -> bool {
4183        cx.focused_view_id(self.window_id)
4184            .map_or(false, |focused_id| focused_id == self.view_id)
4185    }
4186
4187    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
4188        if self.is::<T>() {
4189            let result = Some(ViewHandle {
4190                window_id: self.window_id,
4191                view_id: self.view_id,
4192                ref_counts: self.ref_counts.clone(),
4193                view_type: PhantomData,
4194                #[cfg(any(test, feature = "test-support"))]
4195                handle_id: self.handle_id,
4196            });
4197            unsafe {
4198                Arc::decrement_strong_count(&self.ref_counts);
4199            }
4200            std::mem::forget(self);
4201            result
4202        } else {
4203            None
4204        }
4205    }
4206
4207    pub fn downgrade(&self) -> AnyWeakViewHandle {
4208        AnyWeakViewHandle {
4209            window_id: self.window_id,
4210            view_id: self.view_id,
4211            view_type: self.view_type,
4212        }
4213    }
4214
4215    pub fn view_type(&self) -> TypeId {
4216        self.view_type
4217    }
4218
4219    pub fn debug_json(&self, cx: &AppContext) -> serde_json::Value {
4220        cx.views
4221            .get(&(self.window_id, self.view_id))
4222            .map_or_else(|| serde_json::Value::Null, |view| view.debug_json(cx))
4223    }
4224}
4225
4226impl Clone for AnyViewHandle {
4227    fn clone(&self) -> Self {
4228        Self::new(
4229            self.window_id,
4230            self.view_id,
4231            self.view_type,
4232            self.ref_counts.clone(),
4233        )
4234    }
4235}
4236
4237impl From<&AnyViewHandle> for AnyViewHandle {
4238    fn from(handle: &AnyViewHandle) -> Self {
4239        handle.clone()
4240    }
4241}
4242
4243impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
4244    fn from(handle: &ViewHandle<T>) -> Self {
4245        Self::new(
4246            handle.window_id,
4247            handle.view_id,
4248            TypeId::of::<T>(),
4249            handle.ref_counts.clone(),
4250        )
4251    }
4252}
4253
4254impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
4255    fn from(handle: ViewHandle<T>) -> Self {
4256        let any_handle = AnyViewHandle {
4257            window_id: handle.window_id,
4258            view_id: handle.view_id,
4259            view_type: TypeId::of::<T>(),
4260            ref_counts: handle.ref_counts.clone(),
4261            #[cfg(any(test, feature = "test-support"))]
4262            handle_id: handle.handle_id,
4263        };
4264        unsafe {
4265            Arc::decrement_strong_count(&handle.ref_counts);
4266        }
4267        std::mem::forget(handle);
4268        any_handle
4269    }
4270}
4271
4272impl Drop for AnyViewHandle {
4273    fn drop(&mut self) {
4274        self.ref_counts
4275            .lock()
4276            .dec_view(self.window_id, self.view_id);
4277        #[cfg(any(test, feature = "test-support"))]
4278        self.ref_counts
4279            .lock()
4280            .leak_detector
4281            .lock()
4282            .handle_dropped(self.view_id, self.handle_id);
4283    }
4284}
4285
4286pub struct AnyModelHandle {
4287    model_id: usize,
4288    model_type: TypeId,
4289    ref_counts: Arc<Mutex<RefCounts>>,
4290
4291    #[cfg(any(test, feature = "test-support"))]
4292    handle_id: usize,
4293}
4294
4295impl AnyModelHandle {
4296    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
4297        ref_counts.lock().inc_model(model_id);
4298
4299        #[cfg(any(test, feature = "test-support"))]
4300        let handle_id = ref_counts
4301            .lock()
4302            .leak_detector
4303            .lock()
4304            .handle_created(None, model_id);
4305
4306        Self {
4307            model_id,
4308            model_type,
4309            ref_counts,
4310
4311            #[cfg(any(test, feature = "test-support"))]
4312            handle_id,
4313        }
4314    }
4315
4316    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
4317        if self.is::<T>() {
4318            let result = Some(ModelHandle {
4319                model_id: self.model_id,
4320                model_type: PhantomData,
4321                ref_counts: self.ref_counts.clone(),
4322
4323                #[cfg(any(test, feature = "test-support"))]
4324                handle_id: self.handle_id,
4325            });
4326            unsafe {
4327                Arc::decrement_strong_count(&self.ref_counts);
4328            }
4329            std::mem::forget(self);
4330            result
4331        } else {
4332            None
4333        }
4334    }
4335
4336    pub fn downgrade(&self) -> AnyWeakModelHandle {
4337        AnyWeakModelHandle {
4338            model_id: self.model_id,
4339            model_type: self.model_type,
4340        }
4341    }
4342
4343    pub fn is<T: Entity>(&self) -> bool {
4344        self.model_type == TypeId::of::<T>()
4345    }
4346
4347    pub fn model_type(&self) -> TypeId {
4348        self.model_type
4349    }
4350}
4351
4352impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
4353    fn from(handle: ModelHandle<T>) -> Self {
4354        Self::new(
4355            handle.model_id,
4356            TypeId::of::<T>(),
4357            handle.ref_counts.clone(),
4358        )
4359    }
4360}
4361
4362impl Clone for AnyModelHandle {
4363    fn clone(&self) -> Self {
4364        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
4365    }
4366}
4367
4368impl Drop for AnyModelHandle {
4369    fn drop(&mut self) {
4370        let mut ref_counts = self.ref_counts.lock();
4371        ref_counts.dec_model(self.model_id);
4372
4373        #[cfg(any(test, feature = "test-support"))]
4374        ref_counts
4375            .leak_detector
4376            .lock()
4377            .handle_dropped(self.model_id, self.handle_id);
4378    }
4379}
4380
4381pub struct AnyWeakModelHandle {
4382    model_id: usize,
4383    model_type: TypeId,
4384}
4385
4386impl AnyWeakModelHandle {
4387    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
4388        cx.upgrade_any_model_handle(self)
4389    }
4390}
4391
4392impl<T: Entity> From<WeakModelHandle<T>> for AnyWeakModelHandle {
4393    fn from(handle: WeakModelHandle<T>) -> Self {
4394        AnyWeakModelHandle {
4395            model_id: handle.model_id,
4396            model_type: TypeId::of::<T>(),
4397        }
4398    }
4399}
4400
4401pub struct WeakViewHandle<T> {
4402    window_id: usize,
4403    view_id: usize,
4404    view_type: PhantomData<T>,
4405}
4406
4407impl<T> WeakHandle for WeakViewHandle<T> {
4408    fn id(&self) -> usize {
4409        self.view_id
4410    }
4411}
4412
4413impl<T: View> WeakViewHandle<T> {
4414    fn new(window_id: usize, view_id: usize) -> Self {
4415        Self {
4416            window_id,
4417            view_id,
4418            view_type: PhantomData,
4419        }
4420    }
4421
4422    pub fn id(&self) -> usize {
4423        self.view_id
4424    }
4425
4426    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
4427        cx.upgrade_view_handle(self)
4428    }
4429}
4430
4431impl<T> Clone for WeakViewHandle<T> {
4432    fn clone(&self) -> Self {
4433        Self {
4434            window_id: self.window_id,
4435            view_id: self.view_id,
4436            view_type: PhantomData,
4437        }
4438    }
4439}
4440
4441impl<T> PartialEq for WeakViewHandle<T> {
4442    fn eq(&self, other: &Self) -> bool {
4443        self.window_id == other.window_id && self.view_id == other.view_id
4444    }
4445}
4446
4447impl<T> Eq for WeakViewHandle<T> {}
4448
4449impl<T> Hash for WeakViewHandle<T> {
4450    fn hash<H: Hasher>(&self, state: &mut H) {
4451        self.window_id.hash(state);
4452        self.view_id.hash(state);
4453    }
4454}
4455
4456pub struct AnyWeakViewHandle {
4457    window_id: usize,
4458    view_id: usize,
4459    view_type: TypeId,
4460}
4461
4462impl AnyWeakViewHandle {
4463    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<AnyViewHandle> {
4464        cx.upgrade_any_view_handle(self)
4465    }
4466}
4467
4468impl<T: View> From<WeakViewHandle<T>> for AnyWeakViewHandle {
4469    fn from(handle: WeakViewHandle<T>) -> Self {
4470        AnyWeakViewHandle {
4471            window_id: handle.window_id,
4472            view_id: handle.view_id,
4473            view_type: TypeId::of::<T>(),
4474        }
4475    }
4476}
4477
4478#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4479pub struct ElementStateId {
4480    view_id: usize,
4481    element_id: usize,
4482    tag: TypeId,
4483}
4484
4485pub struct ElementStateHandle<T> {
4486    value_type: PhantomData<T>,
4487    id: ElementStateId,
4488    ref_counts: Weak<Mutex<RefCounts>>,
4489}
4490
4491impl<T: 'static> ElementStateHandle<T> {
4492    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4493        ref_counts.lock().inc_element_state(id, frame_id);
4494        Self {
4495            value_type: PhantomData,
4496            id,
4497            ref_counts: Arc::downgrade(ref_counts),
4498        }
4499    }
4500
4501    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
4502        cx.element_states
4503            .get(&self.id)
4504            .unwrap()
4505            .downcast_ref()
4506            .unwrap()
4507    }
4508
4509    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
4510    where
4511        C: DerefMut<Target = MutableAppContext>,
4512    {
4513        let mut element_state = cx.deref_mut().cx.element_states.remove(&self.id).unwrap();
4514        let result = f(element_state.downcast_mut().unwrap(), cx);
4515        cx.deref_mut()
4516            .cx
4517            .element_states
4518            .insert(self.id, element_state);
4519        result
4520    }
4521}
4522
4523impl<T> Drop for ElementStateHandle<T> {
4524    fn drop(&mut self) {
4525        if let Some(ref_counts) = self.ref_counts.upgrade() {
4526            ref_counts.lock().dec_element_state(self.id);
4527        }
4528    }
4529}
4530
4531#[must_use]
4532pub enum Subscription {
4533    Subscription {
4534        id: usize,
4535        entity_id: usize,
4536        subscriptions:
4537            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, Option<SubscriptionCallback>>>>>>,
4538    },
4539    GlobalSubscription {
4540        id: usize,
4541        type_id: TypeId,
4542        subscriptions: Option<
4543            Weak<Mutex<HashMap<TypeId, BTreeMap<usize, Option<GlobalSubscriptionCallback>>>>>,
4544        >,
4545    },
4546    Observation {
4547        id: usize,
4548        entity_id: usize,
4549        observations:
4550            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, Option<ObservationCallback>>>>>>,
4551    },
4552    GlobalObservation {
4553        id: usize,
4554        type_id: TypeId,
4555        observations: Option<
4556            Weak<Mutex<HashMap<TypeId, BTreeMap<usize, Option<GlobalObservationCallback>>>>>,
4557        >,
4558    },
4559    FocusObservation {
4560        id: usize,
4561        view_id: usize,
4562        observations:
4563            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, Option<FocusObservationCallback>>>>>>,
4564    },
4565    ReleaseObservation {
4566        id: usize,
4567        entity_id: usize,
4568        observations:
4569            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>>,
4570    },
4571}
4572
4573impl Subscription {
4574    pub fn detach(&mut self) {
4575        match self {
4576            Subscription::Subscription { subscriptions, .. } => {
4577                subscriptions.take();
4578            }
4579            Subscription::GlobalSubscription { subscriptions, .. } => {
4580                subscriptions.take();
4581            }
4582            Subscription::Observation { observations, .. } => {
4583                observations.take();
4584            }
4585            Subscription::GlobalObservation { observations, .. } => {
4586                observations.take();
4587            }
4588            Subscription::ReleaseObservation { observations, .. } => {
4589                observations.take();
4590            }
4591            Subscription::FocusObservation { observations, .. } => {
4592                observations.take();
4593            }
4594        }
4595    }
4596}
4597
4598impl Drop for Subscription {
4599    fn drop(&mut self) {
4600        match self {
4601            Subscription::Subscription {
4602                id,
4603                entity_id,
4604                subscriptions,
4605            } => {
4606                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
4607                    match subscriptions
4608                        .lock()
4609                        .entry(*entity_id)
4610                        .or_default()
4611                        .entry(*id)
4612                    {
4613                        btree_map::Entry::Vacant(entry) => {
4614                            entry.insert(None);
4615                        }
4616                        btree_map::Entry::Occupied(entry) => {
4617                            entry.remove();
4618                        }
4619                    }
4620                }
4621            }
4622            Subscription::GlobalSubscription {
4623                id,
4624                type_id,
4625                subscriptions,
4626            } => {
4627                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
4628                    match subscriptions.lock().entry(*type_id).or_default().entry(*id) {
4629                        btree_map::Entry::Vacant(entry) => {
4630                            entry.insert(None);
4631                        }
4632                        btree_map::Entry::Occupied(entry) => {
4633                            entry.remove();
4634                        }
4635                    }
4636                }
4637            }
4638            Subscription::Observation {
4639                id,
4640                entity_id,
4641                observations,
4642            } => {
4643                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4644                    match observations
4645                        .lock()
4646                        .entry(*entity_id)
4647                        .or_default()
4648                        .entry(*id)
4649                    {
4650                        btree_map::Entry::Vacant(entry) => {
4651                            entry.insert(None);
4652                        }
4653                        btree_map::Entry::Occupied(entry) => {
4654                            entry.remove();
4655                        }
4656                    }
4657                }
4658            }
4659            Subscription::GlobalObservation {
4660                id,
4661                type_id,
4662                observations,
4663            } => {
4664                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4665                    match observations.lock().entry(*type_id).or_default().entry(*id) {
4666                        collections::btree_map::Entry::Vacant(entry) => {
4667                            entry.insert(None);
4668                        }
4669                        collections::btree_map::Entry::Occupied(entry) => {
4670                            entry.remove();
4671                        }
4672                    }
4673                }
4674            }
4675            Subscription::ReleaseObservation {
4676                id,
4677                entity_id,
4678                observations,
4679            } => {
4680                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4681                    if let Some(observations) = observations.lock().get_mut(entity_id) {
4682                        observations.remove(id);
4683                    }
4684                }
4685            }
4686            Subscription::FocusObservation {
4687                id,
4688                view_id,
4689                observations,
4690            } => {
4691                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4692                    match observations.lock().entry(*view_id).or_default().entry(*id) {
4693                        btree_map::Entry::Vacant(entry) => {
4694                            entry.insert(None);
4695                        }
4696                        btree_map::Entry::Occupied(entry) => {
4697                            entry.remove();
4698                        }
4699                    }
4700                }
4701            }
4702        }
4703    }
4704}
4705
4706lazy_static! {
4707    static ref LEAK_BACKTRACE: bool =
4708        std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty());
4709}
4710
4711#[cfg(any(test, feature = "test-support"))]
4712#[derive(Default)]
4713pub struct LeakDetector {
4714    next_handle_id: usize,
4715    handle_backtraces: HashMap<
4716        usize,
4717        (
4718            Option<&'static str>,
4719            HashMap<usize, Option<backtrace::Backtrace>>,
4720        ),
4721    >,
4722}
4723
4724#[cfg(any(test, feature = "test-support"))]
4725impl LeakDetector {
4726    fn handle_created(&mut self, type_name: Option<&'static str>, entity_id: usize) -> usize {
4727        let handle_id = post_inc(&mut self.next_handle_id);
4728        let entry = self.handle_backtraces.entry(entity_id).or_default();
4729        let backtrace = if *LEAK_BACKTRACE {
4730            Some(backtrace::Backtrace::new_unresolved())
4731        } else {
4732            None
4733        };
4734        if let Some(type_name) = type_name {
4735            entry.0.get_or_insert(type_name);
4736        }
4737        entry.1.insert(handle_id, backtrace);
4738        handle_id
4739    }
4740
4741    fn handle_dropped(&mut self, entity_id: usize, handle_id: usize) {
4742        if let Some((_, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
4743            assert!(backtraces.remove(&handle_id).is_some());
4744            if backtraces.is_empty() {
4745                self.handle_backtraces.remove(&entity_id);
4746            }
4747        }
4748    }
4749
4750    pub fn assert_dropped(&mut self, entity_id: usize) {
4751        if let Some((type_name, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
4752            for trace in backtraces.values_mut() {
4753                if let Some(trace) = trace {
4754                    trace.resolve();
4755                    eprintln!("{:?}", crate::util::CwdBacktrace(trace));
4756                }
4757            }
4758
4759            let hint = if *LEAK_BACKTRACE {
4760                ""
4761            } else {
4762                " – set LEAK_BACKTRACE=1 for more information"
4763            };
4764
4765            panic!(
4766                "{} handles to {} {} still exist{}",
4767                backtraces.len(),
4768                type_name.unwrap_or("entity"),
4769                entity_id,
4770                hint
4771            );
4772        }
4773    }
4774
4775    pub fn detect(&mut self) {
4776        let mut found_leaks = false;
4777        for (id, (type_name, backtraces)) in self.handle_backtraces.iter_mut() {
4778            eprintln!(
4779                "leaked {} handles to {} {}",
4780                backtraces.len(),
4781                type_name.unwrap_or("entity"),
4782                id
4783            );
4784            for trace in backtraces.values_mut() {
4785                if let Some(trace) = trace {
4786                    trace.resolve();
4787                    eprintln!("{:?}", crate::util::CwdBacktrace(trace));
4788                }
4789            }
4790            found_leaks = true;
4791        }
4792
4793        let hint = if *LEAK_BACKTRACE {
4794            ""
4795        } else {
4796            " – set LEAK_BACKTRACE=1 for more information"
4797        };
4798        assert!(!found_leaks, "detected leaked handles{}", hint);
4799    }
4800}
4801
4802#[derive(Default)]
4803struct RefCounts {
4804    entity_counts: HashMap<usize, usize>,
4805    element_state_counts: HashMap<ElementStateId, ElementStateRefCount>,
4806    dropped_models: HashSet<usize>,
4807    dropped_views: HashSet<(usize, usize)>,
4808    dropped_element_states: HashSet<ElementStateId>,
4809
4810    #[cfg(any(test, feature = "test-support"))]
4811    leak_detector: Arc<Mutex<LeakDetector>>,
4812}
4813
4814struct ElementStateRefCount {
4815    ref_count: usize,
4816    frame_id: usize,
4817}
4818
4819impl RefCounts {
4820    fn inc_model(&mut self, model_id: usize) {
4821        match self.entity_counts.entry(model_id) {
4822            Entry::Occupied(mut entry) => {
4823                *entry.get_mut() += 1;
4824            }
4825            Entry::Vacant(entry) => {
4826                entry.insert(1);
4827                self.dropped_models.remove(&model_id);
4828            }
4829        }
4830    }
4831
4832    fn inc_view(&mut self, window_id: usize, view_id: usize) {
4833        match self.entity_counts.entry(view_id) {
4834            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
4835            Entry::Vacant(entry) => {
4836                entry.insert(1);
4837                self.dropped_views.remove(&(window_id, view_id));
4838            }
4839        }
4840    }
4841
4842    fn inc_element_state(&mut self, id: ElementStateId, frame_id: usize) {
4843        match self.element_state_counts.entry(id) {
4844            Entry::Occupied(mut entry) => {
4845                let entry = entry.get_mut();
4846                if entry.frame_id == frame_id || entry.ref_count >= 2 {
4847                    panic!("used the same element state more than once in the same frame");
4848                }
4849                entry.ref_count += 1;
4850                entry.frame_id = frame_id;
4851            }
4852            Entry::Vacant(entry) => {
4853                entry.insert(ElementStateRefCount {
4854                    ref_count: 1,
4855                    frame_id,
4856                });
4857                self.dropped_element_states.remove(&id);
4858            }
4859        }
4860    }
4861
4862    fn dec_model(&mut self, model_id: usize) {
4863        let count = self.entity_counts.get_mut(&model_id).unwrap();
4864        *count -= 1;
4865        if *count == 0 {
4866            self.entity_counts.remove(&model_id);
4867            self.dropped_models.insert(model_id);
4868        }
4869    }
4870
4871    fn dec_view(&mut self, window_id: usize, view_id: usize) {
4872        let count = self.entity_counts.get_mut(&view_id).unwrap();
4873        *count -= 1;
4874        if *count == 0 {
4875            self.entity_counts.remove(&view_id);
4876            self.dropped_views.insert((window_id, view_id));
4877        }
4878    }
4879
4880    fn dec_element_state(&mut self, id: ElementStateId) {
4881        let entry = self.element_state_counts.get_mut(&id).unwrap();
4882        entry.ref_count -= 1;
4883        if entry.ref_count == 0 {
4884            self.element_state_counts.remove(&id);
4885            self.dropped_element_states.insert(id);
4886        }
4887    }
4888
4889    fn is_entity_alive(&self, entity_id: usize) -> bool {
4890        self.entity_counts.contains_key(&entity_id)
4891    }
4892
4893    fn take_dropped(
4894        &mut self,
4895    ) -> (
4896        HashSet<usize>,
4897        HashSet<(usize, usize)>,
4898        HashSet<ElementStateId>,
4899    ) {
4900        (
4901            std::mem::take(&mut self.dropped_models),
4902            std::mem::take(&mut self.dropped_views),
4903            std::mem::take(&mut self.dropped_element_states),
4904        )
4905    }
4906}
4907
4908#[cfg(test)]
4909mod tests {
4910    use super::*;
4911    use crate::{actions, elements::*, impl_actions};
4912    use serde::Deserialize;
4913    use smol::future::poll_once;
4914    use std::{
4915        cell::Cell,
4916        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
4917    };
4918
4919    #[crate::test(self)]
4920    fn test_model_handles(cx: &mut MutableAppContext) {
4921        struct Model {
4922            other: Option<ModelHandle<Model>>,
4923            events: Vec<String>,
4924        }
4925
4926        impl Entity for Model {
4927            type Event = usize;
4928        }
4929
4930        impl Model {
4931            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
4932                if let Some(other) = other.as_ref() {
4933                    cx.observe(other, |me, _, _| {
4934                        me.events.push("notified".into());
4935                    })
4936                    .detach();
4937                    cx.subscribe(other, |me, _, event, _| {
4938                        me.events.push(format!("observed event {}", event));
4939                    })
4940                    .detach();
4941                }
4942
4943                Self {
4944                    other,
4945                    events: Vec::new(),
4946                }
4947            }
4948        }
4949
4950        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
4951        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
4952        assert_eq!(cx.cx.models.len(), 2);
4953
4954        handle_1.update(cx, |model, cx| {
4955            model.events.push("updated".into());
4956            cx.emit(1);
4957            cx.notify();
4958            cx.emit(2);
4959        });
4960        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4961        assert_eq!(
4962            handle_2.read(cx).events,
4963            vec![
4964                "observed event 1".to_string(),
4965                "notified".to_string(),
4966                "observed event 2".to_string(),
4967            ]
4968        );
4969
4970        handle_2.update(cx, |model, _| {
4971            drop(handle_1);
4972            model.other.take();
4973        });
4974
4975        assert_eq!(cx.cx.models.len(), 1);
4976        assert!(cx.subscriptions.lock().is_empty());
4977        assert!(cx.observations.lock().is_empty());
4978    }
4979
4980    #[crate::test(self)]
4981    fn test_model_events(cx: &mut MutableAppContext) {
4982        #[derive(Default)]
4983        struct Model {
4984            events: Vec<usize>,
4985        }
4986
4987        impl Entity for Model {
4988            type Event = usize;
4989        }
4990
4991        let handle_1 = cx.add_model(|_| Model::default());
4992        let handle_2 = cx.add_model(|_| Model::default());
4993
4994        handle_1.update(cx, |_, cx| {
4995            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
4996                model.events.push(*event);
4997
4998                cx.subscribe(&emitter, |model, _, event, _| {
4999                    model.events.push(*event * 2);
5000                })
5001                .detach();
5002            })
5003            .detach();
5004        });
5005
5006        handle_2.update(cx, |_, c| c.emit(7));
5007        assert_eq!(handle_1.read(cx).events, vec![7]);
5008
5009        handle_2.update(cx, |_, c| c.emit(5));
5010        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
5011    }
5012
5013    #[crate::test(self)]
5014    fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
5015        #[derive(Default)]
5016        struct Model;
5017
5018        impl Entity for Model {
5019            type Event = ();
5020        }
5021
5022        let events = Rc::new(RefCell::new(Vec::new()));
5023        cx.add_model(|cx| {
5024            drop(cx.subscribe(&cx.handle(), {
5025                let events = events.clone();
5026                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
5027            }));
5028            cx.subscribe(&cx.handle(), {
5029                let events = events.clone();
5030                move |_, _, _, _| events.borrow_mut().push("before emit")
5031            })
5032            .detach();
5033            cx.emit(());
5034            cx.subscribe(&cx.handle(), {
5035                let events = events.clone();
5036                move |_, _, _, _| events.borrow_mut().push("after emit")
5037            })
5038            .detach();
5039            Model
5040        });
5041        assert_eq!(*events.borrow(), ["before emit"]);
5042    }
5043
5044    #[crate::test(self)]
5045    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
5046        #[derive(Default)]
5047        struct Model {
5048            count: usize,
5049            events: Vec<usize>,
5050        }
5051
5052        impl Entity for Model {
5053            type Event = ();
5054        }
5055
5056        let handle_1 = cx.add_model(|_| Model::default());
5057        let handle_2 = cx.add_model(|_| Model::default());
5058
5059        handle_1.update(cx, |_, c| {
5060            c.observe(&handle_2, move |model, observed, c| {
5061                model.events.push(observed.read(c).count);
5062                c.observe(&observed, |model, observed, c| {
5063                    model.events.push(observed.read(c).count * 2);
5064                })
5065                .detach();
5066            })
5067            .detach();
5068        });
5069
5070        handle_2.update(cx, |model, c| {
5071            model.count = 7;
5072            c.notify()
5073        });
5074        assert_eq!(handle_1.read(cx).events, vec![7]);
5075
5076        handle_2.update(cx, |model, c| {
5077            model.count = 5;
5078            c.notify()
5079        });
5080        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
5081    }
5082
5083    #[crate::test(self)]
5084    fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
5085        #[derive(Default)]
5086        struct Model;
5087
5088        impl Entity for Model {
5089            type Event = ();
5090        }
5091
5092        let events = Rc::new(RefCell::new(Vec::new()));
5093        cx.add_model(|cx| {
5094            drop(cx.observe(&cx.handle(), {
5095                let events = events.clone();
5096                move |_, _, _| events.borrow_mut().push("dropped before flush")
5097            }));
5098            cx.observe(&cx.handle(), {
5099                let events = events.clone();
5100                move |_, _, _| events.borrow_mut().push("before notify")
5101            })
5102            .detach();
5103            cx.notify();
5104            cx.observe(&cx.handle(), {
5105                let events = events.clone();
5106                move |_, _, _| events.borrow_mut().push("after notify")
5107            })
5108            .detach();
5109            Model
5110        });
5111        assert_eq!(*events.borrow(), ["before notify"]);
5112    }
5113
5114    #[crate::test(self)]
5115    fn test_defer_and_after_window_update(cx: &mut MutableAppContext) {
5116        struct View {
5117            render_count: usize,
5118        }
5119
5120        impl Entity for View {
5121            type Event = usize;
5122        }
5123
5124        impl super::View for View {
5125            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5126                post_inc(&mut self.render_count);
5127                Empty::new().boxed()
5128            }
5129
5130            fn ui_name() -> &'static str {
5131                "View"
5132            }
5133        }
5134
5135        let (_, view) = cx.add_window(Default::default(), |_| View { render_count: 0 });
5136        let called_defer = Rc::new(AtomicBool::new(false));
5137        let called_after_window_update = Rc::new(AtomicBool::new(false));
5138
5139        view.update(cx, |this, cx| {
5140            assert_eq!(this.render_count, 1);
5141            cx.defer({
5142                let called_defer = called_defer.clone();
5143                move |this, _| {
5144                    assert_eq!(this.render_count, 1);
5145                    called_defer.store(true, SeqCst);
5146                }
5147            });
5148            cx.after_window_update({
5149                let called_after_window_update = called_after_window_update.clone();
5150                move |this, cx| {
5151                    assert_eq!(this.render_count, 2);
5152                    called_after_window_update.store(true, SeqCst);
5153                    cx.notify();
5154                }
5155            });
5156            assert!(!called_defer.load(SeqCst));
5157            assert!(!called_after_window_update.load(SeqCst));
5158            cx.notify();
5159        });
5160
5161        assert!(called_defer.load(SeqCst));
5162        assert!(called_after_window_update.load(SeqCst));
5163        assert_eq!(view.read(cx).render_count, 3);
5164    }
5165
5166    #[crate::test(self)]
5167    fn test_view_handles(cx: &mut MutableAppContext) {
5168        struct View {
5169            other: Option<ViewHandle<View>>,
5170            events: Vec<String>,
5171        }
5172
5173        impl Entity for View {
5174            type Event = usize;
5175        }
5176
5177        impl super::View for View {
5178            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5179                Empty::new().boxed()
5180            }
5181
5182            fn ui_name() -> &'static str {
5183                "View"
5184            }
5185        }
5186
5187        impl View {
5188            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
5189                if let Some(other) = other.as_ref() {
5190                    cx.subscribe(other, |me, _, event, _| {
5191                        me.events.push(format!("observed event {}", event));
5192                    })
5193                    .detach();
5194                }
5195                Self {
5196                    other,
5197                    events: Vec::new(),
5198                }
5199            }
5200        }
5201
5202        let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
5203        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
5204        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
5205        assert_eq!(cx.cx.views.len(), 3);
5206
5207        handle_1.update(cx, |view, cx| {
5208            view.events.push("updated".into());
5209            cx.emit(1);
5210            cx.emit(2);
5211        });
5212        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5213        assert_eq!(
5214            handle_2.read(cx).events,
5215            vec![
5216                "observed event 1".to_string(),
5217                "observed event 2".to_string(),
5218            ]
5219        );
5220
5221        handle_2.update(cx, |view, _| {
5222            drop(handle_1);
5223            view.other.take();
5224        });
5225
5226        assert_eq!(cx.cx.views.len(), 2);
5227        assert!(cx.subscriptions.lock().is_empty());
5228        assert!(cx.observations.lock().is_empty());
5229    }
5230
5231    #[crate::test(self)]
5232    fn test_add_window(cx: &mut MutableAppContext) {
5233        struct View {
5234            mouse_down_count: Arc<AtomicUsize>,
5235        }
5236
5237        impl Entity for View {
5238            type Event = ();
5239        }
5240
5241        impl super::View for View {
5242            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5243                let mouse_down_count = self.mouse_down_count.clone();
5244                EventHandler::new(Empty::new().boxed())
5245                    .on_mouse_down(move |_| {
5246                        mouse_down_count.fetch_add(1, SeqCst);
5247                        true
5248                    })
5249                    .boxed()
5250            }
5251
5252            fn ui_name() -> &'static str {
5253                "View"
5254            }
5255        }
5256
5257        let mouse_down_count = Arc::new(AtomicUsize::new(0));
5258        let (window_id, _) = cx.add_window(Default::default(), |_| View {
5259            mouse_down_count: mouse_down_count.clone(),
5260        });
5261        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
5262        // Ensure window's root element is in a valid lifecycle state.
5263        presenter.borrow_mut().dispatch_event(
5264            Event::LeftMouseDown {
5265                position: Default::default(),
5266                ctrl: false,
5267                alt: false,
5268                shift: false,
5269                cmd: false,
5270                click_count: 1,
5271            },
5272            cx,
5273        );
5274        assert_eq!(mouse_down_count.load(SeqCst), 1);
5275    }
5276
5277    #[crate::test(self)]
5278    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
5279        struct Model {
5280            released: Rc<Cell<bool>>,
5281        }
5282
5283        struct View {
5284            released: Rc<Cell<bool>>,
5285        }
5286
5287        impl Entity for Model {
5288            type Event = ();
5289
5290            fn release(&mut self, _: &mut MutableAppContext) {
5291                self.released.set(true);
5292            }
5293        }
5294
5295        impl Entity for View {
5296            type Event = ();
5297
5298            fn release(&mut self, _: &mut MutableAppContext) {
5299                self.released.set(true);
5300            }
5301        }
5302
5303        impl super::View for View {
5304            fn ui_name() -> &'static str {
5305                "View"
5306            }
5307
5308            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5309                Empty::new().boxed()
5310            }
5311        }
5312
5313        let model_released = Rc::new(Cell::new(false));
5314        let model_release_observed = Rc::new(Cell::new(false));
5315        let view_released = Rc::new(Cell::new(false));
5316        let view_release_observed = Rc::new(Cell::new(false));
5317
5318        let model = cx.add_model(|_| Model {
5319            released: model_released.clone(),
5320        });
5321        let (window_id, view) = cx.add_window(Default::default(), |_| View {
5322            released: view_released.clone(),
5323        });
5324        assert!(!model_released.get());
5325        assert!(!view_released.get());
5326
5327        cx.observe_release(&model, {
5328            let model_release_observed = model_release_observed.clone();
5329            move |_, _| model_release_observed.set(true)
5330        })
5331        .detach();
5332        cx.observe_release(&view, {
5333            let view_release_observed = view_release_observed.clone();
5334            move |_, _| view_release_observed.set(true)
5335        })
5336        .detach();
5337
5338        cx.update(move |_| {
5339            drop(model);
5340        });
5341        assert!(model_released.get());
5342        assert!(model_release_observed.get());
5343
5344        drop(view);
5345        cx.remove_window(window_id);
5346        assert!(view_released.get());
5347        assert!(view_release_observed.get());
5348    }
5349
5350    #[crate::test(self)]
5351    fn test_view_events(cx: &mut MutableAppContext) {
5352        #[derive(Default)]
5353        struct View {
5354            events: Vec<usize>,
5355        }
5356
5357        impl Entity for View {
5358            type Event = usize;
5359        }
5360
5361        impl super::View for View {
5362            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5363                Empty::new().boxed()
5364            }
5365
5366            fn ui_name() -> &'static str {
5367                "View"
5368            }
5369        }
5370
5371        struct Model;
5372
5373        impl Entity for Model {
5374            type Event = usize;
5375        }
5376
5377        let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
5378        let handle_2 = cx.add_view(window_id, |_| View::default());
5379        let handle_3 = cx.add_model(|_| Model);
5380
5381        handle_1.update(cx, |_, cx| {
5382            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
5383                me.events.push(*event);
5384
5385                cx.subscribe(&emitter, |me, _, event, _| {
5386                    me.events.push(*event * 2);
5387                })
5388                .detach();
5389            })
5390            .detach();
5391
5392            cx.subscribe(&handle_3, |me, _, event, _| {
5393                me.events.push(*event);
5394            })
5395            .detach();
5396        });
5397
5398        handle_2.update(cx, |_, c| c.emit(7));
5399        assert_eq!(handle_1.read(cx).events, vec![7]);
5400
5401        handle_2.update(cx, |_, c| c.emit(5));
5402        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
5403
5404        handle_3.update(cx, |_, c| c.emit(9));
5405        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
5406    }
5407
5408    #[crate::test(self)]
5409    fn test_global_events(cx: &mut MutableAppContext) {
5410        #[derive(Clone, Debug, Eq, PartialEq)]
5411        struct GlobalEvent(u64);
5412
5413        let events = Rc::new(RefCell::new(Vec::new()));
5414        let first_subscription;
5415        let second_subscription;
5416
5417        {
5418            let events = events.clone();
5419            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5420                events.borrow_mut().push(("First", e.clone()));
5421            });
5422        }
5423
5424        {
5425            let events = events.clone();
5426            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5427                events.borrow_mut().push(("Second", e.clone()));
5428            });
5429        }
5430
5431        cx.update(|cx| {
5432            cx.emit_global(GlobalEvent(1));
5433            cx.emit_global(GlobalEvent(2));
5434        });
5435
5436        drop(first_subscription);
5437
5438        cx.update(|cx| {
5439            cx.emit_global(GlobalEvent(3));
5440        });
5441
5442        drop(second_subscription);
5443
5444        cx.update(|cx| {
5445            cx.emit_global(GlobalEvent(4));
5446        });
5447
5448        assert_eq!(
5449            &*events.borrow(),
5450            &[
5451                ("First", GlobalEvent(1)),
5452                ("Second", GlobalEvent(1)),
5453                ("First", GlobalEvent(2)),
5454                ("Second", GlobalEvent(2)),
5455                ("Second", GlobalEvent(3)),
5456            ]
5457        );
5458    }
5459
5460    #[crate::test(self)]
5461    fn test_global_events_emitted_before_subscription_in_same_update_cycle(
5462        cx: &mut MutableAppContext,
5463    ) {
5464        let events = Rc::new(RefCell::new(Vec::new()));
5465        cx.update(|cx| {
5466            {
5467                let events = events.clone();
5468                drop(cx.subscribe_global(move |_: &(), _| {
5469                    events.borrow_mut().push("dropped before emit");
5470                }));
5471            }
5472
5473            {
5474                let events = events.clone();
5475                cx.subscribe_global(move |_: &(), _| {
5476                    events.borrow_mut().push("before emit");
5477                })
5478                .detach();
5479            }
5480
5481            cx.emit_global(());
5482
5483            {
5484                let events = events.clone();
5485                cx.subscribe_global(move |_: &(), _| {
5486                    events.borrow_mut().push("after emit");
5487                })
5488                .detach();
5489            }
5490        });
5491
5492        assert_eq!(*events.borrow(), ["before emit"]);
5493    }
5494
5495    #[crate::test(self)]
5496    fn test_global_nested_events(cx: &mut MutableAppContext) {
5497        #[derive(Clone, Debug, Eq, PartialEq)]
5498        struct GlobalEvent(u64);
5499
5500        let events = Rc::new(RefCell::new(Vec::new()));
5501
5502        {
5503            let events = events.clone();
5504            cx.subscribe_global(move |e: &GlobalEvent, cx| {
5505                events.borrow_mut().push(("Outer", e.clone()));
5506
5507                if e.0 == 1 {
5508                    let events = events.clone();
5509                    cx.subscribe_global(move |e: &GlobalEvent, _| {
5510                        events.borrow_mut().push(("Inner", e.clone()));
5511                    })
5512                    .detach();
5513                }
5514            })
5515            .detach();
5516        }
5517
5518        cx.update(|cx| {
5519            cx.emit_global(GlobalEvent(1));
5520            cx.emit_global(GlobalEvent(2));
5521            cx.emit_global(GlobalEvent(3));
5522        });
5523        cx.update(|cx| {
5524            cx.emit_global(GlobalEvent(4));
5525        });
5526
5527        assert_eq!(
5528            &*events.borrow(),
5529            &[
5530                ("Outer", GlobalEvent(1)),
5531                ("Outer", GlobalEvent(2)),
5532                ("Outer", GlobalEvent(3)),
5533                ("Outer", GlobalEvent(4)),
5534                ("Inner", GlobalEvent(4)),
5535            ]
5536        );
5537    }
5538
5539    #[crate::test(self)]
5540    fn test_global(cx: &mut MutableAppContext) {
5541        type Global = usize;
5542
5543        let observation_count = Rc::new(RefCell::new(0));
5544        let subscription = cx.observe_global::<Global, _>({
5545            let observation_count = observation_count.clone();
5546            move |_, _| {
5547                *observation_count.borrow_mut() += 1;
5548            }
5549        });
5550
5551        assert!(!cx.has_global::<Global>());
5552        assert_eq!(cx.default_global::<Global>(), &0);
5553        assert_eq!(*observation_count.borrow(), 1);
5554        assert!(cx.has_global::<Global>());
5555        assert_eq!(
5556            cx.update_global::<Global, _, _>(|global, _| {
5557                *global = 1;
5558                "Update Result"
5559            }),
5560            "Update Result"
5561        );
5562        assert_eq!(*observation_count.borrow(), 2);
5563        assert_eq!(cx.global::<Global>(), &1);
5564
5565        drop(subscription);
5566        cx.update_global::<Global, _, _>(|global, _| {
5567            *global = 2;
5568        });
5569        assert_eq!(*observation_count.borrow(), 2);
5570
5571        type OtherGlobal = f32;
5572
5573        let observation_count = Rc::new(RefCell::new(0));
5574        cx.observe_global::<OtherGlobal, _>({
5575            let observation_count = observation_count.clone();
5576            move |_, _| {
5577                *observation_count.borrow_mut() += 1;
5578            }
5579        })
5580        .detach();
5581
5582        assert_eq!(
5583            cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
5584                assert_eq!(global, &0.0);
5585                *global = 2.0;
5586                "Default update result"
5587            }),
5588            "Default update result"
5589        );
5590        assert_eq!(cx.global::<OtherGlobal>(), &2.0);
5591        assert_eq!(*observation_count.borrow(), 1);
5592    }
5593
5594    #[crate::test(self)]
5595    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
5596        struct View;
5597
5598        impl Entity for View {
5599            type Event = ();
5600        }
5601
5602        impl super::View for View {
5603            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5604                Empty::new().boxed()
5605            }
5606
5607            fn ui_name() -> &'static str {
5608                "View"
5609            }
5610        }
5611
5612        struct Model;
5613
5614        impl Entity for Model {
5615            type Event = ();
5616        }
5617
5618        let (window_id, _) = cx.add_window(Default::default(), |_| View);
5619        let observing_view = cx.add_view(window_id, |_| View);
5620        let emitting_view = cx.add_view(window_id, |_| View);
5621        let observing_model = cx.add_model(|_| Model);
5622        let observed_model = cx.add_model(|_| Model);
5623
5624        observing_view.update(cx, |_, cx| {
5625            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
5626            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5627        });
5628        observing_model.update(cx, |_, cx| {
5629            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5630        });
5631
5632        cx.update(|_| {
5633            drop(observing_view);
5634            drop(observing_model);
5635        });
5636
5637        emitting_view.update(cx, |_, cx| cx.emit(()));
5638        observed_model.update(cx, |_, cx| cx.emit(()));
5639    }
5640
5641    #[crate::test(self)]
5642    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
5643        #[derive(Default)]
5644        struct TestView;
5645
5646        impl Entity for TestView {
5647            type Event = ();
5648        }
5649
5650        impl View for TestView {
5651            fn ui_name() -> &'static str {
5652                "TestView"
5653            }
5654
5655            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5656                Empty::new().boxed()
5657            }
5658        }
5659
5660        let events = Rc::new(RefCell::new(Vec::new()));
5661        cx.add_window(Default::default(), |cx| {
5662            drop(cx.subscribe(&cx.handle(), {
5663                let events = events.clone();
5664                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
5665            }));
5666            cx.subscribe(&cx.handle(), {
5667                let events = events.clone();
5668                move |_, _, _, _| events.borrow_mut().push("before emit")
5669            })
5670            .detach();
5671            cx.emit(());
5672            cx.subscribe(&cx.handle(), {
5673                let events = events.clone();
5674                move |_, _, _, _| events.borrow_mut().push("after emit")
5675            })
5676            .detach();
5677            TestView
5678        });
5679        assert_eq!(*events.borrow(), ["before emit"]);
5680    }
5681
5682    #[crate::test(self)]
5683    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
5684        #[derive(Default)]
5685        struct View {
5686            events: Vec<usize>,
5687        }
5688
5689        impl Entity for View {
5690            type Event = usize;
5691        }
5692
5693        impl super::View for View {
5694            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5695                Empty::new().boxed()
5696            }
5697
5698            fn ui_name() -> &'static str {
5699                "View"
5700            }
5701        }
5702
5703        #[derive(Default)]
5704        struct Model {
5705            count: usize,
5706        }
5707
5708        impl Entity for Model {
5709            type Event = ();
5710        }
5711
5712        let (_, view) = cx.add_window(Default::default(), |_| View::default());
5713        let model = cx.add_model(|_| Model::default());
5714
5715        view.update(cx, |_, c| {
5716            c.observe(&model, |me, observed, c| {
5717                me.events.push(observed.read(c).count)
5718            })
5719            .detach();
5720        });
5721
5722        model.update(cx, |model, c| {
5723            model.count = 11;
5724            c.notify();
5725        });
5726        assert_eq!(view.read(cx).events, vec![11]);
5727    }
5728
5729    #[crate::test(self)]
5730    fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
5731        #[derive(Default)]
5732        struct TestView;
5733
5734        impl Entity for TestView {
5735            type Event = ();
5736        }
5737
5738        impl View for TestView {
5739            fn ui_name() -> &'static str {
5740                "TestView"
5741            }
5742
5743            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5744                Empty::new().boxed()
5745            }
5746        }
5747
5748        let events = Rc::new(RefCell::new(Vec::new()));
5749        cx.add_window(Default::default(), |cx| {
5750            drop(cx.observe(&cx.handle(), {
5751                let events = events.clone();
5752                move |_, _, _| events.borrow_mut().push("dropped before flush")
5753            }));
5754            cx.observe(&cx.handle(), {
5755                let events = events.clone();
5756                move |_, _, _| events.borrow_mut().push("before notify")
5757            })
5758            .detach();
5759            cx.notify();
5760            cx.observe(&cx.handle(), {
5761                let events = events.clone();
5762                move |_, _, _| events.borrow_mut().push("after notify")
5763            })
5764            .detach();
5765            TestView
5766        });
5767        assert_eq!(*events.borrow(), ["before notify"]);
5768    }
5769
5770    #[crate::test(self)]
5771    fn test_dropping_observers(cx: &mut MutableAppContext) {
5772        struct View;
5773
5774        impl Entity for View {
5775            type Event = ();
5776        }
5777
5778        impl super::View for View {
5779            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5780                Empty::new().boxed()
5781            }
5782
5783            fn ui_name() -> &'static str {
5784                "View"
5785            }
5786        }
5787
5788        struct Model;
5789
5790        impl Entity for Model {
5791            type Event = ();
5792        }
5793
5794        let (window_id, _) = cx.add_window(Default::default(), |_| View);
5795        let observing_view = cx.add_view(window_id, |_| View);
5796        let observing_model = cx.add_model(|_| Model);
5797        let observed_model = cx.add_model(|_| Model);
5798
5799        observing_view.update(cx, |_, cx| {
5800            cx.observe(&observed_model, |_, _, _| {}).detach();
5801        });
5802        observing_model.update(cx, |_, cx| {
5803            cx.observe(&observed_model, |_, _, _| {}).detach();
5804        });
5805
5806        cx.update(|_| {
5807            drop(observing_view);
5808            drop(observing_model);
5809        });
5810
5811        observed_model.update(cx, |_, cx| cx.notify());
5812    }
5813
5814    #[crate::test(self)]
5815    fn test_dropping_subscriptions_during_callback(cx: &mut MutableAppContext) {
5816        struct Model;
5817
5818        impl Entity for Model {
5819            type Event = u64;
5820        }
5821
5822        // Events
5823        let observing_model = cx.add_model(|_| Model);
5824        let observed_model = cx.add_model(|_| Model);
5825
5826        let events = Rc::new(RefCell::new(Vec::new()));
5827
5828        observing_model.update(cx, |_, cx| {
5829            let events = events.clone();
5830            let subscription = Rc::new(RefCell::new(None));
5831            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
5832                let subscription = subscription.clone();
5833                move |_, _, e, _| {
5834                    subscription.borrow_mut().take();
5835                    events.borrow_mut().push(e.clone());
5836                }
5837            }));
5838        });
5839
5840        observed_model.update(cx, |_, cx| {
5841            cx.emit(1);
5842            cx.emit(2);
5843        });
5844
5845        assert_eq!(*events.borrow(), [1]);
5846
5847        // Global Events
5848        #[derive(Clone, Debug, Eq, PartialEq)]
5849        struct GlobalEvent(u64);
5850
5851        let events = Rc::new(RefCell::new(Vec::new()));
5852
5853        {
5854            let events = events.clone();
5855            let subscription = Rc::new(RefCell::new(None));
5856            *subscription.borrow_mut() = Some(cx.subscribe_global({
5857                let subscription = subscription.clone();
5858                move |e: &GlobalEvent, _| {
5859                    subscription.borrow_mut().take();
5860                    events.borrow_mut().push(e.clone());
5861                }
5862            }));
5863        }
5864
5865        cx.update(|cx| {
5866            cx.emit_global(GlobalEvent(1));
5867            cx.emit_global(GlobalEvent(2));
5868        });
5869
5870        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
5871
5872        // Model Observation
5873        let observing_model = cx.add_model(|_| Model);
5874        let observed_model = cx.add_model(|_| Model);
5875
5876        let observation_count = Rc::new(RefCell::new(0));
5877
5878        observing_model.update(cx, |_, cx| {
5879            let observation_count = observation_count.clone();
5880            let subscription = Rc::new(RefCell::new(None));
5881            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
5882                let subscription = subscription.clone();
5883                move |_, _, _| {
5884                    subscription.borrow_mut().take();
5885                    *observation_count.borrow_mut() += 1;
5886                }
5887            }));
5888        });
5889
5890        observed_model.update(cx, |_, cx| {
5891            cx.notify();
5892        });
5893
5894        observed_model.update(cx, |_, cx| {
5895            cx.notify();
5896        });
5897
5898        assert_eq!(*observation_count.borrow(), 1);
5899
5900        // View Observation
5901        struct View;
5902
5903        impl Entity for View {
5904            type Event = ();
5905        }
5906
5907        impl super::View for View {
5908            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5909                Empty::new().boxed()
5910            }
5911
5912            fn ui_name() -> &'static str {
5913                "View"
5914            }
5915        }
5916
5917        let (window_id, _) = cx.add_window(Default::default(), |_| View);
5918        let observing_view = cx.add_view(window_id, |_| View);
5919        let observed_view = cx.add_view(window_id, |_| View);
5920
5921        let observation_count = Rc::new(RefCell::new(0));
5922        observing_view.update(cx, |_, cx| {
5923            let observation_count = observation_count.clone();
5924            let subscription = Rc::new(RefCell::new(None));
5925            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
5926                let subscription = subscription.clone();
5927                move |_, _, _| {
5928                    subscription.borrow_mut().take();
5929                    *observation_count.borrow_mut() += 1;
5930                }
5931            }));
5932        });
5933
5934        observed_view.update(cx, |_, cx| {
5935            cx.notify();
5936        });
5937
5938        observed_view.update(cx, |_, cx| {
5939            cx.notify();
5940        });
5941
5942        assert_eq!(*observation_count.borrow(), 1);
5943
5944        // Global Observation
5945        let observation_count = Rc::new(RefCell::new(0));
5946        let subscription = Rc::new(RefCell::new(None));
5947        *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
5948            let observation_count = observation_count.clone();
5949            let subscription = subscription.clone();
5950            move |_, _| {
5951                subscription.borrow_mut().take();
5952                *observation_count.borrow_mut() += 1;
5953            }
5954        }));
5955
5956        cx.default_global::<()>();
5957        cx.set_global(());
5958        assert_eq!(*observation_count.borrow(), 1);
5959    }
5960
5961    #[crate::test(self)]
5962    fn test_focus(cx: &mut MutableAppContext) {
5963        struct View {
5964            name: String,
5965            events: Arc<Mutex<Vec<String>>>,
5966        }
5967
5968        impl Entity for View {
5969            type Event = ();
5970        }
5971
5972        impl super::View for View {
5973            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5974                Empty::new().boxed()
5975            }
5976
5977            fn ui_name() -> &'static str {
5978                "View"
5979            }
5980
5981            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
5982                self.events.lock().push(format!("{} focused", &self.name));
5983            }
5984
5985            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
5986                self.events.lock().push(format!("{} blurred", &self.name));
5987            }
5988        }
5989
5990        let view_events: Arc<Mutex<Vec<String>>> = Default::default();
5991        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
5992            events: view_events.clone(),
5993            name: "view 1".to_string(),
5994        });
5995        let view_2 = cx.add_view(window_id, |_| View {
5996            events: view_events.clone(),
5997            name: "view 2".to_string(),
5998        });
5999
6000        let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
6001        view_1.update(cx, |_, cx| {
6002            cx.observe_focus(&view_2, {
6003                let observed_events = observed_events.clone();
6004                move |this, view, cx| {
6005                    observed_events.lock().push(format!(
6006                        "{} observed {}'s focus",
6007                        this.name,
6008                        view.read(cx).name
6009                    ))
6010                }
6011            })
6012            .detach();
6013        });
6014        view_2.update(cx, |_, cx| {
6015            cx.observe_focus(&view_1, {
6016                let observed_events = observed_events.clone();
6017                move |this, view, cx| {
6018                    observed_events.lock().push(format!(
6019                        "{} observed {}'s focus",
6020                        this.name,
6021                        view.read(cx).name
6022                    ))
6023                }
6024            })
6025            .detach();
6026        });
6027
6028        view_1.update(cx, |_, cx| {
6029            // Ensure only the latest focus is honored.
6030            cx.focus(&view_2);
6031            cx.focus(&view_1);
6032            cx.focus(&view_2);
6033        });
6034        view_1.update(cx, |_, cx| cx.focus(&view_1));
6035        view_1.update(cx, |_, cx| cx.focus(&view_2));
6036        view_1.update(cx, |_, _| drop(view_2));
6037
6038        assert_eq!(
6039            *view_events.lock(),
6040            [
6041                "view 1 focused".to_string(),
6042                "view 1 blurred".to_string(),
6043                "view 2 focused".to_string(),
6044                "view 2 blurred".to_string(),
6045                "view 1 focused".to_string(),
6046                "view 1 blurred".to_string(),
6047                "view 2 focused".to_string(),
6048                "view 1 focused".to_string(),
6049            ],
6050        );
6051        assert_eq!(
6052            *observed_events.lock(),
6053            [
6054                "view 1 observed view 2's focus".to_string(),
6055                "view 2 observed view 1's focus".to_string(),
6056                "view 1 observed view 2's focus".to_string(),
6057            ]
6058        );
6059    }
6060
6061    #[crate::test(self)]
6062    fn test_deserialize_actions(cx: &mut MutableAppContext) {
6063        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6064        pub struct ComplexAction {
6065            arg: String,
6066            count: usize,
6067        }
6068
6069        actions!(test::something, [SimpleAction]);
6070        impl_actions!(test::something, [ComplexAction]);
6071
6072        cx.add_global_action(move |_: &SimpleAction, _: &mut MutableAppContext| {});
6073        cx.add_global_action(move |_: &ComplexAction, _: &mut MutableAppContext| {});
6074
6075        let action1 = cx
6076            .deserialize_action(
6077                "test::something::ComplexAction",
6078                Some(r#"{"arg": "a", "count": 5}"#),
6079            )
6080            .unwrap();
6081        let action2 = cx
6082            .deserialize_action("test::something::SimpleAction", None)
6083            .unwrap();
6084        assert_eq!(
6085            action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
6086            &ComplexAction {
6087                arg: "a".to_string(),
6088                count: 5,
6089            }
6090        );
6091        assert_eq!(
6092            action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
6093            &SimpleAction
6094        );
6095    }
6096
6097    #[crate::test(self)]
6098    fn test_dispatch_action(cx: &mut MutableAppContext) {
6099        struct ViewA {
6100            id: usize,
6101        }
6102
6103        impl Entity for ViewA {
6104            type Event = ();
6105        }
6106
6107        impl View for ViewA {
6108            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6109                Empty::new().boxed()
6110            }
6111
6112            fn ui_name() -> &'static str {
6113                "View"
6114            }
6115        }
6116
6117        struct ViewB {
6118            id: usize,
6119        }
6120
6121        impl Entity for ViewB {
6122            type Event = ();
6123        }
6124
6125        impl View for ViewB {
6126            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6127                Empty::new().boxed()
6128            }
6129
6130            fn ui_name() -> &'static str {
6131                "View"
6132            }
6133        }
6134
6135        #[derive(Clone, Deserialize)]
6136        pub struct Action(pub String);
6137
6138        impl_actions!(test, [Action]);
6139
6140        let actions = Rc::new(RefCell::new(Vec::new()));
6141
6142        cx.add_global_action({
6143            let actions = actions.clone();
6144            move |_: &Action, _: &mut MutableAppContext| {
6145                actions.borrow_mut().push("global".to_string());
6146            }
6147        });
6148
6149        cx.add_action({
6150            let actions = actions.clone();
6151            move |view: &mut ViewA, action: &Action, cx| {
6152                assert_eq!(action.0, "bar");
6153                cx.propagate_action();
6154                actions.borrow_mut().push(format!("{} a", view.id));
6155            }
6156        });
6157
6158        cx.add_action({
6159            let actions = actions.clone();
6160            move |view: &mut ViewA, _: &Action, cx| {
6161                if view.id != 1 {
6162                    cx.add_view(|cx| {
6163                        cx.propagate_action(); // Still works on a nested ViewContext
6164                        ViewB { id: 5 }
6165                    });
6166                }
6167                actions.borrow_mut().push(format!("{} b", view.id));
6168            }
6169        });
6170
6171        cx.add_action({
6172            let actions = actions.clone();
6173            move |view: &mut ViewB, _: &Action, cx| {
6174                cx.propagate_action();
6175                actions.borrow_mut().push(format!("{} c", view.id));
6176            }
6177        });
6178
6179        cx.add_action({
6180            let actions = actions.clone();
6181            move |view: &mut ViewB, _: &Action, cx| {
6182                cx.propagate_action();
6183                actions.borrow_mut().push(format!("{} d", view.id));
6184            }
6185        });
6186
6187        cx.capture_action({
6188            let actions = actions.clone();
6189            move |view: &mut ViewA, _: &Action, cx| {
6190                cx.propagate_action();
6191                actions.borrow_mut().push(format!("{} capture", view.id));
6192            }
6193        });
6194
6195        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
6196        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
6197        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
6198        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
6199
6200        cx.dispatch_action(
6201            window_id,
6202            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
6203            &Action("bar".to_string()),
6204        );
6205
6206        assert_eq!(
6207            *actions.borrow(),
6208            vec![
6209                "1 capture",
6210                "3 capture",
6211                "4 d",
6212                "4 c",
6213                "3 b",
6214                "3 a",
6215                "2 d",
6216                "2 c",
6217                "1 b"
6218            ]
6219        );
6220
6221        // Remove view_1, which doesn't propagate the action
6222        actions.borrow_mut().clear();
6223        cx.dispatch_action(
6224            window_id,
6225            vec![view_2.id(), view_3.id(), view_4.id()],
6226            &Action("bar".to_string()),
6227        );
6228
6229        assert_eq!(
6230            *actions.borrow(),
6231            vec![
6232                "3 capture",
6233                "4 d",
6234                "4 c",
6235                "3 b",
6236                "3 a",
6237                "2 d",
6238                "2 c",
6239                "global"
6240            ]
6241        );
6242    }
6243
6244    #[crate::test(self)]
6245    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
6246        #[derive(Clone, Deserialize)]
6247        pub struct Action(String);
6248
6249        impl_actions!(test, [Action]);
6250
6251        struct View {
6252            id: usize,
6253            keymap_context: keymap::Context,
6254        }
6255
6256        impl Entity for View {
6257            type Event = ();
6258        }
6259
6260        impl super::View for View {
6261            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6262                Empty::new().boxed()
6263            }
6264
6265            fn ui_name() -> &'static str {
6266                "View"
6267            }
6268
6269            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
6270                self.keymap_context.clone()
6271            }
6272        }
6273
6274        impl View {
6275            fn new(id: usize) -> Self {
6276                View {
6277                    id,
6278                    keymap_context: keymap::Context::default(),
6279                }
6280            }
6281        }
6282
6283        let mut view_1 = View::new(1);
6284        let mut view_2 = View::new(2);
6285        let mut view_3 = View::new(3);
6286        view_1.keymap_context.set.insert("a".into());
6287        view_2.keymap_context.set.insert("a".into());
6288        view_2.keymap_context.set.insert("b".into());
6289        view_3.keymap_context.set.insert("a".into());
6290        view_3.keymap_context.set.insert("b".into());
6291        view_3.keymap_context.set.insert("c".into());
6292
6293        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
6294        let view_2 = cx.add_view(window_id, |_| view_2);
6295        let view_3 = cx.add_view(window_id, |_| view_3);
6296
6297        // This keymap's only binding dispatches an action on view 2 because that view will have
6298        // "a" and "b" in its context, but not "c".
6299        cx.add_bindings(vec![keymap::Binding::new(
6300            "a",
6301            Action("a".to_string()),
6302            Some("a && b && !c"),
6303        )]);
6304
6305        cx.add_bindings(vec![keymap::Binding::new(
6306            "b",
6307            Action("b".to_string()),
6308            None,
6309        )]);
6310
6311        let actions = Rc::new(RefCell::new(Vec::new()));
6312        cx.add_action({
6313            let actions = actions.clone();
6314            move |view: &mut View, action: &Action, cx| {
6315                if action.0 == "a" {
6316                    actions.borrow_mut().push(format!("{} a", view.id));
6317                } else {
6318                    actions
6319                        .borrow_mut()
6320                        .push(format!("{} {}", view.id, action.0));
6321                    cx.propagate_action();
6322                }
6323            }
6324        });
6325
6326        cx.add_global_action({
6327            let actions = actions.clone();
6328            move |action: &Action, _| {
6329                actions.borrow_mut().push(format!("global {}", action.0));
6330            }
6331        });
6332
6333        cx.dispatch_keystroke(
6334            window_id,
6335            vec![view_1.id(), view_2.id(), view_3.id()],
6336            &Keystroke::parse("a").unwrap(),
6337        );
6338
6339        assert_eq!(&*actions.borrow(), &["2 a"]);
6340
6341        actions.borrow_mut().clear();
6342        cx.dispatch_keystroke(
6343            window_id,
6344            vec![view_1.id(), view_2.id(), view_3.id()],
6345            &Keystroke::parse("b").unwrap(),
6346        );
6347
6348        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
6349    }
6350
6351    #[crate::test(self)]
6352    async fn test_model_condition(cx: &mut TestAppContext) {
6353        struct Counter(usize);
6354
6355        impl super::Entity for Counter {
6356            type Event = ();
6357        }
6358
6359        impl Counter {
6360            fn inc(&mut self, cx: &mut ModelContext<Self>) {
6361                self.0 += 1;
6362                cx.notify();
6363            }
6364        }
6365
6366        let model = cx.add_model(|_| Counter(0));
6367
6368        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
6369        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
6370        smol::pin!(condition1, condition2);
6371
6372        model.update(cx, |model, cx| model.inc(cx));
6373        assert_eq!(poll_once(&mut condition1).await, None);
6374        assert_eq!(poll_once(&mut condition2).await, None);
6375
6376        model.update(cx, |model, cx| model.inc(cx));
6377        assert_eq!(poll_once(&mut condition1).await, Some(()));
6378        assert_eq!(poll_once(&mut condition2).await, None);
6379
6380        model.update(cx, |model, cx| model.inc(cx));
6381        assert_eq!(poll_once(&mut condition2).await, Some(()));
6382
6383        model.update(cx, |_, cx| cx.notify());
6384    }
6385
6386    #[crate::test(self)]
6387    #[should_panic]
6388    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
6389        struct Model;
6390
6391        impl super::Entity for Model {
6392            type Event = ();
6393        }
6394
6395        let model = cx.add_model(|_| Model);
6396        model.condition(&cx, |_, _| false).await;
6397    }
6398
6399    #[crate::test(self)]
6400    #[should_panic(expected = "model dropped with pending condition")]
6401    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
6402        struct Model;
6403
6404        impl super::Entity for Model {
6405            type Event = ();
6406        }
6407
6408        let model = cx.add_model(|_| Model);
6409        let condition = model.condition(&cx, |_, _| false);
6410        cx.update(|_| drop(model));
6411        condition.await;
6412    }
6413
6414    #[crate::test(self)]
6415    async fn test_view_condition(cx: &mut TestAppContext) {
6416        struct Counter(usize);
6417
6418        impl super::Entity for Counter {
6419            type Event = ();
6420        }
6421
6422        impl super::View for Counter {
6423            fn ui_name() -> &'static str {
6424                "test view"
6425            }
6426
6427            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6428                Empty::new().boxed()
6429            }
6430        }
6431
6432        impl Counter {
6433            fn inc(&mut self, cx: &mut ViewContext<Self>) {
6434                self.0 += 1;
6435                cx.notify();
6436            }
6437        }
6438
6439        let (_, view) = cx.add_window(|_| Counter(0));
6440
6441        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
6442        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
6443        smol::pin!(condition1, condition2);
6444
6445        view.update(cx, |view, cx| view.inc(cx));
6446        assert_eq!(poll_once(&mut condition1).await, None);
6447        assert_eq!(poll_once(&mut condition2).await, None);
6448
6449        view.update(cx, |view, cx| view.inc(cx));
6450        assert_eq!(poll_once(&mut condition1).await, Some(()));
6451        assert_eq!(poll_once(&mut condition2).await, None);
6452
6453        view.update(cx, |view, cx| view.inc(cx));
6454        assert_eq!(poll_once(&mut condition2).await, Some(()));
6455        view.update(cx, |_, cx| cx.notify());
6456    }
6457
6458    #[crate::test(self)]
6459    #[should_panic]
6460    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
6461        struct View;
6462
6463        impl super::Entity for View {
6464            type Event = ();
6465        }
6466
6467        impl super::View for View {
6468            fn ui_name() -> &'static str {
6469                "test view"
6470            }
6471
6472            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6473                Empty::new().boxed()
6474            }
6475        }
6476
6477        let (_, view) = cx.add_window(|_| View);
6478        view.condition(&cx, |_, _| false).await;
6479    }
6480
6481    #[crate::test(self)]
6482    #[should_panic(expected = "view dropped with pending condition")]
6483    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
6484        struct View;
6485
6486        impl super::Entity for View {
6487            type Event = ();
6488        }
6489
6490        impl super::View for View {
6491            fn ui_name() -> &'static str {
6492                "test view"
6493            }
6494
6495            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6496                Empty::new().boxed()
6497            }
6498        }
6499
6500        let window_id = cx.add_window(|_| View).0;
6501        let view = cx.add_view(window_id, |_| View);
6502
6503        let condition = view.condition(&cx, |_, _| false);
6504        cx.update(|_| drop(view));
6505        condition.await;
6506    }
6507
6508    #[crate::test(self)]
6509    fn test_refresh_windows(cx: &mut MutableAppContext) {
6510        struct View(usize);
6511
6512        impl super::Entity for View {
6513            type Event = ();
6514        }
6515
6516        impl super::View for View {
6517            fn ui_name() -> &'static str {
6518                "test view"
6519            }
6520
6521            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6522                Empty::new().named(format!("render count: {}", post_inc(&mut self.0)))
6523            }
6524        }
6525
6526        let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
6527        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
6528
6529        assert_eq!(
6530            presenter.borrow().rendered_views[&root_view.id()].name(),
6531            Some("render count: 0")
6532        );
6533
6534        let view = cx.add_view(window_id, |cx| {
6535            cx.refresh_windows();
6536            View(0)
6537        });
6538
6539        assert_eq!(
6540            presenter.borrow().rendered_views[&root_view.id()].name(),
6541            Some("render count: 1")
6542        );
6543        assert_eq!(
6544            presenter.borrow().rendered_views[&view.id()].name(),
6545            Some("render count: 0")
6546        );
6547
6548        cx.update(|cx| cx.refresh_windows());
6549        assert_eq!(
6550            presenter.borrow().rendered_views[&root_view.id()].name(),
6551            Some("render count: 2")
6552        );
6553        assert_eq!(
6554            presenter.borrow().rendered_views[&view.id()].name(),
6555            Some("render count: 1")
6556        );
6557
6558        cx.update(|cx| {
6559            cx.refresh_windows();
6560            drop(view);
6561        });
6562        assert_eq!(
6563            presenter.borrow().rendered_views[&root_view.id()].name(),
6564            Some("render count: 3")
6565        );
6566        assert_eq!(presenter.borrow().rendered_views.len(), 1);
6567    }
6568}