app.rs

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