app.rs

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