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        let (tx, mut rx) = futures::channel::mpsc::unbounded();
3396        let mut cx = cx.cx.borrow_mut();
3397        let subscription = cx.observe(self, move |_, _| {
3398            tx.unbounded_send(()).ok();
3399        });
3400
3401        let duration = if std::env::var("CI").is_ok() {
3402            Duration::from_secs(5)
3403        } else {
3404            Duration::from_secs(1)
3405        };
3406
3407        async move {
3408            let notification = crate::util::timeout(duration, rx.next())
3409                .await
3410                .expect("next notification timed out");
3411            drop(subscription);
3412            notification.expect("model dropped while test was waiting for its next notification")
3413        }
3414    }
3415
3416    #[cfg(any(test, feature = "test-support"))]
3417    pub fn next_event(&self, cx: &TestAppContext) -> impl Future<Output = T::Event>
3418    where
3419        T::Event: Clone,
3420    {
3421        let (tx, mut rx) = futures::channel::mpsc::unbounded();
3422        let mut cx = cx.cx.borrow_mut();
3423        let subscription = cx.subscribe(self, move |_, event, _| {
3424            tx.unbounded_send(event.clone()).ok();
3425        });
3426
3427        let duration = if std::env::var("CI").is_ok() {
3428            Duration::from_secs(5)
3429        } else {
3430            Duration::from_secs(1)
3431        };
3432
3433        cx.foreground.start_waiting();
3434        async move {
3435            let event = crate::util::timeout(duration, rx.next())
3436                .await
3437                .expect("next event timed out");
3438            drop(subscription);
3439            event.expect("model dropped while test was waiting for its next event")
3440        }
3441    }
3442
3443    #[cfg(any(test, feature = "test-support"))]
3444    pub fn condition(
3445        &self,
3446        cx: &TestAppContext,
3447        mut predicate: impl FnMut(&T, &AppContext) -> bool,
3448    ) -> impl Future<Output = ()> {
3449        let (tx, mut rx) = futures::channel::mpsc::unbounded();
3450
3451        let mut cx = cx.cx.borrow_mut();
3452        let subscriptions = (
3453            cx.observe(self, {
3454                let tx = tx.clone();
3455                move |_, _| {
3456                    tx.unbounded_send(()).ok();
3457                }
3458            }),
3459            cx.subscribe(self, {
3460                let tx = tx.clone();
3461                move |_, _, _| {
3462                    tx.unbounded_send(()).ok();
3463                }
3464            }),
3465        );
3466
3467        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
3468        let handle = self.downgrade();
3469        let duration = if std::env::var("CI").is_ok() {
3470            Duration::from_secs(5)
3471        } else {
3472            Duration::from_secs(1)
3473        };
3474
3475        async move {
3476            crate::util::timeout(duration, async move {
3477                loop {
3478                    {
3479                        let cx = cx.borrow();
3480                        let cx = cx.as_ref();
3481                        if predicate(
3482                            handle
3483                                .upgrade(cx)
3484                                .expect("model dropped with pending condition")
3485                                .read(cx),
3486                            cx,
3487                        ) {
3488                            break;
3489                        }
3490                    }
3491
3492                    cx.borrow().foreground().start_waiting();
3493                    rx.next()
3494                        .await
3495                        .expect("model dropped with pending condition");
3496                    cx.borrow().foreground().finish_waiting();
3497                }
3498            })
3499            .await
3500            .expect("condition timed out");
3501            drop(subscriptions);
3502        }
3503    }
3504}
3505
3506impl<T: Entity> Clone for ModelHandle<T> {
3507    fn clone(&self) -> Self {
3508        Self::new(self.model_id, &self.ref_counts)
3509    }
3510}
3511
3512impl<T: Entity> PartialEq for ModelHandle<T> {
3513    fn eq(&self, other: &Self) -> bool {
3514        self.model_id == other.model_id
3515    }
3516}
3517
3518impl<T: Entity> Eq for ModelHandle<T> {}
3519
3520impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
3521    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
3522        self.model_id == other.model_id
3523    }
3524}
3525
3526impl<T: Entity> Hash for ModelHandle<T> {
3527    fn hash<H: Hasher>(&self, state: &mut H) {
3528        self.model_id.hash(state);
3529    }
3530}
3531
3532impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
3533    fn borrow(&self) -> &usize {
3534        &self.model_id
3535    }
3536}
3537
3538impl<T: Entity> Debug for ModelHandle<T> {
3539    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3540        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
3541            .field(&self.model_id)
3542            .finish()
3543    }
3544}
3545
3546unsafe impl<T: Entity> Send for ModelHandle<T> {}
3547unsafe impl<T: Entity> Sync for ModelHandle<T> {}
3548
3549impl<T: Entity> Drop for ModelHandle<T> {
3550    fn drop(&mut self) {
3551        let mut ref_counts = self.ref_counts.lock();
3552        ref_counts.dec_model(self.model_id);
3553
3554        #[cfg(any(test, feature = "test-support"))]
3555        ref_counts
3556            .leak_detector
3557            .lock()
3558            .handle_dropped(self.model_id, self.handle_id);
3559    }
3560}
3561
3562impl<T: Entity> Handle<T> for ModelHandle<T> {
3563    type Weak = WeakModelHandle<T>;
3564
3565    fn id(&self) -> usize {
3566        self.model_id
3567    }
3568
3569    fn location(&self) -> EntityLocation {
3570        EntityLocation::Model(self.model_id)
3571    }
3572
3573    fn downgrade(&self) -> Self::Weak {
3574        self.downgrade()
3575    }
3576
3577    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3578    where
3579        Self: Sized,
3580    {
3581        weak.upgrade(cx)
3582    }
3583}
3584
3585pub struct WeakModelHandle<T> {
3586    model_id: usize,
3587    model_type: PhantomData<T>,
3588}
3589
3590impl<T> WeakHandle for WeakModelHandle<T> {
3591    fn id(&self) -> usize {
3592        self.model_id
3593    }
3594}
3595
3596unsafe impl<T> Send for WeakModelHandle<T> {}
3597unsafe impl<T> Sync for WeakModelHandle<T> {}
3598
3599impl<T: Entity> WeakModelHandle<T> {
3600    fn new(model_id: usize) -> Self {
3601        Self {
3602            model_id,
3603            model_type: PhantomData,
3604        }
3605    }
3606
3607    pub fn id(&self) -> usize {
3608        self.model_id
3609    }
3610
3611    pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
3612        cx.model_handle_is_upgradable(self)
3613    }
3614
3615    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
3616        cx.upgrade_model_handle(self)
3617    }
3618}
3619
3620impl<T> Hash for WeakModelHandle<T> {
3621    fn hash<H: Hasher>(&self, state: &mut H) {
3622        self.model_id.hash(state)
3623    }
3624}
3625
3626impl<T> PartialEq for WeakModelHandle<T> {
3627    fn eq(&self, other: &Self) -> bool {
3628        self.model_id == other.model_id
3629    }
3630}
3631
3632impl<T> Eq for WeakModelHandle<T> {}
3633
3634impl<T> Clone for WeakModelHandle<T> {
3635    fn clone(&self) -> Self {
3636        Self {
3637            model_id: self.model_id,
3638            model_type: PhantomData,
3639        }
3640    }
3641}
3642
3643impl<T> Copy for WeakModelHandle<T> {}
3644
3645pub struct ViewHandle<T> {
3646    window_id: usize,
3647    view_id: usize,
3648    view_type: PhantomData<T>,
3649    ref_counts: Arc<Mutex<RefCounts>>,
3650    #[cfg(any(test, feature = "test-support"))]
3651    handle_id: usize,
3652}
3653
3654impl<T: View> ViewHandle<T> {
3655    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3656        ref_counts.lock().inc_view(window_id, view_id);
3657        #[cfg(any(test, feature = "test-support"))]
3658        let handle_id = ref_counts
3659            .lock()
3660            .leak_detector
3661            .lock()
3662            .handle_created(Some(type_name::<T>()), view_id);
3663
3664        Self {
3665            window_id,
3666            view_id,
3667            view_type: PhantomData,
3668            ref_counts: ref_counts.clone(),
3669
3670            #[cfg(any(test, feature = "test-support"))]
3671            handle_id,
3672        }
3673    }
3674
3675    pub fn downgrade(&self) -> WeakViewHandle<T> {
3676        WeakViewHandle::new(self.window_id, self.view_id)
3677    }
3678
3679    pub fn window_id(&self) -> usize {
3680        self.window_id
3681    }
3682
3683    pub fn id(&self) -> usize {
3684        self.view_id
3685    }
3686
3687    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
3688        cx.read_view(self)
3689    }
3690
3691    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3692    where
3693        C: ReadViewWith,
3694        F: FnOnce(&T, &AppContext) -> S,
3695    {
3696        let mut read = Some(read);
3697        cx.read_view_with(self, &mut |view, cx| {
3698            let read = read.take().unwrap();
3699            read(view, cx)
3700        })
3701    }
3702
3703    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3704    where
3705        C: UpdateView,
3706        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
3707    {
3708        let mut update = Some(update);
3709        cx.update_view(self, &mut |view, cx| {
3710            let update = update.take().unwrap();
3711            update(view, cx)
3712        })
3713    }
3714
3715    pub fn defer<C, F>(&self, cx: &mut C, update: F)
3716    where
3717        C: AsMut<MutableAppContext>,
3718        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
3719    {
3720        let this = self.clone();
3721        cx.as_mut().defer(move |cx| {
3722            this.update(cx, |view, cx| update(view, cx));
3723        });
3724    }
3725
3726    pub fn is_focused(&self, cx: &AppContext) -> bool {
3727        cx.focused_view_id(self.window_id)
3728            .map_or(false, |focused_id| focused_id == self.view_id)
3729    }
3730
3731    #[cfg(any(test, feature = "test-support"))]
3732    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
3733        use postage::prelude::{Sink as _, Stream as _};
3734
3735        let (mut tx, mut rx) = postage::mpsc::channel(1);
3736        let mut cx = cx.cx.borrow_mut();
3737        let subscription = cx.observe(self, move |_, _| {
3738            tx.try_send(()).ok();
3739        });
3740
3741        let duration = if std::env::var("CI").is_ok() {
3742            Duration::from_secs(5)
3743        } else {
3744            Duration::from_secs(1)
3745        };
3746
3747        async move {
3748            let notification = crate::util::timeout(duration, rx.recv())
3749                .await
3750                .expect("next notification timed out");
3751            drop(subscription);
3752            notification.expect("model dropped while test was waiting for its next notification")
3753        }
3754    }
3755
3756    #[cfg(any(test, feature = "test-support"))]
3757    pub fn condition(
3758        &self,
3759        cx: &TestAppContext,
3760        mut predicate: impl FnMut(&T, &AppContext) -> bool,
3761    ) -> impl Future<Output = ()> {
3762        use postage::prelude::{Sink as _, Stream as _};
3763
3764        let (tx, mut rx) = postage::mpsc::channel(1024);
3765
3766        let mut cx = cx.cx.borrow_mut();
3767        let subscriptions = self.update(&mut *cx, |_, cx| {
3768            (
3769                cx.observe(self, {
3770                    let mut tx = tx.clone();
3771                    move |_, _, _| {
3772                        tx.blocking_send(()).ok();
3773                    }
3774                }),
3775                cx.subscribe(self, {
3776                    let mut tx = tx.clone();
3777                    move |_, _, _, _| {
3778                        tx.blocking_send(()).ok();
3779                    }
3780                }),
3781            )
3782        });
3783
3784        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
3785        let handle = self.downgrade();
3786        let duration = if std::env::var("CI").is_ok() {
3787            Duration::from_secs(2)
3788        } else {
3789            Duration::from_millis(500)
3790        };
3791
3792        async move {
3793            crate::util::timeout(duration, async move {
3794                loop {
3795                    {
3796                        let cx = cx.borrow();
3797                        let cx = cx.as_ref();
3798                        if predicate(
3799                            handle
3800                                .upgrade(cx)
3801                                .expect("view dropped with pending condition")
3802                                .read(cx),
3803                            cx,
3804                        ) {
3805                            break;
3806                        }
3807                    }
3808
3809                    cx.borrow().foreground().start_waiting();
3810                    rx.recv()
3811                        .await
3812                        .expect("view dropped with pending condition");
3813                    cx.borrow().foreground().finish_waiting();
3814                }
3815            })
3816            .await
3817            .expect("condition timed out");
3818            drop(subscriptions);
3819        }
3820    }
3821}
3822
3823impl<T: View> Clone for ViewHandle<T> {
3824    fn clone(&self) -> Self {
3825        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
3826    }
3827}
3828
3829impl<T> PartialEq for ViewHandle<T> {
3830    fn eq(&self, other: &Self) -> bool {
3831        self.window_id == other.window_id && self.view_id == other.view_id
3832    }
3833}
3834
3835impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
3836    fn eq(&self, other: &WeakViewHandle<T>) -> bool {
3837        self.window_id == other.window_id && self.view_id == other.view_id
3838    }
3839}
3840
3841impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
3842    fn eq(&self, other: &ViewHandle<T>) -> bool {
3843        self.window_id == other.window_id && self.view_id == other.view_id
3844    }
3845}
3846
3847impl<T> Eq for ViewHandle<T> {}
3848
3849impl<T> Hash for ViewHandle<T> {
3850    fn hash<H: Hasher>(&self, state: &mut H) {
3851        self.window_id.hash(state);
3852        self.view_id.hash(state);
3853    }
3854}
3855
3856impl<T> Debug for ViewHandle<T> {
3857    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3858        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
3859            .field("window_id", &self.window_id)
3860            .field("view_id", &self.view_id)
3861            .finish()
3862    }
3863}
3864
3865impl<T> Drop for ViewHandle<T> {
3866    fn drop(&mut self) {
3867        self.ref_counts
3868            .lock()
3869            .dec_view(self.window_id, self.view_id);
3870        #[cfg(any(test, feature = "test-support"))]
3871        self.ref_counts
3872            .lock()
3873            .leak_detector
3874            .lock()
3875            .handle_dropped(self.view_id, self.handle_id);
3876    }
3877}
3878
3879impl<T: View> Handle<T> for ViewHandle<T> {
3880    type Weak = WeakViewHandle<T>;
3881
3882    fn id(&self) -> usize {
3883        self.view_id
3884    }
3885
3886    fn location(&self) -> EntityLocation {
3887        EntityLocation::View(self.window_id, self.view_id)
3888    }
3889
3890    fn downgrade(&self) -> Self::Weak {
3891        self.downgrade()
3892    }
3893
3894    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3895    where
3896        Self: Sized,
3897    {
3898        weak.upgrade(cx)
3899    }
3900}
3901
3902pub struct AnyViewHandle {
3903    window_id: usize,
3904    view_id: usize,
3905    view_type: TypeId,
3906    ref_counts: Arc<Mutex<RefCounts>>,
3907
3908    #[cfg(any(test, feature = "test-support"))]
3909    handle_id: usize,
3910}
3911
3912impl AnyViewHandle {
3913    fn new(
3914        window_id: usize,
3915        view_id: usize,
3916        view_type: TypeId,
3917        ref_counts: Arc<Mutex<RefCounts>>,
3918    ) -> Self {
3919        ref_counts.lock().inc_view(window_id, view_id);
3920
3921        #[cfg(any(test, feature = "test-support"))]
3922        let handle_id = ref_counts
3923            .lock()
3924            .leak_detector
3925            .lock()
3926            .handle_created(None, view_id);
3927
3928        Self {
3929            window_id,
3930            view_id,
3931            view_type,
3932            ref_counts,
3933            #[cfg(any(test, feature = "test-support"))]
3934            handle_id,
3935        }
3936    }
3937
3938    pub fn id(&self) -> usize {
3939        self.view_id
3940    }
3941
3942    pub fn is<T: 'static>(&self) -> bool {
3943        TypeId::of::<T>() == self.view_type
3944    }
3945
3946    pub fn is_focused(&self, cx: &AppContext) -> bool {
3947        cx.focused_view_id(self.window_id)
3948            .map_or(false, |focused_id| focused_id == self.view_id)
3949    }
3950
3951    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
3952        if self.is::<T>() {
3953            let result = Some(ViewHandle {
3954                window_id: self.window_id,
3955                view_id: self.view_id,
3956                ref_counts: self.ref_counts.clone(),
3957                view_type: PhantomData,
3958                #[cfg(any(test, feature = "test-support"))]
3959                handle_id: self.handle_id,
3960            });
3961            unsafe {
3962                Arc::decrement_strong_count(&self.ref_counts);
3963            }
3964            std::mem::forget(self);
3965            result
3966        } else {
3967            None
3968        }
3969    }
3970
3971    pub fn downgrade(&self) -> AnyWeakViewHandle {
3972        AnyWeakViewHandle {
3973            window_id: self.window_id,
3974            view_id: self.view_id,
3975            view_type: self.view_type,
3976        }
3977    }
3978
3979    pub fn view_type(&self) -> TypeId {
3980        self.view_type
3981    }
3982}
3983
3984impl Clone for AnyViewHandle {
3985    fn clone(&self) -> Self {
3986        Self::new(
3987            self.window_id,
3988            self.view_id,
3989            self.view_type,
3990            self.ref_counts.clone(),
3991        )
3992    }
3993}
3994
3995impl From<&AnyViewHandle> for AnyViewHandle {
3996    fn from(handle: &AnyViewHandle) -> Self {
3997        handle.clone()
3998    }
3999}
4000
4001impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
4002    fn from(handle: &ViewHandle<T>) -> Self {
4003        Self::new(
4004            handle.window_id,
4005            handle.view_id,
4006            TypeId::of::<T>(),
4007            handle.ref_counts.clone(),
4008        )
4009    }
4010}
4011
4012impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
4013    fn from(handle: ViewHandle<T>) -> Self {
4014        let any_handle = AnyViewHandle {
4015            window_id: handle.window_id,
4016            view_id: handle.view_id,
4017            view_type: TypeId::of::<T>(),
4018            ref_counts: handle.ref_counts.clone(),
4019            #[cfg(any(test, feature = "test-support"))]
4020            handle_id: handle.handle_id,
4021        };
4022        unsafe {
4023            Arc::decrement_strong_count(&handle.ref_counts);
4024        }
4025        std::mem::forget(handle);
4026        any_handle
4027    }
4028}
4029
4030impl Drop for AnyViewHandle {
4031    fn drop(&mut self) {
4032        self.ref_counts
4033            .lock()
4034            .dec_view(self.window_id, self.view_id);
4035        #[cfg(any(test, feature = "test-support"))]
4036        self.ref_counts
4037            .lock()
4038            .leak_detector
4039            .lock()
4040            .handle_dropped(self.view_id, self.handle_id);
4041    }
4042}
4043
4044pub struct AnyModelHandle {
4045    model_id: usize,
4046    model_type: TypeId,
4047    ref_counts: Arc<Mutex<RefCounts>>,
4048
4049    #[cfg(any(test, feature = "test-support"))]
4050    handle_id: usize,
4051}
4052
4053impl AnyModelHandle {
4054    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
4055        ref_counts.lock().inc_model(model_id);
4056
4057        #[cfg(any(test, feature = "test-support"))]
4058        let handle_id = ref_counts
4059            .lock()
4060            .leak_detector
4061            .lock()
4062            .handle_created(None, model_id);
4063
4064        Self {
4065            model_id,
4066            model_type,
4067            ref_counts,
4068
4069            #[cfg(any(test, feature = "test-support"))]
4070            handle_id,
4071        }
4072    }
4073
4074    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
4075        if self.is::<T>() {
4076            let result = Some(ModelHandle {
4077                model_id: self.model_id,
4078                model_type: PhantomData,
4079                ref_counts: self.ref_counts.clone(),
4080
4081                #[cfg(any(test, feature = "test-support"))]
4082                handle_id: self.handle_id,
4083            });
4084            unsafe {
4085                Arc::decrement_strong_count(&self.ref_counts);
4086            }
4087            std::mem::forget(self);
4088            result
4089        } else {
4090            None
4091        }
4092    }
4093
4094    pub fn downgrade(&self) -> AnyWeakModelHandle {
4095        AnyWeakModelHandle {
4096            model_id: self.model_id,
4097            model_type: self.model_type,
4098        }
4099    }
4100
4101    pub fn is<T: Entity>(&self) -> bool {
4102        self.model_type == TypeId::of::<T>()
4103    }
4104
4105    pub fn model_type(&self) -> TypeId {
4106        self.model_type
4107    }
4108}
4109
4110impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
4111    fn from(handle: ModelHandle<T>) -> Self {
4112        Self::new(
4113            handle.model_id,
4114            TypeId::of::<T>(),
4115            handle.ref_counts.clone(),
4116        )
4117    }
4118}
4119
4120impl Clone for AnyModelHandle {
4121    fn clone(&self) -> Self {
4122        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
4123    }
4124}
4125
4126impl Drop for AnyModelHandle {
4127    fn drop(&mut self) {
4128        let mut ref_counts = self.ref_counts.lock();
4129        ref_counts.dec_model(self.model_id);
4130
4131        #[cfg(any(test, feature = "test-support"))]
4132        ref_counts
4133            .leak_detector
4134            .lock()
4135            .handle_dropped(self.model_id, self.handle_id);
4136    }
4137}
4138
4139pub struct AnyWeakModelHandle {
4140    model_id: usize,
4141    model_type: TypeId,
4142}
4143
4144impl AnyWeakModelHandle {
4145    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
4146        cx.upgrade_any_model_handle(self)
4147    }
4148}
4149
4150impl<T: Entity> From<WeakModelHandle<T>> for AnyWeakModelHandle {
4151    fn from(handle: WeakModelHandle<T>) -> Self {
4152        AnyWeakModelHandle {
4153            model_id: handle.model_id,
4154            model_type: TypeId::of::<T>(),
4155        }
4156    }
4157}
4158
4159pub struct WeakViewHandle<T> {
4160    window_id: usize,
4161    view_id: usize,
4162    view_type: PhantomData<T>,
4163}
4164
4165impl<T> WeakHandle for WeakViewHandle<T> {
4166    fn id(&self) -> usize {
4167        self.view_id
4168    }
4169}
4170
4171impl<T: View> WeakViewHandle<T> {
4172    fn new(window_id: usize, view_id: usize) -> Self {
4173        Self {
4174            window_id,
4175            view_id,
4176            view_type: PhantomData,
4177        }
4178    }
4179
4180    pub fn id(&self) -> usize {
4181        self.view_id
4182    }
4183
4184    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
4185        cx.upgrade_view_handle(self)
4186    }
4187}
4188
4189impl<T> Clone for WeakViewHandle<T> {
4190    fn clone(&self) -> Self {
4191        Self {
4192            window_id: self.window_id,
4193            view_id: self.view_id,
4194            view_type: PhantomData,
4195        }
4196    }
4197}
4198
4199impl<T> PartialEq for WeakViewHandle<T> {
4200    fn eq(&self, other: &Self) -> bool {
4201        self.window_id == other.window_id && self.view_id == other.view_id
4202    }
4203}
4204
4205impl<T> Eq for WeakViewHandle<T> {}
4206
4207impl<T> Hash for WeakViewHandle<T> {
4208    fn hash<H: Hasher>(&self, state: &mut H) {
4209        self.window_id.hash(state);
4210        self.view_id.hash(state);
4211    }
4212}
4213
4214pub struct AnyWeakViewHandle {
4215    window_id: usize,
4216    view_id: usize,
4217    view_type: TypeId,
4218}
4219
4220impl AnyWeakViewHandle {
4221    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<AnyViewHandle> {
4222        cx.upgrade_any_view_handle(self)
4223    }
4224}
4225
4226impl<T: View> From<WeakViewHandle<T>> for AnyWeakViewHandle {
4227    fn from(handle: WeakViewHandle<T>) -> Self {
4228        AnyWeakViewHandle {
4229            window_id: handle.window_id,
4230            view_id: handle.view_id,
4231            view_type: TypeId::of::<T>(),
4232        }
4233    }
4234}
4235
4236#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4237pub struct ElementStateId {
4238    view_id: usize,
4239    element_id: usize,
4240    tag: TypeId,
4241}
4242
4243pub struct ElementStateHandle<T> {
4244    value_type: PhantomData<T>,
4245    id: ElementStateId,
4246    ref_counts: Weak<Mutex<RefCounts>>,
4247}
4248
4249impl<T: 'static> ElementStateHandle<T> {
4250    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4251        ref_counts.lock().inc_element_state(id, frame_id);
4252        Self {
4253            value_type: PhantomData,
4254            id,
4255            ref_counts: Arc::downgrade(ref_counts),
4256        }
4257    }
4258
4259    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
4260        cx.element_states
4261            .get(&self.id)
4262            .unwrap()
4263            .downcast_ref()
4264            .unwrap()
4265    }
4266
4267    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
4268    where
4269        C: DerefMut<Target = MutableAppContext>,
4270    {
4271        let mut element_state = cx.deref_mut().cx.element_states.remove(&self.id).unwrap();
4272        let result = f(element_state.downcast_mut().unwrap(), cx);
4273        cx.deref_mut()
4274            .cx
4275            .element_states
4276            .insert(self.id, element_state);
4277        result
4278    }
4279}
4280
4281impl<T> Drop for ElementStateHandle<T> {
4282    fn drop(&mut self) {
4283        if let Some(ref_counts) = self.ref_counts.upgrade() {
4284            ref_counts.lock().dec_element_state(self.id);
4285        }
4286    }
4287}
4288
4289pub struct CursorStyleHandle {
4290    id: usize,
4291    next_cursor_style_handle_id: Arc<AtomicUsize>,
4292    platform: Arc<dyn Platform>,
4293}
4294
4295impl Drop for CursorStyleHandle {
4296    fn drop(&mut self) {
4297        if self.id + 1 == self.next_cursor_style_handle_id.load(SeqCst) {
4298            self.platform.set_cursor_style(CursorStyle::Arrow);
4299        }
4300    }
4301}
4302
4303#[must_use]
4304pub enum Subscription {
4305    Subscription {
4306        id: usize,
4307        entity_id: usize,
4308        subscriptions:
4309            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, Option<SubscriptionCallback>>>>>>,
4310    },
4311    GlobalSubscription {
4312        id: usize,
4313        type_id: TypeId,
4314        subscriptions: Option<
4315            Weak<Mutex<HashMap<TypeId, BTreeMap<usize, Option<GlobalSubscriptionCallback>>>>>,
4316        >,
4317    },
4318    Observation {
4319        id: usize,
4320        entity_id: usize,
4321        observations:
4322            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, Option<ObservationCallback>>>>>>,
4323    },
4324    GlobalObservation {
4325        id: usize,
4326        type_id: TypeId,
4327        observations: Option<
4328            Weak<Mutex<HashMap<TypeId, BTreeMap<usize, Option<GlobalObservationCallback>>>>>,
4329        >,
4330    },
4331    ReleaseObservation {
4332        id: usize,
4333        entity_id: usize,
4334        observations:
4335            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>>,
4336    },
4337}
4338
4339impl Subscription {
4340    pub fn detach(&mut self) {
4341        match self {
4342            Subscription::Subscription { subscriptions, .. } => {
4343                subscriptions.take();
4344            }
4345            Subscription::GlobalSubscription { subscriptions, .. } => {
4346                subscriptions.take();
4347            }
4348            Subscription::Observation { observations, .. } => {
4349                observations.take();
4350            }
4351            Subscription::GlobalObservation { observations, .. } => {
4352                observations.take();
4353            }
4354            Subscription::ReleaseObservation { observations, .. } => {
4355                observations.take();
4356            }
4357        }
4358    }
4359}
4360
4361impl Drop for Subscription {
4362    fn drop(&mut self) {
4363        match self {
4364            Subscription::Subscription {
4365                id,
4366                entity_id,
4367                subscriptions,
4368            } => {
4369                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
4370                    match subscriptions
4371                        .lock()
4372                        .entry(*entity_id)
4373                        .or_default()
4374                        .entry(*id)
4375                    {
4376                        btree_map::Entry::Vacant(entry) => {
4377                            entry.insert(None);
4378                        }
4379                        btree_map::Entry::Occupied(entry) => {
4380                            entry.remove();
4381                        }
4382                    }
4383                }
4384            }
4385            Subscription::GlobalSubscription {
4386                id,
4387                type_id,
4388                subscriptions,
4389            } => {
4390                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
4391                    match subscriptions.lock().entry(*type_id).or_default().entry(*id) {
4392                        btree_map::Entry::Vacant(entry) => {
4393                            entry.insert(None);
4394                        }
4395                        btree_map::Entry::Occupied(entry) => {
4396                            entry.remove();
4397                        }
4398                    }
4399                }
4400            }
4401            Subscription::Observation {
4402                id,
4403                entity_id,
4404                observations,
4405            } => {
4406                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4407                    match observations
4408                        .lock()
4409                        .entry(*entity_id)
4410                        .or_default()
4411                        .entry(*id)
4412                    {
4413                        btree_map::Entry::Vacant(entry) => {
4414                            entry.insert(None);
4415                        }
4416                        btree_map::Entry::Occupied(entry) => {
4417                            entry.remove();
4418                        }
4419                    }
4420                }
4421            }
4422            Subscription::GlobalObservation {
4423                id,
4424                type_id,
4425                observations,
4426            } => {
4427                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4428                    match observations.lock().entry(*type_id).or_default().entry(*id) {
4429                        collections::btree_map::Entry::Vacant(entry) => {
4430                            entry.insert(None);
4431                        }
4432                        collections::btree_map::Entry::Occupied(entry) => {
4433                            entry.remove();
4434                        }
4435                    }
4436                }
4437            }
4438            Subscription::ReleaseObservation {
4439                id,
4440                entity_id,
4441                observations,
4442            } => {
4443                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4444                    if let Some(observations) = observations.lock().get_mut(entity_id) {
4445                        observations.remove(id);
4446                    }
4447                }
4448            }
4449        }
4450    }
4451}
4452
4453lazy_static! {
4454    static ref LEAK_BACKTRACE: bool =
4455        std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty());
4456}
4457
4458#[cfg(any(test, feature = "test-support"))]
4459#[derive(Default)]
4460pub struct LeakDetector {
4461    next_handle_id: usize,
4462    handle_backtraces: HashMap<
4463        usize,
4464        (
4465            Option<&'static str>,
4466            HashMap<usize, Option<backtrace::Backtrace>>,
4467        ),
4468    >,
4469}
4470
4471#[cfg(any(test, feature = "test-support"))]
4472impl LeakDetector {
4473    fn handle_created(&mut self, type_name: Option<&'static str>, entity_id: usize) -> usize {
4474        let handle_id = post_inc(&mut self.next_handle_id);
4475        let entry = self.handle_backtraces.entry(entity_id).or_default();
4476        let backtrace = if *LEAK_BACKTRACE {
4477            Some(backtrace::Backtrace::new_unresolved())
4478        } else {
4479            None
4480        };
4481        if let Some(type_name) = type_name {
4482            entry.0.get_or_insert(type_name);
4483        }
4484        entry.1.insert(handle_id, backtrace);
4485        handle_id
4486    }
4487
4488    fn handle_dropped(&mut self, entity_id: usize, handle_id: usize) {
4489        if let Some((_, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
4490            assert!(backtraces.remove(&handle_id).is_some());
4491            if backtraces.is_empty() {
4492                self.handle_backtraces.remove(&entity_id);
4493            }
4494        }
4495    }
4496
4497    pub fn assert_dropped(&mut self, entity_id: usize) {
4498        if let Some((type_name, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
4499            for trace in backtraces.values_mut() {
4500                if let Some(trace) = trace {
4501                    trace.resolve();
4502                    eprintln!("{:?}", crate::util::CwdBacktrace(trace));
4503                }
4504            }
4505
4506            let hint = if *LEAK_BACKTRACE {
4507                ""
4508            } else {
4509                " – set LEAK_BACKTRACE=1 for more information"
4510            };
4511
4512            panic!(
4513                "{} handles to {} {} still exist{}",
4514                backtraces.len(),
4515                type_name.unwrap_or("entity"),
4516                entity_id,
4517                hint
4518            );
4519        }
4520    }
4521
4522    pub fn detect(&mut self) {
4523        let mut found_leaks = false;
4524        for (id, (type_name, backtraces)) in self.handle_backtraces.iter_mut() {
4525            eprintln!(
4526                "leaked {} handles to {} {}",
4527                backtraces.len(),
4528                type_name.unwrap_or("entity"),
4529                id
4530            );
4531            for trace in backtraces.values_mut() {
4532                if let Some(trace) = trace {
4533                    trace.resolve();
4534                    eprintln!("{:?}", crate::util::CwdBacktrace(trace));
4535                }
4536            }
4537            found_leaks = true;
4538        }
4539
4540        let hint = if *LEAK_BACKTRACE {
4541            ""
4542        } else {
4543            " – set LEAK_BACKTRACE=1 for more information"
4544        };
4545        assert!(!found_leaks, "detected leaked handles{}", hint);
4546    }
4547}
4548
4549#[derive(Default)]
4550struct RefCounts {
4551    entity_counts: HashMap<usize, usize>,
4552    element_state_counts: HashMap<ElementStateId, ElementStateRefCount>,
4553    dropped_models: HashSet<usize>,
4554    dropped_views: HashSet<(usize, usize)>,
4555    dropped_element_states: HashSet<ElementStateId>,
4556
4557    #[cfg(any(test, feature = "test-support"))]
4558    leak_detector: Arc<Mutex<LeakDetector>>,
4559}
4560
4561struct ElementStateRefCount {
4562    ref_count: usize,
4563    frame_id: usize,
4564}
4565
4566impl RefCounts {
4567    fn inc_model(&mut self, model_id: usize) {
4568        match self.entity_counts.entry(model_id) {
4569            Entry::Occupied(mut entry) => {
4570                *entry.get_mut() += 1;
4571            }
4572            Entry::Vacant(entry) => {
4573                entry.insert(1);
4574                self.dropped_models.remove(&model_id);
4575            }
4576        }
4577    }
4578
4579    fn inc_view(&mut self, window_id: usize, view_id: usize) {
4580        match self.entity_counts.entry(view_id) {
4581            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
4582            Entry::Vacant(entry) => {
4583                entry.insert(1);
4584                self.dropped_views.remove(&(window_id, view_id));
4585            }
4586        }
4587    }
4588
4589    fn inc_element_state(&mut self, id: ElementStateId, frame_id: usize) {
4590        match self.element_state_counts.entry(id) {
4591            Entry::Occupied(mut entry) => {
4592                let entry = entry.get_mut();
4593                if entry.frame_id == frame_id || entry.ref_count >= 2 {
4594                    panic!("used the same element state more than once in the same frame");
4595                }
4596                entry.ref_count += 1;
4597                entry.frame_id = frame_id;
4598            }
4599            Entry::Vacant(entry) => {
4600                entry.insert(ElementStateRefCount {
4601                    ref_count: 1,
4602                    frame_id,
4603                });
4604                self.dropped_element_states.remove(&id);
4605            }
4606        }
4607    }
4608
4609    fn dec_model(&mut self, model_id: usize) {
4610        let count = self.entity_counts.get_mut(&model_id).unwrap();
4611        *count -= 1;
4612        if *count == 0 {
4613            self.entity_counts.remove(&model_id);
4614            self.dropped_models.insert(model_id);
4615        }
4616    }
4617
4618    fn dec_view(&mut self, window_id: usize, view_id: usize) {
4619        let count = self.entity_counts.get_mut(&view_id).unwrap();
4620        *count -= 1;
4621        if *count == 0 {
4622            self.entity_counts.remove(&view_id);
4623            self.dropped_views.insert((window_id, view_id));
4624        }
4625    }
4626
4627    fn dec_element_state(&mut self, id: ElementStateId) {
4628        let entry = self.element_state_counts.get_mut(&id).unwrap();
4629        entry.ref_count -= 1;
4630        if entry.ref_count == 0 {
4631            self.element_state_counts.remove(&id);
4632            self.dropped_element_states.insert(id);
4633        }
4634    }
4635
4636    fn is_entity_alive(&self, entity_id: usize) -> bool {
4637        self.entity_counts.contains_key(&entity_id)
4638    }
4639
4640    fn take_dropped(
4641        &mut self,
4642    ) -> (
4643        HashSet<usize>,
4644        HashSet<(usize, usize)>,
4645        HashSet<ElementStateId>,
4646    ) {
4647        (
4648            std::mem::take(&mut self.dropped_models),
4649            std::mem::take(&mut self.dropped_views),
4650            std::mem::take(&mut self.dropped_element_states),
4651        )
4652    }
4653}
4654
4655#[cfg(test)]
4656mod tests {
4657    use super::*;
4658    use crate::elements::*;
4659    use smol::future::poll_once;
4660    use std::{
4661        cell::Cell,
4662        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
4663    };
4664
4665    #[crate::test(self)]
4666    fn test_model_handles(cx: &mut MutableAppContext) {
4667        struct Model {
4668            other: Option<ModelHandle<Model>>,
4669            events: Vec<String>,
4670        }
4671
4672        impl Entity for Model {
4673            type Event = usize;
4674        }
4675
4676        impl Model {
4677            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
4678                if let Some(other) = other.as_ref() {
4679                    cx.observe(other, |me, _, _| {
4680                        me.events.push("notified".into());
4681                    })
4682                    .detach();
4683                    cx.subscribe(other, |me, _, event, _| {
4684                        me.events.push(format!("observed event {}", event));
4685                    })
4686                    .detach();
4687                }
4688
4689                Self {
4690                    other,
4691                    events: Vec::new(),
4692                }
4693            }
4694        }
4695
4696        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
4697        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
4698        assert_eq!(cx.cx.models.len(), 2);
4699
4700        handle_1.update(cx, |model, cx| {
4701            model.events.push("updated".into());
4702            cx.emit(1);
4703            cx.notify();
4704            cx.emit(2);
4705        });
4706        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4707        assert_eq!(
4708            handle_2.read(cx).events,
4709            vec![
4710                "observed event 1".to_string(),
4711                "notified".to_string(),
4712                "observed event 2".to_string(),
4713            ]
4714        );
4715
4716        handle_2.update(cx, |model, _| {
4717            drop(handle_1);
4718            model.other.take();
4719        });
4720
4721        assert_eq!(cx.cx.models.len(), 1);
4722        assert!(cx.subscriptions.lock().is_empty());
4723        assert!(cx.observations.lock().is_empty());
4724    }
4725
4726    #[crate::test(self)]
4727    fn test_model_events(cx: &mut MutableAppContext) {
4728        #[derive(Default)]
4729        struct Model {
4730            events: Vec<usize>,
4731        }
4732
4733        impl Entity for Model {
4734            type Event = usize;
4735        }
4736
4737        let handle_1 = cx.add_model(|_| Model::default());
4738        let handle_2 = cx.add_model(|_| Model::default());
4739
4740        handle_1.update(cx, |_, cx| {
4741            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
4742                model.events.push(*event);
4743
4744                cx.subscribe(&emitter, |model, _, event, _| {
4745                    model.events.push(*event * 2);
4746                })
4747                .detach();
4748            })
4749            .detach();
4750        });
4751
4752        handle_2.update(cx, |_, c| c.emit(7));
4753        assert_eq!(handle_1.read(cx).events, vec![7]);
4754
4755        handle_2.update(cx, |_, c| c.emit(5));
4756        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4757    }
4758
4759    #[crate::test(self)]
4760    fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
4761        #[derive(Default)]
4762        struct Model;
4763
4764        impl Entity for Model {
4765            type Event = ();
4766        }
4767
4768        let events = Rc::new(RefCell::new(Vec::new()));
4769        cx.add_model(|cx| {
4770            drop(cx.subscribe(&cx.handle(), {
4771                let events = events.clone();
4772                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
4773            }));
4774            cx.subscribe(&cx.handle(), {
4775                let events = events.clone();
4776                move |_, _, _, _| events.borrow_mut().push("before emit")
4777            })
4778            .detach();
4779            cx.emit(());
4780            cx.subscribe(&cx.handle(), {
4781                let events = events.clone();
4782                move |_, _, _, _| events.borrow_mut().push("after emit")
4783            })
4784            .detach();
4785            Model
4786        });
4787        assert_eq!(*events.borrow(), ["before emit"]);
4788    }
4789
4790    #[crate::test(self)]
4791    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
4792        #[derive(Default)]
4793        struct Model {
4794            count: usize,
4795            events: Vec<usize>,
4796        }
4797
4798        impl Entity for Model {
4799            type Event = ();
4800        }
4801
4802        let handle_1 = cx.add_model(|_| Model::default());
4803        let handle_2 = cx.add_model(|_| Model::default());
4804
4805        handle_1.update(cx, |_, c| {
4806            c.observe(&handle_2, move |model, observed, c| {
4807                model.events.push(observed.read(c).count);
4808                c.observe(&observed, |model, observed, c| {
4809                    model.events.push(observed.read(c).count * 2);
4810                })
4811                .detach();
4812            })
4813            .detach();
4814        });
4815
4816        handle_2.update(cx, |model, c| {
4817            model.count = 7;
4818            c.notify()
4819        });
4820        assert_eq!(handle_1.read(cx).events, vec![7]);
4821
4822        handle_2.update(cx, |model, c| {
4823            model.count = 5;
4824            c.notify()
4825        });
4826        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
4827    }
4828
4829    #[crate::test(self)]
4830    fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
4831        #[derive(Default)]
4832        struct Model;
4833
4834        impl Entity for Model {
4835            type Event = ();
4836        }
4837
4838        let events = Rc::new(RefCell::new(Vec::new()));
4839        cx.add_model(|cx| {
4840            drop(cx.observe(&cx.handle(), {
4841                let events = events.clone();
4842                move |_, _, _| events.borrow_mut().push("dropped before flush")
4843            }));
4844            cx.observe(&cx.handle(), {
4845                let events = events.clone();
4846                move |_, _, _| events.borrow_mut().push("before notify")
4847            })
4848            .detach();
4849            cx.notify();
4850            cx.observe(&cx.handle(), {
4851                let events = events.clone();
4852                move |_, _, _| events.borrow_mut().push("after notify")
4853            })
4854            .detach();
4855            Model
4856        });
4857        assert_eq!(*events.borrow(), ["before notify"]);
4858    }
4859
4860    #[crate::test(self)]
4861    fn test_defer_and_after_window_update(cx: &mut MutableAppContext) {
4862        struct View {
4863            render_count: usize,
4864        }
4865
4866        impl Entity for View {
4867            type Event = usize;
4868        }
4869
4870        impl super::View for View {
4871            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4872                post_inc(&mut self.render_count);
4873                Empty::new().boxed()
4874            }
4875
4876            fn ui_name() -> &'static str {
4877                "View"
4878            }
4879        }
4880
4881        let (_, view) = cx.add_window(Default::default(), |_| View { render_count: 0 });
4882        let called_defer = Rc::new(AtomicBool::new(false));
4883        let called_after_window_update = Rc::new(AtomicBool::new(false));
4884
4885        view.update(cx, |this, cx| {
4886            assert_eq!(this.render_count, 1);
4887            cx.defer({
4888                let called_defer = called_defer.clone();
4889                move |this, _| {
4890                    assert_eq!(this.render_count, 1);
4891                    called_defer.store(true, SeqCst);
4892                }
4893            });
4894            cx.after_window_update({
4895                let called_after_window_update = called_after_window_update.clone();
4896                move |this, cx| {
4897                    assert_eq!(this.render_count, 2);
4898                    called_after_window_update.store(true, SeqCst);
4899                    cx.notify();
4900                }
4901            });
4902            assert!(!called_defer.load(SeqCst));
4903            assert!(!called_after_window_update.load(SeqCst));
4904            cx.notify();
4905        });
4906
4907        assert!(called_defer.load(SeqCst));
4908        assert!(called_after_window_update.load(SeqCst));
4909        assert_eq!(view.read(cx).render_count, 3);
4910    }
4911
4912    #[crate::test(self)]
4913    fn test_view_handles(cx: &mut MutableAppContext) {
4914        struct View {
4915            other: Option<ViewHandle<View>>,
4916            events: Vec<String>,
4917        }
4918
4919        impl Entity for View {
4920            type Event = usize;
4921        }
4922
4923        impl super::View for View {
4924            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4925                Empty::new().boxed()
4926            }
4927
4928            fn ui_name() -> &'static str {
4929                "View"
4930            }
4931        }
4932
4933        impl View {
4934            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
4935                if let Some(other) = other.as_ref() {
4936                    cx.subscribe(other, |me, _, event, _| {
4937                        me.events.push(format!("observed event {}", event));
4938                    })
4939                    .detach();
4940                }
4941                Self {
4942                    other,
4943                    events: Vec::new(),
4944                }
4945            }
4946        }
4947
4948        let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
4949        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
4950        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
4951        assert_eq!(cx.cx.views.len(), 3);
4952
4953        handle_1.update(cx, |view, cx| {
4954            view.events.push("updated".into());
4955            cx.emit(1);
4956            cx.emit(2);
4957        });
4958        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4959        assert_eq!(
4960            handle_2.read(cx).events,
4961            vec![
4962                "observed event 1".to_string(),
4963                "observed event 2".to_string(),
4964            ]
4965        );
4966
4967        handle_2.update(cx, |view, _| {
4968            drop(handle_1);
4969            view.other.take();
4970        });
4971
4972        assert_eq!(cx.cx.views.len(), 2);
4973        assert!(cx.subscriptions.lock().is_empty());
4974        assert!(cx.observations.lock().is_empty());
4975    }
4976
4977    #[crate::test(self)]
4978    fn test_add_window(cx: &mut MutableAppContext) {
4979        struct View {
4980            mouse_down_count: Arc<AtomicUsize>,
4981        }
4982
4983        impl Entity for View {
4984            type Event = ();
4985        }
4986
4987        impl super::View for View {
4988            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4989                let mouse_down_count = self.mouse_down_count.clone();
4990                EventHandler::new(Empty::new().boxed())
4991                    .on_mouse_down(move |_| {
4992                        mouse_down_count.fetch_add(1, SeqCst);
4993                        true
4994                    })
4995                    .boxed()
4996            }
4997
4998            fn ui_name() -> &'static str {
4999                "View"
5000            }
5001        }
5002
5003        let mouse_down_count = Arc::new(AtomicUsize::new(0));
5004        let (window_id, _) = cx.add_window(Default::default(), |_| View {
5005            mouse_down_count: mouse_down_count.clone(),
5006        });
5007        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
5008        // Ensure window's root element is in a valid lifecycle state.
5009        presenter.borrow_mut().dispatch_event(
5010            Event::LeftMouseDown {
5011                position: Default::default(),
5012                ctrl: false,
5013                alt: false,
5014                shift: false,
5015                cmd: false,
5016                click_count: 1,
5017            },
5018            cx,
5019        );
5020        assert_eq!(mouse_down_count.load(SeqCst), 1);
5021    }
5022
5023    #[crate::test(self)]
5024    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
5025        struct Model {
5026            released: Rc<Cell<bool>>,
5027        }
5028
5029        struct View {
5030            released: Rc<Cell<bool>>,
5031        }
5032
5033        impl Entity for Model {
5034            type Event = ();
5035
5036            fn release(&mut self, _: &mut MutableAppContext) {
5037                self.released.set(true);
5038            }
5039        }
5040
5041        impl Entity for View {
5042            type Event = ();
5043
5044            fn release(&mut self, _: &mut MutableAppContext) {
5045                self.released.set(true);
5046            }
5047        }
5048
5049        impl super::View for View {
5050            fn ui_name() -> &'static str {
5051                "View"
5052            }
5053
5054            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5055                Empty::new().boxed()
5056            }
5057        }
5058
5059        let model_released = Rc::new(Cell::new(false));
5060        let model_release_observed = Rc::new(Cell::new(false));
5061        let view_released = Rc::new(Cell::new(false));
5062        let view_release_observed = Rc::new(Cell::new(false));
5063
5064        let model = cx.add_model(|_| Model {
5065            released: model_released.clone(),
5066        });
5067        let (window_id, view) = cx.add_window(Default::default(), |_| View {
5068            released: view_released.clone(),
5069        });
5070        assert!(!model_released.get());
5071        assert!(!view_released.get());
5072
5073        cx.observe_release(&model, {
5074            let model_release_observed = model_release_observed.clone();
5075            move |_, _| model_release_observed.set(true)
5076        })
5077        .detach();
5078        cx.observe_release(&view, {
5079            let view_release_observed = view_release_observed.clone();
5080            move |_, _| view_release_observed.set(true)
5081        })
5082        .detach();
5083
5084        cx.update(move |_| {
5085            drop(model);
5086        });
5087        assert!(model_released.get());
5088        assert!(model_release_observed.get());
5089
5090        drop(view);
5091        cx.remove_window(window_id);
5092        assert!(view_released.get());
5093        assert!(view_release_observed.get());
5094    }
5095
5096    #[crate::test(self)]
5097    fn test_view_events(cx: &mut MutableAppContext) {
5098        #[derive(Default)]
5099        struct View {
5100            events: Vec<usize>,
5101        }
5102
5103        impl Entity for View {
5104            type Event = usize;
5105        }
5106
5107        impl super::View for View {
5108            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5109                Empty::new().boxed()
5110            }
5111
5112            fn ui_name() -> &'static str {
5113                "View"
5114            }
5115        }
5116
5117        struct Model;
5118
5119        impl Entity for Model {
5120            type Event = usize;
5121        }
5122
5123        let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
5124        let handle_2 = cx.add_view(window_id, |_| View::default());
5125        let handle_3 = cx.add_model(|_| Model);
5126
5127        handle_1.update(cx, |_, cx| {
5128            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
5129                me.events.push(*event);
5130
5131                cx.subscribe(&emitter, |me, _, event, _| {
5132                    me.events.push(*event * 2);
5133                })
5134                .detach();
5135            })
5136            .detach();
5137
5138            cx.subscribe(&handle_3, |me, _, event, _| {
5139                me.events.push(*event);
5140            })
5141            .detach();
5142        });
5143
5144        handle_2.update(cx, |_, c| c.emit(7));
5145        assert_eq!(handle_1.read(cx).events, vec![7]);
5146
5147        handle_2.update(cx, |_, c| c.emit(5));
5148        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
5149
5150        handle_3.update(cx, |_, c| c.emit(9));
5151        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
5152    }
5153
5154    #[crate::test(self)]
5155    fn test_global_events(cx: &mut MutableAppContext) {
5156        #[derive(Clone, Debug, Eq, PartialEq)]
5157        struct GlobalEvent(u64);
5158
5159        let events = Rc::new(RefCell::new(Vec::new()));
5160        let first_subscription;
5161        let second_subscription;
5162
5163        {
5164            let events = events.clone();
5165            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5166                events.borrow_mut().push(("First", e.clone()));
5167            });
5168        }
5169
5170        {
5171            let events = events.clone();
5172            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5173                events.borrow_mut().push(("Second", e.clone()));
5174            });
5175        }
5176
5177        cx.update(|cx| {
5178            cx.emit_global(GlobalEvent(1));
5179            cx.emit_global(GlobalEvent(2));
5180        });
5181
5182        drop(first_subscription);
5183
5184        cx.update(|cx| {
5185            cx.emit_global(GlobalEvent(3));
5186        });
5187
5188        drop(second_subscription);
5189
5190        cx.update(|cx| {
5191            cx.emit_global(GlobalEvent(4));
5192        });
5193
5194        assert_eq!(
5195            &*events.borrow(),
5196            &[
5197                ("First", GlobalEvent(1)),
5198                ("Second", GlobalEvent(1)),
5199                ("First", GlobalEvent(2)),
5200                ("Second", GlobalEvent(2)),
5201                ("Second", GlobalEvent(3)),
5202            ]
5203        );
5204    }
5205
5206    #[crate::test(self)]
5207    fn test_global_events_emitted_before_subscription_in_same_update_cycle(
5208        cx: &mut MutableAppContext,
5209    ) {
5210        let events = Rc::new(RefCell::new(Vec::new()));
5211        cx.update(|cx| {
5212            {
5213                let events = events.clone();
5214                drop(cx.subscribe_global(move |_: &(), _| {
5215                    events.borrow_mut().push("dropped before emit");
5216                }));
5217            }
5218
5219            {
5220                let events = events.clone();
5221                cx.subscribe_global(move |_: &(), _| {
5222                    events.borrow_mut().push("before emit");
5223                })
5224                .detach();
5225            }
5226
5227            cx.emit_global(());
5228
5229            {
5230                let events = events.clone();
5231                cx.subscribe_global(move |_: &(), _| {
5232                    events.borrow_mut().push("after emit");
5233                })
5234                .detach();
5235            }
5236        });
5237
5238        assert_eq!(*events.borrow(), ["before emit"]);
5239    }
5240
5241    #[crate::test(self)]
5242    fn test_global_nested_events(cx: &mut MutableAppContext) {
5243        #[derive(Clone, Debug, Eq, PartialEq)]
5244        struct GlobalEvent(u64);
5245
5246        let events = Rc::new(RefCell::new(Vec::new()));
5247
5248        {
5249            let events = events.clone();
5250            cx.subscribe_global(move |e: &GlobalEvent, cx| {
5251                events.borrow_mut().push(("Outer", e.clone()));
5252
5253                if e.0 == 1 {
5254                    let events = events.clone();
5255                    cx.subscribe_global(move |e: &GlobalEvent, _| {
5256                        events.borrow_mut().push(("Inner", e.clone()));
5257                    })
5258                    .detach();
5259                }
5260            })
5261            .detach();
5262        }
5263
5264        cx.update(|cx| {
5265            cx.emit_global(GlobalEvent(1));
5266            cx.emit_global(GlobalEvent(2));
5267            cx.emit_global(GlobalEvent(3));
5268        });
5269        cx.update(|cx| {
5270            cx.emit_global(GlobalEvent(4));
5271        });
5272
5273        assert_eq!(
5274            &*events.borrow(),
5275            &[
5276                ("Outer", GlobalEvent(1)),
5277                ("Outer", GlobalEvent(2)),
5278                ("Outer", GlobalEvent(3)),
5279                ("Outer", GlobalEvent(4)),
5280                ("Inner", GlobalEvent(4)),
5281            ]
5282        );
5283    }
5284
5285    #[crate::test(self)]
5286    fn test_global(cx: &mut MutableAppContext) {
5287        type Global = usize;
5288
5289        let observation_count = Rc::new(RefCell::new(0));
5290        let subscription = cx.observe_global::<Global, _>({
5291            let observation_count = observation_count.clone();
5292            move |_, _| {
5293                *observation_count.borrow_mut() += 1;
5294            }
5295        });
5296
5297        assert!(!cx.has_global::<Global>());
5298        assert_eq!(cx.default_global::<Global>(), &0);
5299        assert_eq!(*observation_count.borrow(), 1);
5300        assert!(cx.has_global::<Global>());
5301        assert_eq!(
5302            cx.update_global::<Global, _, _>(|global, _| {
5303                *global = 1;
5304                "Update Result"
5305            }),
5306            "Update Result"
5307        );
5308        assert_eq!(*observation_count.borrow(), 2);
5309        assert_eq!(cx.global::<Global>(), &1);
5310
5311        drop(subscription);
5312        cx.update_global::<Global, _, _>(|global, _| {
5313            *global = 2;
5314        });
5315        assert_eq!(*observation_count.borrow(), 2);
5316
5317        type OtherGlobal = f32;
5318
5319        let observation_count = Rc::new(RefCell::new(0));
5320        cx.observe_global::<OtherGlobal, _>({
5321            let observation_count = observation_count.clone();
5322            move |_, _| {
5323                *observation_count.borrow_mut() += 1;
5324            }
5325        })
5326        .detach();
5327
5328        assert_eq!(
5329            cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
5330                assert_eq!(global, &0.0);
5331                *global = 2.0;
5332                "Default update result"
5333            }),
5334            "Default update result"
5335        );
5336        assert_eq!(cx.global::<OtherGlobal>(), &2.0);
5337        assert_eq!(*observation_count.borrow(), 1);
5338    }
5339
5340    #[crate::test(self)]
5341    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
5342        struct View;
5343
5344        impl Entity for View {
5345            type Event = ();
5346        }
5347
5348        impl super::View for View {
5349            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5350                Empty::new().boxed()
5351            }
5352
5353            fn ui_name() -> &'static str {
5354                "View"
5355            }
5356        }
5357
5358        struct Model;
5359
5360        impl Entity for Model {
5361            type Event = ();
5362        }
5363
5364        let (window_id, _) = cx.add_window(Default::default(), |_| View);
5365        let observing_view = cx.add_view(window_id, |_| View);
5366        let emitting_view = cx.add_view(window_id, |_| View);
5367        let observing_model = cx.add_model(|_| Model);
5368        let observed_model = cx.add_model(|_| Model);
5369
5370        observing_view.update(cx, |_, cx| {
5371            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
5372            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5373        });
5374        observing_model.update(cx, |_, cx| {
5375            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5376        });
5377
5378        cx.update(|_| {
5379            drop(observing_view);
5380            drop(observing_model);
5381        });
5382
5383        emitting_view.update(cx, |_, cx| cx.emit(()));
5384        observed_model.update(cx, |_, cx| cx.emit(()));
5385    }
5386
5387    #[crate::test(self)]
5388    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
5389        #[derive(Default)]
5390        struct TestView;
5391
5392        impl Entity for TestView {
5393            type Event = ();
5394        }
5395
5396        impl View for TestView {
5397            fn ui_name() -> &'static str {
5398                "TestView"
5399            }
5400
5401            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5402                Empty::new().boxed()
5403            }
5404        }
5405
5406        let events = Rc::new(RefCell::new(Vec::new()));
5407        cx.add_window(Default::default(), |cx| {
5408            drop(cx.subscribe(&cx.handle(), {
5409                let events = events.clone();
5410                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
5411            }));
5412            cx.subscribe(&cx.handle(), {
5413                let events = events.clone();
5414                move |_, _, _, _| events.borrow_mut().push("before emit")
5415            })
5416            .detach();
5417            cx.emit(());
5418            cx.subscribe(&cx.handle(), {
5419                let events = events.clone();
5420                move |_, _, _, _| events.borrow_mut().push("after emit")
5421            })
5422            .detach();
5423            TestView
5424        });
5425        assert_eq!(*events.borrow(), ["before emit"]);
5426    }
5427
5428    #[crate::test(self)]
5429    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
5430        #[derive(Default)]
5431        struct View {
5432            events: Vec<usize>,
5433        }
5434
5435        impl Entity for View {
5436            type Event = usize;
5437        }
5438
5439        impl super::View for View {
5440            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5441                Empty::new().boxed()
5442            }
5443
5444            fn ui_name() -> &'static str {
5445                "View"
5446            }
5447        }
5448
5449        #[derive(Default)]
5450        struct Model {
5451            count: usize,
5452        }
5453
5454        impl Entity for Model {
5455            type Event = ();
5456        }
5457
5458        let (_, view) = cx.add_window(Default::default(), |_| View::default());
5459        let model = cx.add_model(|_| Model::default());
5460
5461        view.update(cx, |_, c| {
5462            c.observe(&model, |me, observed, c| {
5463                me.events.push(observed.read(c).count)
5464            })
5465            .detach();
5466        });
5467
5468        model.update(cx, |model, c| {
5469            model.count = 11;
5470            c.notify();
5471        });
5472        assert_eq!(view.read(cx).events, vec![11]);
5473    }
5474
5475    #[crate::test(self)]
5476    fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
5477        #[derive(Default)]
5478        struct TestView;
5479
5480        impl Entity for TestView {
5481            type Event = ();
5482        }
5483
5484        impl View for TestView {
5485            fn ui_name() -> &'static str {
5486                "TestView"
5487            }
5488
5489            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5490                Empty::new().boxed()
5491            }
5492        }
5493
5494        let events = Rc::new(RefCell::new(Vec::new()));
5495        cx.add_window(Default::default(), |cx| {
5496            drop(cx.observe(&cx.handle(), {
5497                let events = events.clone();
5498                move |_, _, _| events.borrow_mut().push("dropped before flush")
5499            }));
5500            cx.observe(&cx.handle(), {
5501                let events = events.clone();
5502                move |_, _, _| events.borrow_mut().push("before notify")
5503            })
5504            .detach();
5505            cx.notify();
5506            cx.observe(&cx.handle(), {
5507                let events = events.clone();
5508                move |_, _, _| events.borrow_mut().push("after notify")
5509            })
5510            .detach();
5511            TestView
5512        });
5513        assert_eq!(*events.borrow(), ["before notify"]);
5514    }
5515
5516    #[crate::test(self)]
5517    fn test_dropping_observers(cx: &mut MutableAppContext) {
5518        struct View;
5519
5520        impl Entity for View {
5521            type Event = ();
5522        }
5523
5524        impl super::View for View {
5525            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5526                Empty::new().boxed()
5527            }
5528
5529            fn ui_name() -> &'static str {
5530                "View"
5531            }
5532        }
5533
5534        struct Model;
5535
5536        impl Entity for Model {
5537            type Event = ();
5538        }
5539
5540        let (window_id, _) = cx.add_window(Default::default(), |_| View);
5541        let observing_view = cx.add_view(window_id, |_| View);
5542        let observing_model = cx.add_model(|_| Model);
5543        let observed_model = cx.add_model(|_| Model);
5544
5545        observing_view.update(cx, |_, cx| {
5546            cx.observe(&observed_model, |_, _, _| {}).detach();
5547        });
5548        observing_model.update(cx, |_, cx| {
5549            cx.observe(&observed_model, |_, _, _| {}).detach();
5550        });
5551
5552        cx.update(|_| {
5553            drop(observing_view);
5554            drop(observing_model);
5555        });
5556
5557        observed_model.update(cx, |_, cx| cx.notify());
5558    }
5559
5560    #[crate::test(self)]
5561    fn test_dropping_subscriptions_during_callback(cx: &mut MutableAppContext) {
5562        struct Model;
5563
5564        impl Entity for Model {
5565            type Event = u64;
5566        }
5567
5568        // Events
5569        let observing_model = cx.add_model(|_| Model);
5570        let observed_model = cx.add_model(|_| Model);
5571
5572        let events = Rc::new(RefCell::new(Vec::new()));
5573
5574        observing_model.update(cx, |_, cx| {
5575            let events = events.clone();
5576            let subscription = Rc::new(RefCell::new(None));
5577            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
5578                let subscription = subscription.clone();
5579                move |_, _, e, _| {
5580                    subscription.borrow_mut().take();
5581                    events.borrow_mut().push(e.clone());
5582                }
5583            }));
5584        });
5585
5586        observed_model.update(cx, |_, cx| {
5587            cx.emit(1);
5588            cx.emit(2);
5589        });
5590
5591        assert_eq!(*events.borrow(), [1]);
5592
5593        // Global Events
5594        #[derive(Clone, Debug, Eq, PartialEq)]
5595        struct GlobalEvent(u64);
5596
5597        let events = Rc::new(RefCell::new(Vec::new()));
5598
5599        {
5600            let events = events.clone();
5601            let subscription = Rc::new(RefCell::new(None));
5602            *subscription.borrow_mut() = Some(cx.subscribe_global({
5603                let subscription = subscription.clone();
5604                move |e: &GlobalEvent, _| {
5605                    subscription.borrow_mut().take();
5606                    events.borrow_mut().push(e.clone());
5607                }
5608            }));
5609        }
5610
5611        cx.update(|cx| {
5612            cx.emit_global(GlobalEvent(1));
5613            cx.emit_global(GlobalEvent(2));
5614        });
5615
5616        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
5617
5618        // Model Observation
5619        let observing_model = cx.add_model(|_| Model);
5620        let observed_model = cx.add_model(|_| Model);
5621
5622        let observation_count = Rc::new(RefCell::new(0));
5623
5624        observing_model.update(cx, |_, cx| {
5625            let observation_count = observation_count.clone();
5626            let subscription = Rc::new(RefCell::new(None));
5627            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
5628                let subscription = subscription.clone();
5629                move |_, _, _| {
5630                    subscription.borrow_mut().take();
5631                    *observation_count.borrow_mut() += 1;
5632                }
5633            }));
5634        });
5635
5636        observed_model.update(cx, |_, cx| {
5637            cx.notify();
5638        });
5639
5640        observed_model.update(cx, |_, cx| {
5641            cx.notify();
5642        });
5643
5644        assert_eq!(*observation_count.borrow(), 1);
5645
5646        // View Observation
5647        struct View;
5648
5649        impl Entity for View {
5650            type Event = ();
5651        }
5652
5653        impl super::View for View {
5654            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5655                Empty::new().boxed()
5656            }
5657
5658            fn ui_name() -> &'static str {
5659                "View"
5660            }
5661        }
5662
5663        let (window_id, _) = cx.add_window(Default::default(), |_| View);
5664        let observing_view = cx.add_view(window_id, |_| View);
5665        let observed_view = cx.add_view(window_id, |_| View);
5666
5667        let observation_count = Rc::new(RefCell::new(0));
5668        observing_view.update(cx, |_, cx| {
5669            let observation_count = observation_count.clone();
5670            let subscription = Rc::new(RefCell::new(None));
5671            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
5672                let subscription = subscription.clone();
5673                move |_, _, _| {
5674                    subscription.borrow_mut().take();
5675                    *observation_count.borrow_mut() += 1;
5676                }
5677            }));
5678        });
5679
5680        observed_view.update(cx, |_, cx| {
5681            cx.notify();
5682        });
5683
5684        observed_view.update(cx, |_, cx| {
5685            cx.notify();
5686        });
5687
5688        assert_eq!(*observation_count.borrow(), 1);
5689
5690        // Global Observation
5691        let observation_count = Rc::new(RefCell::new(0));
5692        let subscription = Rc::new(RefCell::new(None));
5693        *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
5694            let observation_count = observation_count.clone();
5695            let subscription = subscription.clone();
5696            move |_, _| {
5697                subscription.borrow_mut().take();
5698                *observation_count.borrow_mut() += 1;
5699            }
5700        }));
5701
5702        cx.default_global::<()>();
5703        cx.set_global(());
5704        assert_eq!(*observation_count.borrow(), 1);
5705    }
5706
5707    #[crate::test(self)]
5708    fn test_focus(cx: &mut MutableAppContext) {
5709        struct View {
5710            name: String,
5711            events: Arc<Mutex<Vec<String>>>,
5712        }
5713
5714        impl Entity for View {
5715            type Event = ();
5716        }
5717
5718        impl super::View for View {
5719            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5720                Empty::new().boxed()
5721            }
5722
5723            fn ui_name() -> &'static str {
5724                "View"
5725            }
5726
5727            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
5728                self.events.lock().push(format!("{} focused", &self.name));
5729            }
5730
5731            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
5732                self.events.lock().push(format!("{} blurred", &self.name));
5733            }
5734        }
5735
5736        let events: Arc<Mutex<Vec<String>>> = Default::default();
5737        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
5738            events: events.clone(),
5739            name: "view 1".to_string(),
5740        });
5741        let view_2 = cx.add_view(window_id, |_| View {
5742            events: events.clone(),
5743            name: "view 2".to_string(),
5744        });
5745
5746        view_1.update(cx, |_, cx| cx.focus(&view_2));
5747        view_1.update(cx, |_, cx| cx.focus(&view_1));
5748        view_1.update(cx, |_, cx| cx.focus(&view_2));
5749        view_1.update(cx, |_, _| drop(view_2));
5750
5751        assert_eq!(
5752            *events.lock(),
5753            [
5754                "view 1 focused".to_string(),
5755                "view 1 blurred".to_string(),
5756                "view 2 focused".to_string(),
5757                "view 2 blurred".to_string(),
5758                "view 1 focused".to_string(),
5759                "view 1 blurred".to_string(),
5760                "view 2 focused".to_string(),
5761                "view 1 focused".to_string(),
5762            ],
5763        );
5764    }
5765
5766    #[crate::test(self)]
5767    fn test_dispatch_action(cx: &mut MutableAppContext) {
5768        struct ViewA {
5769            id: usize,
5770        }
5771
5772        impl Entity for ViewA {
5773            type Event = ();
5774        }
5775
5776        impl View for ViewA {
5777            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5778                Empty::new().boxed()
5779            }
5780
5781            fn ui_name() -> &'static str {
5782                "View"
5783            }
5784        }
5785
5786        struct ViewB {
5787            id: usize,
5788        }
5789
5790        impl Entity for ViewB {
5791            type Event = ();
5792        }
5793
5794        impl View for ViewB {
5795            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5796                Empty::new().boxed()
5797            }
5798
5799            fn ui_name() -> &'static str {
5800                "View"
5801            }
5802        }
5803
5804        action!(Action, &'static str);
5805
5806        let actions = Rc::new(RefCell::new(Vec::new()));
5807
5808        {
5809            let actions = actions.clone();
5810            cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
5811                actions.borrow_mut().push("global".to_string());
5812            });
5813        }
5814
5815        {
5816            let actions = actions.clone();
5817            cx.add_action(move |view: &mut ViewA, action: &Action, cx| {
5818                assert_eq!(action.0, "bar");
5819                cx.propagate_action();
5820                actions.borrow_mut().push(format!("{} a", view.id));
5821            });
5822        }
5823
5824        {
5825            let actions = actions.clone();
5826            cx.add_action(move |view: &mut ViewA, _: &Action, cx| {
5827                if view.id != 1 {
5828                    cx.add_view(|cx| {
5829                        cx.propagate_action(); // Still works on a nested ViewContext
5830                        ViewB { id: 5 }
5831                    });
5832                }
5833                actions.borrow_mut().push(format!("{} b", view.id));
5834            });
5835        }
5836
5837        {
5838            let actions = actions.clone();
5839            cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
5840                cx.propagate_action();
5841                actions.borrow_mut().push(format!("{} c", view.id));
5842            });
5843        }
5844
5845        {
5846            let actions = actions.clone();
5847            cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
5848                cx.propagate_action();
5849                actions.borrow_mut().push(format!("{} d", view.id));
5850            });
5851        }
5852
5853        {
5854            let actions = actions.clone();
5855            cx.capture_action(move |view: &mut ViewA, _: &Action, cx| {
5856                cx.propagate_action();
5857                actions.borrow_mut().push(format!("{} capture", view.id));
5858            });
5859        }
5860
5861        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
5862        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
5863        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
5864        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
5865
5866        cx.dispatch_action(
5867            window_id,
5868            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
5869            &Action("bar"),
5870        );
5871
5872        assert_eq!(
5873            *actions.borrow(),
5874            vec![
5875                "1 capture",
5876                "3 capture",
5877                "4 d",
5878                "4 c",
5879                "3 b",
5880                "3 a",
5881                "2 d",
5882                "2 c",
5883                "1 b"
5884            ]
5885        );
5886
5887        // Remove view_1, which doesn't propagate the action
5888        actions.borrow_mut().clear();
5889        cx.dispatch_action(
5890            window_id,
5891            vec![view_2.id(), view_3.id(), view_4.id()],
5892            &Action("bar"),
5893        );
5894
5895        assert_eq!(
5896            *actions.borrow(),
5897            vec![
5898                "3 capture",
5899                "4 d",
5900                "4 c",
5901                "3 b",
5902                "3 a",
5903                "2 d",
5904                "2 c",
5905                "global"
5906            ]
5907        );
5908    }
5909
5910    #[crate::test(self)]
5911    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
5912        action!(Action, &'static str);
5913
5914        struct View {
5915            id: usize,
5916            keymap_context: keymap::Context,
5917        }
5918
5919        impl Entity for View {
5920            type Event = ();
5921        }
5922
5923        impl super::View for View {
5924            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5925                Empty::new().boxed()
5926            }
5927
5928            fn ui_name() -> &'static str {
5929                "View"
5930            }
5931
5932            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
5933                self.keymap_context.clone()
5934            }
5935        }
5936
5937        impl View {
5938            fn new(id: usize) -> Self {
5939                View {
5940                    id,
5941                    keymap_context: keymap::Context::default(),
5942                }
5943            }
5944        }
5945
5946        let mut view_1 = View::new(1);
5947        let mut view_2 = View::new(2);
5948        let mut view_3 = View::new(3);
5949        view_1.keymap_context.set.insert("a".into());
5950        view_2.keymap_context.set.insert("a".into());
5951        view_2.keymap_context.set.insert("b".into());
5952        view_3.keymap_context.set.insert("a".into());
5953        view_3.keymap_context.set.insert("b".into());
5954        view_3.keymap_context.set.insert("c".into());
5955
5956        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
5957        let view_2 = cx.add_view(window_id, |_| view_2);
5958        let view_3 = cx.add_view(window_id, |_| view_3);
5959
5960        // This keymap's only binding dispatches an action on view 2 because that view will have
5961        // "a" and "b" in its context, but not "c".
5962        cx.add_bindings(vec![keymap::Binding::new(
5963            "a",
5964            Action("a"),
5965            Some("a && b && !c"),
5966        )]);
5967
5968        cx.add_bindings(vec![keymap::Binding::new("b", Action("b"), None)]);
5969
5970        let actions = Rc::new(RefCell::new(Vec::new()));
5971        {
5972            let actions = actions.clone();
5973            cx.add_action(move |view: &mut View, action: &Action, cx| {
5974                if action.0 == "a" {
5975                    actions.borrow_mut().push(format!("{} a", view.id));
5976                } else {
5977                    actions
5978                        .borrow_mut()
5979                        .push(format!("{} {}", view.id, action.0));
5980                    cx.propagate_action();
5981                }
5982            });
5983        }
5984        {
5985            let actions = actions.clone();
5986            cx.add_global_action(move |action: &Action, _| {
5987                actions.borrow_mut().push(format!("global {}", action.0));
5988            });
5989        }
5990
5991        cx.dispatch_keystroke(
5992            window_id,
5993            vec![view_1.id(), view_2.id(), view_3.id()],
5994            &Keystroke::parse("a").unwrap(),
5995        );
5996
5997        assert_eq!(&*actions.borrow(), &["2 a"]);
5998
5999        actions.borrow_mut().clear();
6000        cx.dispatch_keystroke(
6001            window_id,
6002            vec![view_1.id(), view_2.id(), view_3.id()],
6003            &Keystroke::parse("b").unwrap(),
6004        );
6005
6006        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
6007    }
6008
6009    #[crate::test(self)]
6010    async fn test_model_condition(cx: &mut TestAppContext) {
6011        struct Counter(usize);
6012
6013        impl super::Entity for Counter {
6014            type Event = ();
6015        }
6016
6017        impl Counter {
6018            fn inc(&mut self, cx: &mut ModelContext<Self>) {
6019                self.0 += 1;
6020                cx.notify();
6021            }
6022        }
6023
6024        let model = cx.add_model(|_| Counter(0));
6025
6026        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
6027        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
6028        smol::pin!(condition1, condition2);
6029
6030        model.update(cx, |model, cx| model.inc(cx));
6031        assert_eq!(poll_once(&mut condition1).await, None);
6032        assert_eq!(poll_once(&mut condition2).await, None);
6033
6034        model.update(cx, |model, cx| model.inc(cx));
6035        assert_eq!(poll_once(&mut condition1).await, Some(()));
6036        assert_eq!(poll_once(&mut condition2).await, None);
6037
6038        model.update(cx, |model, cx| model.inc(cx));
6039        assert_eq!(poll_once(&mut condition2).await, Some(()));
6040
6041        model.update(cx, |_, cx| cx.notify());
6042    }
6043
6044    #[crate::test(self)]
6045    #[should_panic]
6046    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
6047        struct Model;
6048
6049        impl super::Entity for Model {
6050            type Event = ();
6051        }
6052
6053        let model = cx.add_model(|_| Model);
6054        model.condition(&cx, |_, _| false).await;
6055    }
6056
6057    #[crate::test(self)]
6058    #[should_panic(expected = "model dropped with pending condition")]
6059    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
6060        struct Model;
6061
6062        impl super::Entity for Model {
6063            type Event = ();
6064        }
6065
6066        let model = cx.add_model(|_| Model);
6067        let condition = model.condition(&cx, |_, _| false);
6068        cx.update(|_| drop(model));
6069        condition.await;
6070    }
6071
6072    #[crate::test(self)]
6073    async fn test_view_condition(cx: &mut TestAppContext) {
6074        struct Counter(usize);
6075
6076        impl super::Entity for Counter {
6077            type Event = ();
6078        }
6079
6080        impl super::View for Counter {
6081            fn ui_name() -> &'static str {
6082                "test view"
6083            }
6084
6085            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6086                Empty::new().boxed()
6087            }
6088        }
6089
6090        impl Counter {
6091            fn inc(&mut self, cx: &mut ViewContext<Self>) {
6092                self.0 += 1;
6093                cx.notify();
6094            }
6095        }
6096
6097        let (_, view) = cx.add_window(|_| Counter(0));
6098
6099        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
6100        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
6101        smol::pin!(condition1, condition2);
6102
6103        view.update(cx, |view, cx| view.inc(cx));
6104        assert_eq!(poll_once(&mut condition1).await, None);
6105        assert_eq!(poll_once(&mut condition2).await, None);
6106
6107        view.update(cx, |view, cx| view.inc(cx));
6108        assert_eq!(poll_once(&mut condition1).await, Some(()));
6109        assert_eq!(poll_once(&mut condition2).await, None);
6110
6111        view.update(cx, |view, cx| view.inc(cx));
6112        assert_eq!(poll_once(&mut condition2).await, Some(()));
6113        view.update(cx, |_, cx| cx.notify());
6114    }
6115
6116    #[crate::test(self)]
6117    #[should_panic]
6118    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
6119        struct View;
6120
6121        impl super::Entity for View {
6122            type Event = ();
6123        }
6124
6125        impl super::View for View {
6126            fn ui_name() -> &'static str {
6127                "test view"
6128            }
6129
6130            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6131                Empty::new().boxed()
6132            }
6133        }
6134
6135        let (_, view) = cx.add_window(|_| View);
6136        view.condition(&cx, |_, _| false).await;
6137    }
6138
6139    #[crate::test(self)]
6140    #[should_panic(expected = "view dropped with pending condition")]
6141    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
6142        struct View;
6143
6144        impl super::Entity for View {
6145            type Event = ();
6146        }
6147
6148        impl super::View for View {
6149            fn ui_name() -> &'static str {
6150                "test view"
6151            }
6152
6153            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6154                Empty::new().boxed()
6155            }
6156        }
6157
6158        let window_id = cx.add_window(|_| View).0;
6159        let view = cx.add_view(window_id, |_| View);
6160
6161        let condition = view.condition(&cx, |_, _| false);
6162        cx.update(|_| drop(view));
6163        condition.await;
6164    }
6165
6166    #[crate::test(self)]
6167    fn test_refresh_windows(cx: &mut MutableAppContext) {
6168        struct View(usize);
6169
6170        impl super::Entity for View {
6171            type Event = ();
6172        }
6173
6174        impl super::View for View {
6175            fn ui_name() -> &'static str {
6176                "test view"
6177            }
6178
6179            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6180                Empty::new().named(format!("render count: {}", post_inc(&mut self.0)))
6181            }
6182        }
6183
6184        let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
6185        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
6186
6187        assert_eq!(
6188            presenter.borrow().rendered_views[&root_view.id()].name(),
6189            Some("render count: 0")
6190        );
6191
6192        let view = cx.add_view(window_id, |cx| {
6193            cx.refresh_windows();
6194            View(0)
6195        });
6196
6197        assert_eq!(
6198            presenter.borrow().rendered_views[&root_view.id()].name(),
6199            Some("render count: 1")
6200        );
6201        assert_eq!(
6202            presenter.borrow().rendered_views[&view.id()].name(),
6203            Some("render count: 0")
6204        );
6205
6206        cx.update(|cx| cx.refresh_windows());
6207        assert_eq!(
6208            presenter.borrow().rendered_views[&root_view.id()].name(),
6209            Some("render count: 2")
6210        );
6211        assert_eq!(
6212            presenter.borrow().rendered_views[&view.id()].name(),
6213            Some("render count: 1")
6214        );
6215
6216        cx.update(|cx| {
6217            cx.refresh_windows();
6218            drop(view);
6219        });
6220        assert_eq!(
6221            presenter.borrow().rendered_views[&root_view.id()].name(),
6222            Some("render count: 3")
6223        );
6224        assert_eq!(presenter.borrow().rendered_views.len(), 1);
6225    }
6226}