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