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, timeout},
   8    AssetCache, AssetSource, ClipboardItem, FontCache, PathPromptOptions, TextLayoutCache,
   9};
  10use anyhow::{anyhow, Result};
  11use keymap::MatchResult;
  12use parking_lot::Mutex;
  13use platform::Event;
  14use postage::{mpsc, oneshot, sink::Sink as _, stream::Stream as _};
  15use smol::prelude::*;
  16use std::{
  17    any::{type_name, Any, TypeId},
  18    cell::RefCell,
  19    collections::{hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque},
  20    fmt::{self, Debug},
  21    hash::{Hash, Hasher},
  22    marker::PhantomData,
  23    mem,
  24    ops::{Deref, DerefMut},
  25    path::{Path, PathBuf},
  26    pin::Pin,
  27    rc::{self, Rc},
  28    sync::{
  29        atomic::{AtomicUsize, Ordering::SeqCst},
  30        Arc, Weak,
  31    },
  32    time::Duration,
  33};
  34
  35pub trait Entity: 'static {
  36    type Event;
  37
  38    fn release(&mut self, _: &mut MutableAppContext) {}
  39    fn app_will_quit(
  40        &mut self,
  41        _: &mut MutableAppContext,
  42    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
  43        None
  44    }
  45}
  46
  47pub trait View: Entity + Sized {
  48    fn ui_name() -> &'static str;
  49    fn render(&mut self, cx: &mut RenderContext<'_, Self>) -> ElementBox;
  50    fn on_focus(&mut self, _: &mut ViewContext<Self>) {}
  51    fn on_blur(&mut self, _: &mut ViewContext<Self>) {}
  52    fn keymap_context(&self, _: &AppContext) -> keymap::Context {
  53        Self::default_keymap_context()
  54    }
  55    fn default_keymap_context() -> keymap::Context {
  56        let mut cx = keymap::Context::default();
  57        cx.set.insert(Self::ui_name().into());
  58        cx
  59    }
  60}
  61
  62pub trait ReadModel {
  63    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T;
  64}
  65
  66pub trait ReadModelWith {
  67    fn read_model_with<E: Entity, T>(
  68        &self,
  69        handle: &ModelHandle<E>,
  70        read: &mut dyn FnMut(&E, &AppContext) -> T,
  71    ) -> T;
  72}
  73
  74pub trait UpdateModel {
  75    fn update_model<T: Entity, O>(
  76        &mut self,
  77        handle: &ModelHandle<T>,
  78        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
  79    ) -> O;
  80}
  81
  82pub trait UpgradeModelHandle {
  83    fn upgrade_model_handle<T: Entity>(
  84        &self,
  85        handle: &WeakModelHandle<T>,
  86    ) -> Option<ModelHandle<T>>;
  87}
  88
  89pub trait UpgradeViewHandle {
  90    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>>;
  91}
  92
  93pub trait ReadView {
  94    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T;
  95}
  96
  97pub trait ReadViewWith {
  98    fn read_view_with<V, T>(
  99        &self,
 100        handle: &ViewHandle<V>,
 101        read: &mut dyn FnMut(&V, &AppContext) -> T,
 102    ) -> T
 103    where
 104        V: View;
 105}
 106
 107pub trait UpdateView {
 108    fn update_view<T, S>(
 109        &mut self,
 110        handle: &ViewHandle<T>,
 111        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 112    ) -> S
 113    where
 114        T: View;
 115}
 116
 117pub trait Action: 'static + AnyAction {
 118    type Argument: 'static + Clone;
 119}
 120
 121pub trait AnyAction {
 122    fn id(&self) -> TypeId;
 123    fn name(&self) -> &'static str;
 124    fn as_any(&self) -> &dyn Any;
 125    fn boxed_clone(&self) -> Box<dyn AnyAction>;
 126    fn boxed_clone_as_any(&self) -> Box<dyn Any>;
 127}
 128
 129#[macro_export]
 130macro_rules! action {
 131    ($name:ident, $arg:ty) => {
 132        #[derive(Clone)]
 133        pub struct $name(pub $arg);
 134
 135        impl $crate::Action for $name {
 136            type Argument = $arg;
 137        }
 138
 139        impl $crate::AnyAction for $name {
 140            fn id(&self) -> std::any::TypeId {
 141                std::any::TypeId::of::<$name>()
 142            }
 143
 144            fn name(&self) -> &'static str {
 145                stringify!($name)
 146            }
 147
 148            fn as_any(&self) -> &dyn std::any::Any {
 149                self
 150            }
 151
 152            fn boxed_clone(&self) -> Box<dyn $crate::AnyAction> {
 153                Box::new(self.clone())
 154            }
 155
 156            fn boxed_clone_as_any(&self) -> Box<dyn std::any::Any> {
 157                Box::new(self.clone())
 158            }
 159        }
 160    };
 161
 162    ($name:ident) => {
 163        #[derive(Clone, Debug, Eq, PartialEq)]
 164        pub struct $name;
 165
 166        impl $crate::Action for $name {
 167            type Argument = ();
 168        }
 169
 170        impl $crate::AnyAction for $name {
 171            fn id(&self) -> std::any::TypeId {
 172                std::any::TypeId::of::<$name>()
 173            }
 174
 175            fn name(&self) -> &'static str {
 176                stringify!($name)
 177            }
 178
 179            fn as_any(&self) -> &dyn std::any::Any {
 180                self
 181            }
 182
 183            fn boxed_clone(&self) -> Box<dyn $crate::AnyAction> {
 184                Box::new(self.clone())
 185            }
 186
 187            fn boxed_clone_as_any(&self) -> Box<dyn std::any::Any> {
 188                Box::new(self.clone())
 189            }
 190        }
 191    };
 192}
 193
 194pub struct Menu<'a> {
 195    pub name: &'a str,
 196    pub items: Vec<MenuItem<'a>>,
 197}
 198
 199pub enum MenuItem<'a> {
 200    Action {
 201        name: &'a str,
 202        keystroke: Option<&'a str>,
 203        action: Box<dyn AnyAction>,
 204    },
 205    Separator,
 206}
 207
 208#[derive(Clone)]
 209pub struct App(Rc<RefCell<MutableAppContext>>);
 210
 211#[derive(Clone)]
 212pub struct AsyncAppContext(Rc<RefCell<MutableAppContext>>);
 213
 214#[derive(Clone)]
 215pub struct TestAppContext {
 216    cx: Rc<RefCell<MutableAppContext>>,
 217    foreground_platform: Rc<platform::test::ForegroundPlatform>,
 218}
 219
 220impl App {
 221    pub fn new(asset_source: impl AssetSource) -> Result<Self> {
 222        let platform = platform::current::platform();
 223        let foreground_platform = platform::current::foreground_platform();
 224        let foreground = Rc::new(executor::Foreground::platform(platform.dispatcher())?);
 225        let app = Self(Rc::new(RefCell::new(MutableAppContext::new(
 226            foreground,
 227            Arc::new(executor::Background::new()),
 228            platform.clone(),
 229            foreground_platform.clone(),
 230            Arc::new(FontCache::new(platform.fonts())),
 231            asset_source,
 232        ))));
 233
 234        foreground_platform.on_quit(Box::new({
 235            let cx = app.0.clone();
 236            move || {
 237                cx.borrow_mut().quit();
 238            }
 239        }));
 240        foreground_platform.on_menu_command(Box::new({
 241            let cx = app.0.clone();
 242            move |action| {
 243                let mut cx = cx.borrow_mut();
 244                if let Some(key_window_id) = cx.cx.platform.key_window_id() {
 245                    if let Some((presenter, _)) =
 246                        cx.presenters_and_platform_windows.get(&key_window_id)
 247                    {
 248                        let presenter = presenter.clone();
 249                        let path = presenter.borrow().dispatch_path(cx.as_ref());
 250                        cx.dispatch_action_any(key_window_id, &path, action);
 251                    } else {
 252                        cx.dispatch_global_action_any(action);
 253                    }
 254                } else {
 255                    cx.dispatch_global_action_any(action);
 256                }
 257            }
 258        }));
 259
 260        app.0.borrow_mut().weak_self = Some(Rc::downgrade(&app.0));
 261        Ok(app)
 262    }
 263
 264    pub fn on_become_active<F>(self, mut callback: F) -> Self
 265    where
 266        F: 'static + FnMut(&mut MutableAppContext),
 267    {
 268        let cx = self.0.clone();
 269        self.0
 270            .borrow_mut()
 271            .foreground_platform
 272            .on_become_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 273        self
 274    }
 275
 276    pub fn on_resign_active<F>(self, mut callback: F) -> Self
 277    where
 278        F: 'static + FnMut(&mut MutableAppContext),
 279    {
 280        let cx = self.0.clone();
 281        self.0
 282            .borrow_mut()
 283            .foreground_platform
 284            .on_resign_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 285        self
 286    }
 287
 288    pub fn on_quit<F>(self, mut callback: F) -> Self
 289    where
 290        F: 'static + FnMut(&mut MutableAppContext),
 291    {
 292        let cx = self.0.clone();
 293        self.0
 294            .borrow_mut()
 295            .foreground_platform
 296            .on_quit(Box::new(move || callback(&mut *cx.borrow_mut())));
 297        self
 298    }
 299
 300    pub fn on_event<F>(self, mut callback: F) -> Self
 301    where
 302        F: 'static + FnMut(Event, &mut MutableAppContext) -> bool,
 303    {
 304        let cx = self.0.clone();
 305        self.0
 306            .borrow_mut()
 307            .foreground_platform
 308            .on_event(Box::new(move |event| {
 309                callback(event, &mut *cx.borrow_mut())
 310            }));
 311        self
 312    }
 313
 314    pub fn on_open_files<F>(self, mut callback: F) -> Self
 315    where
 316        F: 'static + FnMut(Vec<PathBuf>, &mut MutableAppContext),
 317    {
 318        let cx = self.0.clone();
 319        self.0
 320            .borrow_mut()
 321            .foreground_platform
 322            .on_open_files(Box::new(move |paths| {
 323                callback(paths, &mut *cx.borrow_mut())
 324            }));
 325        self
 326    }
 327
 328    pub fn run<F>(self, on_finish_launching: F)
 329    where
 330        F: 'static + FnOnce(&mut MutableAppContext),
 331    {
 332        let platform = self.0.borrow().foreground_platform.clone();
 333        platform.run(Box::new(move || {
 334            let mut cx = self.0.borrow_mut();
 335            let cx = &mut *cx;
 336            crate::views::init(cx);
 337            on_finish_launching(cx);
 338        }))
 339    }
 340
 341    pub fn platform(&self) -> Arc<dyn Platform> {
 342        self.0.borrow().platform()
 343    }
 344
 345    pub fn font_cache(&self) -> Arc<FontCache> {
 346        self.0.borrow().cx.font_cache.clone()
 347    }
 348
 349    fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 350        let mut state = self.0.borrow_mut();
 351        let result = state.update(callback);
 352        state.pending_notifications.clear();
 353        result
 354    }
 355}
 356
 357impl TestAppContext {
 358    pub fn new(
 359        foreground_platform: Rc<platform::test::ForegroundPlatform>,
 360        platform: Arc<dyn Platform>,
 361        foreground: Rc<executor::Foreground>,
 362        background: Arc<executor::Background>,
 363        font_cache: Arc<FontCache>,
 364        first_entity_id: usize,
 365    ) -> Self {
 366        let mut cx = MutableAppContext::new(
 367            foreground.clone(),
 368            background,
 369            platform,
 370            foreground_platform.clone(),
 371            font_cache,
 372            (),
 373        );
 374        cx.next_entity_id = first_entity_id;
 375        let cx = TestAppContext {
 376            cx: Rc::new(RefCell::new(cx)),
 377            foreground_platform,
 378        };
 379        cx.cx.borrow_mut().weak_self = Some(Rc::downgrade(&cx.cx));
 380        cx
 381    }
 382
 383    pub fn dispatch_action<A: Action>(
 384        &self,
 385        window_id: usize,
 386        responder_chain: Vec<usize>,
 387        action: A,
 388    ) {
 389        self.cx
 390            .borrow_mut()
 391            .dispatch_action_any(window_id, &responder_chain, &action);
 392    }
 393
 394    pub fn dispatch_global_action<A: Action>(&self, action: A) {
 395        self.cx.borrow_mut().dispatch_global_action(action);
 396    }
 397
 398    pub fn dispatch_keystroke(
 399        &self,
 400        window_id: usize,
 401        responder_chain: Vec<usize>,
 402        keystroke: &Keystroke,
 403    ) -> Result<bool> {
 404        let mut state = self.cx.borrow_mut();
 405        state.dispatch_keystroke(window_id, responder_chain, keystroke)
 406    }
 407
 408    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 409    where
 410        T: Entity,
 411        F: FnOnce(&mut ModelContext<T>) -> T,
 412    {
 413        self.cx.borrow_mut().add_model(build_model)
 414    }
 415
 416    pub fn add_window<T, F>(&mut self, build_root_view: F) -> (usize, ViewHandle<T>)
 417    where
 418        T: View,
 419        F: FnOnce(&mut ViewContext<T>) -> T,
 420    {
 421        self.cx
 422            .borrow_mut()
 423            .add_window(Default::default(), build_root_view)
 424    }
 425
 426    pub fn window_ids(&self) -> Vec<usize> {
 427        self.cx.borrow().window_ids().collect()
 428    }
 429
 430    pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
 431        self.cx.borrow().root_view(window_id)
 432    }
 433
 434    pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
 435    where
 436        T: View,
 437        F: FnOnce(&mut ViewContext<T>) -> T,
 438    {
 439        self.cx.borrow_mut().add_view(window_id, build_view)
 440    }
 441
 442    pub fn add_option_view<T, F>(
 443        &mut self,
 444        window_id: usize,
 445        build_view: F,
 446    ) -> Option<ViewHandle<T>>
 447    where
 448        T: View,
 449        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
 450    {
 451        self.cx.borrow_mut().add_option_view(window_id, build_view)
 452    }
 453
 454    pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
 455        callback(self.cx.borrow().as_ref())
 456    }
 457
 458    pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 459        let mut state = self.cx.borrow_mut();
 460        // Don't increment pending flushes in order to effects to be flushed before the callback
 461        // completes, which is helpful in tests.
 462        let result = callback(&mut *state);
 463        // Flush effects after the callback just in case there are any. This can happen in edge
 464        // cases such as the closure dropping handles.
 465        state.flush_effects();
 466        result
 467    }
 468
 469    pub fn to_async(&self) -> AsyncAppContext {
 470        AsyncAppContext(self.cx.clone())
 471    }
 472
 473    pub fn font_cache(&self) -> Arc<FontCache> {
 474        self.cx.borrow().cx.font_cache.clone()
 475    }
 476
 477    pub fn foreground_platform(&self) -> Rc<platform::test::ForegroundPlatform> {
 478        self.foreground_platform.clone()
 479    }
 480
 481    pub fn platform(&self) -> Arc<dyn platform::Platform> {
 482        self.cx.borrow().cx.platform.clone()
 483    }
 484
 485    pub fn foreground(&self) -> Rc<executor::Foreground> {
 486        self.cx.borrow().foreground().clone()
 487    }
 488
 489    pub fn background(&self) -> Arc<executor::Background> {
 490        self.cx.borrow().background().clone()
 491    }
 492
 493    pub fn simulate_new_path_selection(&self, result: impl FnOnce(PathBuf) -> Option<PathBuf>) {
 494        self.foreground_platform.simulate_new_path_selection(result);
 495    }
 496
 497    pub fn did_prompt_for_new_path(&self) -> bool {
 498        self.foreground_platform.as_ref().did_prompt_for_new_path()
 499    }
 500
 501    pub fn simulate_prompt_answer(&self, window_id: usize, answer: usize) {
 502        let mut state = self.cx.borrow_mut();
 503        let (_, window) = state
 504            .presenters_and_platform_windows
 505            .get_mut(&window_id)
 506            .unwrap();
 507        let test_window = window
 508            .as_any_mut()
 509            .downcast_mut::<platform::test::Window>()
 510            .unwrap();
 511        let mut done_tx = test_window
 512            .last_prompt
 513            .take()
 514            .expect("prompt was not called");
 515        let _ = done_tx.try_send(answer);
 516    }
 517}
 518
 519impl AsyncAppContext {
 520    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
 521    where
 522        F: FnOnce(AsyncAppContext) -> Fut,
 523        Fut: 'static + Future<Output = T>,
 524        T: 'static,
 525    {
 526        self.0.borrow().foreground.spawn(f(self.clone()))
 527    }
 528
 529    pub fn read<T, F: FnOnce(&AppContext) -> T>(&mut self, callback: F) -> T {
 530        callback(self.0.borrow().as_ref())
 531    }
 532
 533    pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 534        self.0.borrow_mut().update(callback)
 535    }
 536
 537    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 538    where
 539        T: Entity,
 540        F: FnOnce(&mut ModelContext<T>) -> T,
 541    {
 542        self.update(|cx| cx.add_model(build_model))
 543    }
 544
 545    pub fn platform(&self) -> Arc<dyn Platform> {
 546        self.0.borrow().platform()
 547    }
 548
 549    pub fn foreground(&self) -> Rc<executor::Foreground> {
 550        self.0.borrow().foreground.clone()
 551    }
 552
 553    pub fn background(&self) -> Arc<executor::Background> {
 554        self.0.borrow().cx.background.clone()
 555    }
 556}
 557
 558impl UpdateModel for AsyncAppContext {
 559    fn update_model<E: Entity, O>(
 560        &mut self,
 561        handle: &ModelHandle<E>,
 562        update: &mut dyn FnMut(&mut E, &mut ModelContext<E>) -> O,
 563    ) -> O {
 564        self.0.borrow_mut().update_model(handle, update)
 565    }
 566}
 567
 568impl UpgradeModelHandle for AsyncAppContext {
 569    fn upgrade_model_handle<T: Entity>(
 570        &self,
 571        handle: &WeakModelHandle<T>,
 572    ) -> Option<ModelHandle<T>> {
 573        self.0.borrow_mut().upgrade_model_handle(handle)
 574    }
 575}
 576
 577impl UpgradeViewHandle for AsyncAppContext {
 578    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
 579        self.0.borrow_mut().upgrade_view_handle(handle)
 580    }
 581}
 582
 583impl ReadModelWith for AsyncAppContext {
 584    fn read_model_with<E: Entity, T>(
 585        &self,
 586        handle: &ModelHandle<E>,
 587        read: &mut dyn FnMut(&E, &AppContext) -> T,
 588    ) -> T {
 589        let cx = self.0.borrow();
 590        let cx = cx.as_ref();
 591        read(handle.read(cx), cx)
 592    }
 593}
 594
 595impl UpdateView for AsyncAppContext {
 596    fn update_view<T, S>(
 597        &mut self,
 598        handle: &ViewHandle<T>,
 599        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 600    ) -> S
 601    where
 602        T: View,
 603    {
 604        self.0.borrow_mut().update_view(handle, update)
 605    }
 606}
 607
 608impl ReadViewWith for AsyncAppContext {
 609    fn read_view_with<V, T>(
 610        &self,
 611        handle: &ViewHandle<V>,
 612        read: &mut dyn FnMut(&V, &AppContext) -> T,
 613    ) -> T
 614    where
 615        V: View,
 616    {
 617        let cx = self.0.borrow();
 618        let cx = cx.as_ref();
 619        read(handle.read(cx), cx)
 620    }
 621}
 622
 623impl UpdateModel for TestAppContext {
 624    fn update_model<T: Entity, O>(
 625        &mut self,
 626        handle: &ModelHandle<T>,
 627        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
 628    ) -> O {
 629        self.cx.borrow_mut().update_model(handle, update)
 630    }
 631}
 632
 633impl ReadModelWith for TestAppContext {
 634    fn read_model_with<E: Entity, T>(
 635        &self,
 636        handle: &ModelHandle<E>,
 637        read: &mut dyn FnMut(&E, &AppContext) -> T,
 638    ) -> T {
 639        let cx = self.cx.borrow();
 640        let cx = cx.as_ref();
 641        read(handle.read(cx), cx)
 642    }
 643}
 644
 645impl UpdateView for TestAppContext {
 646    fn update_view<T, S>(
 647        &mut self,
 648        handle: &ViewHandle<T>,
 649        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 650    ) -> S
 651    where
 652        T: View,
 653    {
 654        self.cx.borrow_mut().update_view(handle, update)
 655    }
 656}
 657
 658impl ReadViewWith for TestAppContext {
 659    fn read_view_with<V, T>(
 660        &self,
 661        handle: &ViewHandle<V>,
 662        read: &mut dyn FnMut(&V, &AppContext) -> T,
 663    ) -> T
 664    where
 665        V: View,
 666    {
 667        let cx = self.cx.borrow();
 668        let cx = cx.as_ref();
 669        read(handle.read(cx), cx)
 670    }
 671}
 672
 673type ActionCallback =
 674    dyn FnMut(&mut dyn AnyView, &dyn AnyAction, &mut MutableAppContext, usize, usize) -> bool;
 675type GlobalActionCallback = dyn FnMut(&dyn AnyAction, &mut MutableAppContext);
 676
 677type SubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut MutableAppContext) -> bool>;
 678type ObservationCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>;
 679type ReleaseObservationCallback = Box<dyn FnMut(&mut MutableAppContext)>;
 680
 681pub struct MutableAppContext {
 682    weak_self: Option<rc::Weak<RefCell<Self>>>,
 683    foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 684    assets: Arc<AssetCache>,
 685    cx: AppContext,
 686    actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 687    global_actions: HashMap<TypeId, Box<GlobalActionCallback>>,
 688    keystroke_matcher: keymap::Matcher,
 689    next_entity_id: usize,
 690    next_window_id: usize,
 691    next_subscription_id: usize,
 692    frame_count: usize,
 693    subscriptions: Arc<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>,
 694    observations: Arc<Mutex<HashMap<usize, BTreeMap<usize, ObservationCallback>>>>,
 695    release_observations: Arc<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>,
 696    presenters_and_platform_windows:
 697        HashMap<usize, (Rc<RefCell<Presenter>>, Box<dyn platform::Window>)>,
 698    debug_elements_callbacks: HashMap<usize, Box<dyn Fn(&AppContext) -> crate::json::Value>>,
 699    foreground: Rc<executor::Foreground>,
 700    pending_effects: VecDeque<Effect>,
 701    pending_notifications: HashSet<usize>,
 702    pending_flushes: usize,
 703    flushing_effects: bool,
 704    next_cursor_style_handle_id: Arc<AtomicUsize>,
 705}
 706
 707impl MutableAppContext {
 708    fn new(
 709        foreground: Rc<executor::Foreground>,
 710        background: Arc<executor::Background>,
 711        platform: Arc<dyn platform::Platform>,
 712        foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 713        font_cache: Arc<FontCache>,
 714        asset_source: impl AssetSource,
 715        // entity_drop_tx:
 716    ) -> Self {
 717        Self {
 718            weak_self: None,
 719            foreground_platform,
 720            assets: Arc::new(AssetCache::new(asset_source)),
 721            cx: AppContext {
 722                models: Default::default(),
 723                views: Default::default(),
 724                windows: Default::default(),
 725                element_states: Default::default(),
 726                ref_counts: Arc::new(Mutex::new(RefCounts::default())),
 727                background,
 728                font_cache,
 729                platform,
 730            },
 731            actions: HashMap::new(),
 732            global_actions: HashMap::new(),
 733            keystroke_matcher: keymap::Matcher::default(),
 734            next_entity_id: 0,
 735            next_window_id: 0,
 736            next_subscription_id: 0,
 737            frame_count: 0,
 738            subscriptions: Default::default(),
 739            observations: Default::default(),
 740            release_observations: Default::default(),
 741            presenters_and_platform_windows: HashMap::new(),
 742            debug_elements_callbacks: HashMap::new(),
 743            foreground,
 744            pending_effects: VecDeque::new(),
 745            pending_notifications: HashSet::new(),
 746            pending_flushes: 0,
 747            flushing_effects: false,
 748            next_cursor_style_handle_id: Default::default(),
 749        }
 750    }
 751
 752    pub fn upgrade(&self) -> App {
 753        App(self.weak_self.as_ref().unwrap().upgrade().unwrap())
 754    }
 755
 756    pub fn quit(&mut self) {
 757        let mut futures = Vec::new();
 758        for model_id in self.cx.models.keys().copied().collect::<Vec<_>>() {
 759            let mut model = self.cx.models.remove(&model_id).unwrap();
 760            futures.extend(model.app_will_quit(self));
 761            self.cx.models.insert(model_id, model);
 762        }
 763
 764        for view_id in self.cx.views.keys().copied().collect::<Vec<_>>() {
 765            let mut view = self.cx.views.remove(&view_id).unwrap();
 766            futures.extend(view.app_will_quit(self));
 767            self.cx.views.insert(view_id, view);
 768        }
 769
 770        self.remove_all_windows();
 771
 772        let futures = futures::future::join_all(futures);
 773        if self
 774            .background
 775            .block_with_timeout(Duration::from_millis(100), futures)
 776            .is_err()
 777        {
 778            log::error!("timed out waiting on app_will_quit");
 779        }
 780    }
 781
 782    fn remove_all_windows(&mut self) {
 783        for (window_id, _) in self.cx.windows.drain() {
 784            self.presenters_and_platform_windows.remove(&window_id);
 785        }
 786        self.remove_dropped_entities();
 787    }
 788
 789    pub fn platform(&self) -> Arc<dyn platform::Platform> {
 790        self.cx.platform.clone()
 791    }
 792
 793    pub fn font_cache(&self) -> &Arc<FontCache> {
 794        &self.cx.font_cache
 795    }
 796
 797    pub fn foreground(&self) -> &Rc<executor::Foreground> {
 798        &self.foreground
 799    }
 800
 801    pub fn background(&self) -> &Arc<executor::Background> {
 802        &self.cx.background
 803    }
 804
 805    pub fn on_debug_elements<F>(&mut self, window_id: usize, callback: F)
 806    where
 807        F: 'static + Fn(&AppContext) -> crate::json::Value,
 808    {
 809        self.debug_elements_callbacks
 810            .insert(window_id, Box::new(callback));
 811    }
 812
 813    pub fn debug_elements(&self, window_id: usize) -> Option<crate::json::Value> {
 814        self.debug_elements_callbacks
 815            .get(&window_id)
 816            .map(|debug_elements| debug_elements(&self.cx))
 817    }
 818
 819    pub fn add_action<A, V, F>(&mut self, mut handler: F)
 820    where
 821        A: Action,
 822        V: View,
 823        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
 824    {
 825        let handler = Box::new(
 826            move |view: &mut dyn AnyView,
 827                  action: &dyn AnyAction,
 828                  cx: &mut MutableAppContext,
 829                  window_id: usize,
 830                  view_id: usize| {
 831                let action = action.as_any().downcast_ref().unwrap();
 832                let mut cx = ViewContext::new(cx, window_id, view_id);
 833                handler(
 834                    view.as_any_mut()
 835                        .downcast_mut()
 836                        .expect("downcast is type safe"),
 837                    action,
 838                    &mut cx,
 839                );
 840                cx.halt_action_dispatch
 841            },
 842        );
 843
 844        self.actions
 845            .entry(TypeId::of::<V>())
 846            .or_default()
 847            .entry(TypeId::of::<A>())
 848            .or_default()
 849            .push(handler);
 850    }
 851
 852    pub fn add_async_action<A, V, F>(&mut self, mut handler: F)
 853    where
 854        A: Action,
 855        V: View,
 856        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> Option<Task<Result<()>>>,
 857    {
 858        self.add_action(move |view, action, cx| {
 859            handler(view, action, cx).map(|task| task.detach_and_log_err(cx));
 860        })
 861    }
 862
 863    pub fn add_global_action<A, F>(&mut self, mut handler: F)
 864    where
 865        A: Action,
 866        F: 'static + FnMut(&A, &mut MutableAppContext),
 867    {
 868        let handler = Box::new(move |action: &dyn AnyAction, cx: &mut MutableAppContext| {
 869            let action = action.as_any().downcast_ref().unwrap();
 870            handler(action, cx);
 871        });
 872
 873        if self
 874            .global_actions
 875            .insert(TypeId::of::<A>(), handler)
 876            .is_some()
 877        {
 878            panic!("registered multiple global handlers for the same action type");
 879        }
 880    }
 881
 882    pub fn window_ids(&self) -> impl Iterator<Item = usize> + '_ {
 883        self.cx.windows.keys().cloned()
 884    }
 885
 886    pub fn activate_window(&self, window_id: usize) {
 887        if let Some((_, window)) = self.presenters_and_platform_windows.get(&window_id) {
 888            window.activate()
 889        }
 890    }
 891
 892    pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
 893        self.cx
 894            .windows
 895            .get(&window_id)
 896            .and_then(|window| window.root_view.clone().downcast::<T>())
 897    }
 898
 899    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
 900        self.cx.root_view_id(window_id)
 901    }
 902
 903    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
 904        self.cx.focused_view_id(window_id)
 905    }
 906
 907    pub fn render_view(
 908        &mut self,
 909        window_id: usize,
 910        view_id: usize,
 911        titlebar_height: f32,
 912        refreshing: bool,
 913    ) -> Result<ElementBox> {
 914        let mut view = self
 915            .cx
 916            .views
 917            .remove(&(window_id, view_id))
 918            .ok_or(anyhow!("view not found"))?;
 919        let element = view.render(window_id, view_id, titlebar_height, refreshing, self);
 920        self.cx.views.insert((window_id, view_id), view);
 921        Ok(element)
 922    }
 923
 924    pub fn render_views(
 925        &mut self,
 926        window_id: usize,
 927        titlebar_height: f32,
 928    ) -> HashMap<usize, ElementBox> {
 929        self.start_frame();
 930        let view_ids = self
 931            .views
 932            .keys()
 933            .filter_map(|(win_id, view_id)| {
 934                if *win_id == window_id {
 935                    Some(*view_id)
 936                } else {
 937                    None
 938                }
 939            })
 940            .collect::<Vec<_>>();
 941        view_ids
 942            .into_iter()
 943            .map(|view_id| {
 944                (
 945                    view_id,
 946                    self.render_view(window_id, view_id, titlebar_height, false)
 947                        .unwrap(),
 948                )
 949            })
 950            .collect()
 951    }
 952
 953    pub(crate) fn start_frame(&mut self) {
 954        self.frame_count += 1;
 955    }
 956
 957    pub fn update<T, F: FnOnce(&mut Self) -> T>(&mut self, callback: F) -> T {
 958        self.pending_flushes += 1;
 959        let result = callback(self);
 960        self.flush_effects();
 961        result
 962    }
 963
 964    pub fn set_menus(&mut self, menus: Vec<Menu>) {
 965        self.foreground_platform.set_menus(menus);
 966    }
 967
 968    fn prompt(
 969        &self,
 970        window_id: usize,
 971        level: PromptLevel,
 972        msg: &str,
 973        answers: &[&str],
 974    ) -> oneshot::Receiver<usize> {
 975        let (_, window) = &self.presenters_and_platform_windows[&window_id];
 976        window.prompt(level, msg, answers)
 977    }
 978
 979    pub fn prompt_for_paths(
 980        &self,
 981        options: PathPromptOptions,
 982    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 983        self.foreground_platform.prompt_for_paths(options)
 984    }
 985
 986    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
 987        self.foreground_platform.prompt_for_new_path(directory)
 988    }
 989
 990    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 991    where
 992        E: Entity,
 993        E::Event: 'static,
 994        H: Handle<E>,
 995        F: 'static + FnMut(H, &E::Event, &mut Self),
 996    {
 997        self.subscribe_internal(handle, move |handle, event, cx| {
 998            callback(handle, event, cx);
 999            true
1000        })
1001    }
1002
1003    pub fn observe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1004    where
1005        E: Entity,
1006        E::Event: 'static,
1007        H: Handle<E>,
1008        F: 'static + FnMut(H, &mut Self),
1009    {
1010        self.observe_internal(handle, move |handle, cx| {
1011            callback(handle, cx);
1012            true
1013        })
1014    }
1015
1016    pub fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1017    where
1018        E: Entity,
1019        E::Event: 'static,
1020        H: Handle<E>,
1021        F: 'static + FnMut(H, &E::Event, &mut Self) -> bool,
1022    {
1023        let id = post_inc(&mut self.next_subscription_id);
1024        let emitter = handle.downgrade();
1025        self.subscriptions
1026            .lock()
1027            .entry(handle.id())
1028            .or_default()
1029            .insert(
1030                id,
1031                Box::new(move |payload, cx| {
1032                    if let Some(emitter) = H::upgrade_from(&emitter, cx.as_ref()) {
1033                        let payload = payload.downcast_ref().expect("downcast is type safe");
1034                        callback(emitter, payload, cx)
1035                    } else {
1036                        false
1037                    }
1038                }),
1039            );
1040        Subscription::Subscription {
1041            id,
1042            entity_id: handle.id(),
1043            subscriptions: Some(Arc::downgrade(&self.subscriptions)),
1044        }
1045    }
1046
1047    fn observe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1048    where
1049        E: Entity,
1050        E::Event: 'static,
1051        H: Handle<E>,
1052        F: 'static + FnMut(H, &mut Self) -> bool,
1053    {
1054        let id = post_inc(&mut self.next_subscription_id);
1055        let observed = handle.downgrade();
1056        self.observations
1057            .lock()
1058            .entry(handle.id())
1059            .or_default()
1060            .insert(
1061                id,
1062                Box::new(move |cx| {
1063                    if let Some(observed) = H::upgrade_from(&observed, cx) {
1064                        callback(observed, cx)
1065                    } else {
1066                        false
1067                    }
1068                }),
1069            );
1070        Subscription::Observation {
1071            id,
1072            entity_id: handle.id(),
1073            observations: Some(Arc::downgrade(&self.observations)),
1074        }
1075    }
1076
1077    pub fn observe_release<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1078    where
1079        E: Entity,
1080        E::Event: 'static,
1081        H: Handle<E>,
1082        F: 'static + FnMut(&mut Self),
1083    {
1084        let id = post_inc(&mut self.next_subscription_id);
1085        self.release_observations
1086            .lock()
1087            .entry(handle.id())
1088            .or_default()
1089            .insert(id, Box::new(move |cx| callback(cx)));
1090        Subscription::ReleaseObservation {
1091            id,
1092            entity_id: handle.id(),
1093            observations: Some(Arc::downgrade(&self.release_observations)),
1094        }
1095    }
1096
1097    fn defer(&mut self, callback: Box<dyn FnOnce(&mut MutableAppContext)>) {
1098        self.pending_effects.push_back(Effect::Deferred(callback))
1099    }
1100
1101    pub(crate) fn notify_model(&mut self, model_id: usize) {
1102        if self.pending_notifications.insert(model_id) {
1103            self.pending_effects
1104                .push_back(Effect::ModelNotification { model_id });
1105        }
1106    }
1107
1108    pub(crate) fn notify_view(&mut self, window_id: usize, view_id: usize) {
1109        if self.pending_notifications.insert(view_id) {
1110            self.pending_effects
1111                .push_back(Effect::ViewNotification { window_id, view_id });
1112        }
1113    }
1114
1115    pub fn dispatch_action<A: Action>(
1116        &mut self,
1117        window_id: usize,
1118        responder_chain: Vec<usize>,
1119        action: &A,
1120    ) {
1121        self.dispatch_action_any(window_id, &responder_chain, action);
1122    }
1123
1124    pub(crate) fn dispatch_action_any(
1125        &mut self,
1126        window_id: usize,
1127        path: &[usize],
1128        action: &dyn AnyAction,
1129    ) -> bool {
1130        self.update(|this| {
1131            let mut halted_dispatch = false;
1132            for view_id in path.iter().rev() {
1133                if let Some(mut view) = this.cx.views.remove(&(window_id, *view_id)) {
1134                    let type_id = view.as_any().type_id();
1135
1136                    if let Some((name, mut handlers)) = this
1137                        .actions
1138                        .get_mut(&type_id)
1139                        .and_then(|h| h.remove_entry(&action.id()))
1140                    {
1141                        for handler in handlers.iter_mut().rev() {
1142                            let halt_dispatch =
1143                                handler(view.as_mut(), action, this, window_id, *view_id);
1144                            if halt_dispatch {
1145                                halted_dispatch = true;
1146                                break;
1147                            }
1148                        }
1149                        this.actions
1150                            .get_mut(&type_id)
1151                            .unwrap()
1152                            .insert(name, handlers);
1153                    }
1154
1155                    this.cx.views.insert((window_id, *view_id), view);
1156
1157                    if halted_dispatch {
1158                        break;
1159                    }
1160                }
1161            }
1162
1163            if !halted_dispatch {
1164                halted_dispatch = this.dispatch_global_action_any(action);
1165            }
1166            halted_dispatch
1167        })
1168    }
1169
1170    pub fn dispatch_global_action<A: Action>(&mut self, action: A) {
1171        self.dispatch_global_action_any(&action);
1172    }
1173
1174    fn dispatch_global_action_any(&mut self, action: &dyn AnyAction) -> bool {
1175        self.update(|this| {
1176            if let Some((name, mut handler)) = this.global_actions.remove_entry(&action.id()) {
1177                handler(action, this);
1178                this.global_actions.insert(name, handler);
1179                true
1180            } else {
1181                false
1182            }
1183        })
1184    }
1185
1186    pub fn add_bindings<T: IntoIterator<Item = keymap::Binding>>(&mut self, bindings: T) {
1187        self.keystroke_matcher.add_bindings(bindings);
1188    }
1189
1190    pub fn dispatch_keystroke(
1191        &mut self,
1192        window_id: usize,
1193        responder_chain: Vec<usize>,
1194        keystroke: &Keystroke,
1195    ) -> Result<bool> {
1196        let mut context_chain = Vec::new();
1197        for view_id in &responder_chain {
1198            if let Some(view) = self.cx.views.get(&(window_id, *view_id)) {
1199                context_chain.push(view.keymap_context(self.as_ref()));
1200            } else {
1201                return Err(anyhow!(
1202                    "View {} in responder chain does not exist",
1203                    view_id
1204                ));
1205            }
1206        }
1207
1208        let mut pending = false;
1209        for (i, cx) in context_chain.iter().enumerate().rev() {
1210            match self
1211                .keystroke_matcher
1212                .push_keystroke(keystroke.clone(), responder_chain[i], cx)
1213            {
1214                MatchResult::None => {}
1215                MatchResult::Pending => pending = true,
1216                MatchResult::Action(action) => {
1217                    if self.dispatch_action_any(window_id, &responder_chain[0..=i], action.as_ref())
1218                    {
1219                        self.keystroke_matcher.clear_pending();
1220                        return Ok(true);
1221                    }
1222                }
1223            }
1224        }
1225
1226        Ok(pending)
1227    }
1228
1229    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
1230    where
1231        T: Entity,
1232        F: FnOnce(&mut ModelContext<T>) -> T,
1233    {
1234        self.update(|this| {
1235            let model_id = post_inc(&mut this.next_entity_id);
1236            let handle = ModelHandle::new(model_id, &this.cx.ref_counts);
1237            let mut cx = ModelContext::new(this, model_id);
1238            let model = build_model(&mut cx);
1239            this.cx.models.insert(model_id, Box::new(model));
1240            handle
1241        })
1242    }
1243
1244    pub fn add_window<T, F>(
1245        &mut self,
1246        window_options: WindowOptions,
1247        build_root_view: F,
1248    ) -> (usize, ViewHandle<T>)
1249    where
1250        T: View,
1251        F: FnOnce(&mut ViewContext<T>) -> T,
1252    {
1253        self.update(|this| {
1254            let window_id = post_inc(&mut this.next_window_id);
1255            let root_view = this.add_view(window_id, build_root_view);
1256
1257            this.cx.windows.insert(
1258                window_id,
1259                Window {
1260                    root_view: root_view.clone().into(),
1261                    focused_view_id: root_view.id(),
1262                    invalidation: None,
1263                },
1264            );
1265            this.open_platform_window(window_id, window_options);
1266            root_view.update(this, |view, cx| {
1267                view.on_focus(cx);
1268                cx.notify();
1269            });
1270
1271            (window_id, root_view)
1272        })
1273    }
1274
1275    pub fn remove_window(&mut self, window_id: usize) {
1276        self.cx.windows.remove(&window_id);
1277        self.presenters_and_platform_windows.remove(&window_id);
1278        self.remove_dropped_entities();
1279        self.flush_effects();
1280    }
1281
1282    fn open_platform_window(&mut self, window_id: usize, window_options: WindowOptions) {
1283        let mut window =
1284            self.cx
1285                .platform
1286                .open_window(window_id, window_options, self.foreground.clone());
1287        let presenter = Rc::new(RefCell::new(
1288            self.build_presenter(window_id, window.titlebar_height()),
1289        ));
1290
1291        {
1292            let mut app = self.upgrade();
1293            let presenter = presenter.clone();
1294            window.on_event(Box::new(move |event| {
1295                app.update(|cx| {
1296                    if let Event::KeyDown { keystroke, .. } = &event {
1297                        if cx
1298                            .dispatch_keystroke(
1299                                window_id,
1300                                presenter.borrow().dispatch_path(cx.as_ref()),
1301                                keystroke,
1302                            )
1303                            .unwrap()
1304                        {
1305                            return;
1306                        }
1307                    }
1308
1309                    presenter.borrow_mut().dispatch_event(event, cx);
1310                })
1311            }));
1312        }
1313
1314        {
1315            let mut app = self.upgrade();
1316            window.on_resize(Box::new(move || {
1317                app.update(|cx| cx.resize_window(window_id))
1318            }));
1319        }
1320
1321        {
1322            let mut app = self.upgrade();
1323            window.on_close(Box::new(move || {
1324                app.update(|cx| cx.remove_window(window_id));
1325            }));
1326        }
1327
1328        self.presenters_and_platform_windows
1329            .insert(window_id, (presenter.clone(), window));
1330
1331        self.on_debug_elements(window_id, move |cx| {
1332            presenter.borrow().debug_elements(cx).unwrap()
1333        });
1334    }
1335
1336    pub fn build_presenter(&mut self, window_id: usize, titlebar_height: f32) -> Presenter {
1337        Presenter::new(
1338            window_id,
1339            titlebar_height,
1340            self.cx.font_cache.clone(),
1341            TextLayoutCache::new(self.cx.platform.fonts()),
1342            self.assets.clone(),
1343            self,
1344        )
1345    }
1346
1347    pub fn build_render_context<V: View>(
1348        &mut self,
1349        window_id: usize,
1350        view_id: usize,
1351        titlebar_height: f32,
1352        refreshing: bool,
1353    ) -> RenderContext<V> {
1354        RenderContext {
1355            app: self,
1356            titlebar_height,
1357            refreshing,
1358            window_id,
1359            view_id,
1360            view_type: PhantomData,
1361        }
1362    }
1363
1364    pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
1365    where
1366        T: View,
1367        F: FnOnce(&mut ViewContext<T>) -> T,
1368    {
1369        self.add_option_view(window_id, |cx| Some(build_view(cx)))
1370            .unwrap()
1371    }
1372
1373    pub fn add_option_view<T, F>(
1374        &mut self,
1375        window_id: usize,
1376        build_view: F,
1377    ) -> Option<ViewHandle<T>>
1378    where
1379        T: View,
1380        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1381    {
1382        self.update(|this| {
1383            let view_id = post_inc(&mut this.next_entity_id);
1384            let mut cx = ViewContext::new(this, window_id, view_id);
1385            let handle = if let Some(view) = build_view(&mut cx) {
1386                this.cx.views.insert((window_id, view_id), Box::new(view));
1387                if let Some(window) = this.cx.windows.get_mut(&window_id) {
1388                    window
1389                        .invalidation
1390                        .get_or_insert_with(Default::default)
1391                        .updated
1392                        .insert(view_id);
1393                }
1394                Some(ViewHandle::new(window_id, view_id, &this.cx.ref_counts))
1395            } else {
1396                None
1397            };
1398            handle
1399        })
1400    }
1401
1402    pub fn element_state<Tag: 'static, T: 'static + Default>(
1403        &mut self,
1404        id: ElementStateId,
1405    ) -> ElementStateHandle<T> {
1406        let key = (TypeId::of::<Tag>(), id);
1407        self.cx
1408            .element_states
1409            .entry(key)
1410            .or_insert_with(|| Box::new(T::default()));
1411        ElementStateHandle::new(
1412            TypeId::of::<Tag>(),
1413            id,
1414            self.frame_count,
1415            &self.cx.ref_counts,
1416        )
1417    }
1418
1419    fn remove_dropped_entities(&mut self) {
1420        loop {
1421            let (dropped_models, dropped_views, dropped_element_states) =
1422                self.cx.ref_counts.lock().take_dropped();
1423            if dropped_models.is_empty()
1424                && dropped_views.is_empty()
1425                && dropped_element_states.is_empty()
1426            {
1427                break;
1428            }
1429
1430            for model_id in dropped_models {
1431                self.subscriptions.lock().remove(&model_id);
1432                self.observations.lock().remove(&model_id);
1433                let mut model = self.cx.models.remove(&model_id).unwrap();
1434                model.release(self);
1435                self.pending_effects.push_back(Effect::Release {
1436                    entity_id: model_id,
1437                });
1438            }
1439
1440            for (window_id, view_id) in dropped_views {
1441                self.subscriptions.lock().remove(&view_id);
1442                self.observations.lock().remove(&view_id);
1443                let mut view = self.cx.views.remove(&(window_id, view_id)).unwrap();
1444                view.release(self);
1445                let change_focus_to = self.cx.windows.get_mut(&window_id).and_then(|window| {
1446                    window
1447                        .invalidation
1448                        .get_or_insert_with(Default::default)
1449                        .removed
1450                        .push(view_id);
1451                    if window.focused_view_id == view_id {
1452                        Some(window.root_view.id())
1453                    } else {
1454                        None
1455                    }
1456                });
1457
1458                if let Some(view_id) = change_focus_to {
1459                    self.focus(window_id, view_id);
1460                }
1461
1462                self.pending_effects
1463                    .push_back(Effect::Release { entity_id: view_id });
1464            }
1465
1466            for key in dropped_element_states {
1467                self.cx.element_states.remove(&key);
1468            }
1469        }
1470    }
1471
1472    fn flush_effects(&mut self) {
1473        self.pending_flushes = self.pending_flushes.saturating_sub(1);
1474
1475        if !self.flushing_effects && self.pending_flushes == 0 {
1476            self.flushing_effects = true;
1477
1478            let mut refreshing = false;
1479            loop {
1480                if let Some(effect) = self.pending_effects.pop_front() {
1481                    match effect {
1482                        Effect::Event { entity_id, payload } => self.emit_event(entity_id, payload),
1483                        Effect::ModelNotification { model_id } => {
1484                            self.notify_model_observers(model_id)
1485                        }
1486                        Effect::ViewNotification { window_id, view_id } => {
1487                            self.notify_view_observers(window_id, view_id)
1488                        }
1489                        Effect::Deferred(callback) => callback(self),
1490                        Effect::Release { entity_id } => self.notify_release_observers(entity_id),
1491                        Effect::Focus { window_id, view_id } => {
1492                            self.focus(window_id, view_id);
1493                        }
1494                        Effect::ResizeWindow { window_id } => {
1495                            if let Some(window) = self.cx.windows.get_mut(&window_id) {
1496                                window
1497                                    .invalidation
1498                                    .get_or_insert(WindowInvalidation::default());
1499                            }
1500                        }
1501                        Effect::RefreshWindows => {
1502                            refreshing = true;
1503                        }
1504                    }
1505                    self.pending_notifications.clear();
1506                    self.remove_dropped_entities();
1507                } else {
1508                    self.remove_dropped_entities();
1509                    if refreshing {
1510                        self.perform_window_refresh();
1511                    } else {
1512                        self.update_windows();
1513                    }
1514
1515                    if self.pending_effects.is_empty() {
1516                        self.flushing_effects = false;
1517                        self.pending_notifications.clear();
1518                        break;
1519                    } else {
1520                        refreshing = false;
1521                    }
1522                }
1523            }
1524        }
1525    }
1526
1527    fn update_windows(&mut self) {
1528        let mut invalidations = HashMap::new();
1529        for (window_id, window) in &mut self.cx.windows {
1530            if let Some(invalidation) = window.invalidation.take() {
1531                invalidations.insert(*window_id, invalidation);
1532            }
1533        }
1534
1535        for (window_id, invalidation) in invalidations {
1536            if let Some((presenter, mut window)) =
1537                self.presenters_and_platform_windows.remove(&window_id)
1538            {
1539                {
1540                    let mut presenter = presenter.borrow_mut();
1541                    presenter.invalidate(invalidation, self);
1542                    let scene =
1543                        presenter.build_scene(window.size(), window.scale_factor(), false, self);
1544                    window.present_scene(scene);
1545                }
1546                self.presenters_and_platform_windows
1547                    .insert(window_id, (presenter, window));
1548            }
1549        }
1550    }
1551
1552    fn resize_window(&mut self, window_id: usize) {
1553        self.pending_effects
1554            .push_back(Effect::ResizeWindow { window_id });
1555    }
1556
1557    pub fn refresh_windows(&mut self) {
1558        self.pending_effects.push_back(Effect::RefreshWindows);
1559    }
1560
1561    fn perform_window_refresh(&mut self) {
1562        let mut presenters = mem::take(&mut self.presenters_and_platform_windows);
1563        for (window_id, (presenter, window)) in &mut presenters {
1564            let invalidation = self
1565                .cx
1566                .windows
1567                .get_mut(&window_id)
1568                .unwrap()
1569                .invalidation
1570                .take();
1571            let mut presenter = presenter.borrow_mut();
1572            presenter.refresh(invalidation, self);
1573            let scene = presenter.build_scene(window.size(), window.scale_factor(), true, self);
1574            window.present_scene(scene);
1575        }
1576        self.presenters_and_platform_windows = presenters;
1577    }
1578
1579    pub fn set_cursor_style(&mut self, style: CursorStyle) -> CursorStyleHandle {
1580        self.platform.set_cursor_style(style);
1581        let id = self.next_cursor_style_handle_id.fetch_add(1, SeqCst);
1582        CursorStyleHandle {
1583            id,
1584            next_cursor_style_handle_id: self.next_cursor_style_handle_id.clone(),
1585            platform: self.platform(),
1586        }
1587    }
1588
1589    fn emit_event(&mut self, entity_id: usize, payload: Box<dyn Any>) {
1590        let callbacks = self.subscriptions.lock().remove(&entity_id);
1591        if let Some(callbacks) = callbacks {
1592            for (id, mut callback) in callbacks {
1593                let alive = callback(payload.as_ref(), self);
1594                if alive {
1595                    self.subscriptions
1596                        .lock()
1597                        .entry(entity_id)
1598                        .or_default()
1599                        .insert(id, callback);
1600                }
1601            }
1602        }
1603    }
1604
1605    fn notify_model_observers(&mut self, observed_id: usize) {
1606        let callbacks = self.observations.lock().remove(&observed_id);
1607        if let Some(callbacks) = callbacks {
1608            if self.cx.models.contains_key(&observed_id) {
1609                for (id, mut callback) in callbacks {
1610                    let alive = callback(self);
1611                    if alive {
1612                        self.observations
1613                            .lock()
1614                            .entry(observed_id)
1615                            .or_default()
1616                            .insert(id, callback);
1617                    }
1618                }
1619            }
1620        }
1621    }
1622
1623    fn notify_view_observers(&mut self, observed_window_id: usize, observed_view_id: usize) {
1624        if let Some(window) = self.cx.windows.get_mut(&observed_window_id) {
1625            window
1626                .invalidation
1627                .get_or_insert_with(Default::default)
1628                .updated
1629                .insert(observed_view_id);
1630        }
1631
1632        let callbacks = self.observations.lock().remove(&observed_view_id);
1633        if let Some(callbacks) = callbacks {
1634            if self
1635                .cx
1636                .views
1637                .contains_key(&(observed_window_id, observed_view_id))
1638            {
1639                for (id, mut callback) in callbacks {
1640                    let alive = callback(self);
1641                    if alive {
1642                        self.observations
1643                            .lock()
1644                            .entry(observed_view_id)
1645                            .or_default()
1646                            .insert(id, callback);
1647                    }
1648                }
1649            }
1650        }
1651    }
1652
1653    fn notify_release_observers(&mut self, entity_id: usize) {
1654        let callbacks = self.release_observations.lock().remove(&entity_id);
1655        if let Some(callbacks) = callbacks {
1656            for (_, mut callback) in callbacks {
1657                callback(self);
1658            }
1659        }
1660    }
1661
1662    fn focus(&mut self, window_id: usize, focused_id: usize) {
1663        if self
1664            .cx
1665            .windows
1666            .get(&window_id)
1667            .map(|w| w.focused_view_id)
1668            .map_or(false, |cur_focused| cur_focused == focused_id)
1669        {
1670            return;
1671        }
1672
1673        self.update(|this| {
1674            let blurred_id = this.cx.windows.get_mut(&window_id).map(|window| {
1675                let blurred_id = window.focused_view_id;
1676                window.focused_view_id = focused_id;
1677                blurred_id
1678            });
1679
1680            if let Some(blurred_id) = blurred_id {
1681                if let Some(mut blurred_view) = this.cx.views.remove(&(window_id, blurred_id)) {
1682                    blurred_view.on_blur(this, window_id, blurred_id);
1683                    this.cx.views.insert((window_id, blurred_id), blurred_view);
1684                }
1685            }
1686
1687            if let Some(mut focused_view) = this.cx.views.remove(&(window_id, focused_id)) {
1688                focused_view.on_focus(this, window_id, focused_id);
1689                this.cx.views.insert((window_id, focused_id), focused_view);
1690            }
1691        })
1692    }
1693
1694    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
1695    where
1696        F: FnOnce(AsyncAppContext) -> Fut,
1697        Fut: 'static + Future<Output = T>,
1698        T: 'static,
1699    {
1700        let future = f(self.to_async());
1701        let cx = self.to_async();
1702        self.foreground.spawn(async move {
1703            let result = future.await;
1704            cx.0.borrow_mut().flush_effects();
1705            result
1706        })
1707    }
1708
1709    pub fn to_async(&self) -> AsyncAppContext {
1710        AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
1711    }
1712
1713    pub fn write_to_clipboard(&self, item: ClipboardItem) {
1714        self.cx.platform.write_to_clipboard(item);
1715    }
1716
1717    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1718        self.cx.platform.read_from_clipboard()
1719    }
1720}
1721
1722impl ReadModel for MutableAppContext {
1723    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1724        if let Some(model) = self.cx.models.get(&handle.model_id) {
1725            model
1726                .as_any()
1727                .downcast_ref()
1728                .expect("downcast is type safe")
1729        } else {
1730            panic!("circular model reference");
1731        }
1732    }
1733}
1734
1735impl UpdateModel for MutableAppContext {
1736    fn update_model<T: Entity, V>(
1737        &mut self,
1738        handle: &ModelHandle<T>,
1739        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
1740    ) -> V {
1741        if let Some(mut model) = self.cx.models.remove(&handle.model_id) {
1742            self.update(|this| {
1743                let mut cx = ModelContext::new(this, handle.model_id);
1744                let result = update(
1745                    model
1746                        .as_any_mut()
1747                        .downcast_mut()
1748                        .expect("downcast is type safe"),
1749                    &mut cx,
1750                );
1751                this.cx.models.insert(handle.model_id, model);
1752                result
1753            })
1754        } else {
1755            panic!("circular model update");
1756        }
1757    }
1758}
1759
1760impl UpgradeModelHandle for MutableAppContext {
1761    fn upgrade_model_handle<T: Entity>(
1762        &self,
1763        handle: &WeakModelHandle<T>,
1764    ) -> Option<ModelHandle<T>> {
1765        self.cx.upgrade_model_handle(handle)
1766    }
1767}
1768
1769impl UpgradeViewHandle for MutableAppContext {
1770    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
1771        self.cx.upgrade_view_handle(handle)
1772    }
1773}
1774
1775impl ReadView for MutableAppContext {
1776    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1777        if let Some(view) = self.cx.views.get(&(handle.window_id, handle.view_id)) {
1778            view.as_any().downcast_ref().expect("downcast is type safe")
1779        } else {
1780            panic!("circular view reference");
1781        }
1782    }
1783}
1784
1785impl UpdateView for MutableAppContext {
1786    fn update_view<T, S>(
1787        &mut self,
1788        handle: &ViewHandle<T>,
1789        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
1790    ) -> S
1791    where
1792        T: View,
1793    {
1794        self.update(|this| {
1795            let mut view = this
1796                .cx
1797                .views
1798                .remove(&(handle.window_id, handle.view_id))
1799                .expect("circular view update");
1800
1801            let mut cx = ViewContext::new(this, handle.window_id, handle.view_id);
1802            let result = update(
1803                view.as_any_mut()
1804                    .downcast_mut()
1805                    .expect("downcast is type safe"),
1806                &mut cx,
1807            );
1808            this.cx
1809                .views
1810                .insert((handle.window_id, handle.view_id), view);
1811            result
1812        })
1813    }
1814}
1815
1816impl AsRef<AppContext> for MutableAppContext {
1817    fn as_ref(&self) -> &AppContext {
1818        &self.cx
1819    }
1820}
1821
1822impl Deref for MutableAppContext {
1823    type Target = AppContext;
1824
1825    fn deref(&self) -> &Self::Target {
1826        &self.cx
1827    }
1828}
1829
1830pub struct AppContext {
1831    models: HashMap<usize, Box<dyn AnyModel>>,
1832    views: HashMap<(usize, usize), Box<dyn AnyView>>,
1833    windows: HashMap<usize, Window>,
1834    element_states: HashMap<(TypeId, ElementStateId), Box<dyn Any>>,
1835    background: Arc<executor::Background>,
1836    ref_counts: Arc<Mutex<RefCounts>>,
1837    font_cache: Arc<FontCache>,
1838    platform: Arc<dyn Platform>,
1839}
1840
1841impl AppContext {
1842    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
1843        self.windows
1844            .get(&window_id)
1845            .map(|window| window.root_view.id())
1846    }
1847
1848    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
1849        self.windows
1850            .get(&window_id)
1851            .map(|window| window.focused_view_id)
1852    }
1853
1854    pub fn background(&self) -> &Arc<executor::Background> {
1855        &self.background
1856    }
1857
1858    pub fn font_cache(&self) -> &Arc<FontCache> {
1859        &self.font_cache
1860    }
1861
1862    pub fn platform(&self) -> &Arc<dyn Platform> {
1863        &self.platform
1864    }
1865}
1866
1867impl ReadModel for AppContext {
1868    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1869        if let Some(model) = self.models.get(&handle.model_id) {
1870            model
1871                .as_any()
1872                .downcast_ref()
1873                .expect("downcast should be type safe")
1874        } else {
1875            panic!("circular model reference");
1876        }
1877    }
1878}
1879
1880impl UpgradeModelHandle for AppContext {
1881    fn upgrade_model_handle<T: Entity>(
1882        &self,
1883        handle: &WeakModelHandle<T>,
1884    ) -> Option<ModelHandle<T>> {
1885        if self.models.contains_key(&handle.model_id) {
1886            Some(ModelHandle::new(handle.model_id, &self.ref_counts))
1887        } else {
1888            None
1889        }
1890    }
1891}
1892
1893impl UpgradeViewHandle for AppContext {
1894    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
1895        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
1896            Some(ViewHandle::new(
1897                handle.window_id,
1898                handle.view_id,
1899                &self.ref_counts,
1900            ))
1901        } else {
1902            None
1903        }
1904    }
1905}
1906
1907impl ReadView for AppContext {
1908    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1909        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
1910            view.as_any()
1911                .downcast_ref()
1912                .expect("downcast should be type safe")
1913        } else {
1914            panic!("circular view reference");
1915        }
1916    }
1917}
1918
1919struct Window {
1920    root_view: AnyViewHandle,
1921    focused_view_id: usize,
1922    invalidation: Option<WindowInvalidation>,
1923}
1924
1925#[derive(Default, Clone)]
1926pub struct WindowInvalidation {
1927    pub updated: HashSet<usize>,
1928    pub removed: Vec<usize>,
1929}
1930
1931pub enum Effect {
1932    Event {
1933        entity_id: usize,
1934        payload: Box<dyn Any>,
1935    },
1936    ModelNotification {
1937        model_id: usize,
1938    },
1939    ViewNotification {
1940        window_id: usize,
1941        view_id: usize,
1942    },
1943    Deferred(Box<dyn FnOnce(&mut MutableAppContext)>),
1944    Release {
1945        entity_id: usize,
1946    },
1947    Focus {
1948        window_id: usize,
1949        view_id: usize,
1950    },
1951    ResizeWindow {
1952        window_id: usize,
1953    },
1954    RefreshWindows,
1955}
1956
1957impl Debug for Effect {
1958    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1959        match self {
1960            Effect::Event { entity_id, .. } => f
1961                .debug_struct("Effect::Event")
1962                .field("entity_id", entity_id)
1963                .finish(),
1964            Effect::ModelNotification { model_id } => f
1965                .debug_struct("Effect::ModelNotification")
1966                .field("model_id", model_id)
1967                .finish(),
1968            Effect::ViewNotification { window_id, view_id } => f
1969                .debug_struct("Effect::ViewNotification")
1970                .field("window_id", window_id)
1971                .field("view_id", view_id)
1972                .finish(),
1973            Effect::Deferred(_) => f.debug_struct("Effect::Deferred").finish(),
1974            Effect::Release { entity_id } => f
1975                .debug_struct("Effect::Release")
1976                .field("entity_id", entity_id)
1977                .finish(),
1978            Effect::Focus { window_id, view_id } => f
1979                .debug_struct("Effect::Focus")
1980                .field("window_id", window_id)
1981                .field("view_id", view_id)
1982                .finish(),
1983            Effect::ResizeWindow { window_id } => f
1984                .debug_struct("Effect::RefreshWindow")
1985                .field("window_id", window_id)
1986                .finish(),
1987            Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
1988        }
1989    }
1990}
1991
1992pub trait AnyModel {
1993    fn as_any(&self) -> &dyn Any;
1994    fn as_any_mut(&mut self) -> &mut dyn Any;
1995    fn release(&mut self, cx: &mut MutableAppContext);
1996    fn app_will_quit(
1997        &mut self,
1998        cx: &mut MutableAppContext,
1999    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2000}
2001
2002impl<T> AnyModel for T
2003where
2004    T: Entity,
2005{
2006    fn as_any(&self) -> &dyn Any {
2007        self
2008    }
2009
2010    fn as_any_mut(&mut self) -> &mut dyn Any {
2011        self
2012    }
2013
2014    fn release(&mut self, cx: &mut MutableAppContext) {
2015        self.release(cx);
2016    }
2017
2018    fn app_will_quit(
2019        &mut self,
2020        cx: &mut MutableAppContext,
2021    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2022        self.app_will_quit(cx)
2023    }
2024}
2025
2026pub trait AnyView {
2027    fn as_any(&self) -> &dyn Any;
2028    fn as_any_mut(&mut self) -> &mut dyn Any;
2029    fn release(&mut self, cx: &mut MutableAppContext);
2030    fn app_will_quit(
2031        &mut self,
2032        cx: &mut MutableAppContext,
2033    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2034    fn ui_name(&self) -> &'static str;
2035    fn render<'a>(
2036        &mut self,
2037        window_id: usize,
2038        view_id: usize,
2039        titlebar_height: f32,
2040        refreshing: bool,
2041        cx: &mut MutableAppContext,
2042    ) -> ElementBox;
2043    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
2044    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
2045    fn keymap_context(&self, cx: &AppContext) -> keymap::Context;
2046}
2047
2048impl<T> AnyView for T
2049where
2050    T: View,
2051{
2052    fn as_any(&self) -> &dyn Any {
2053        self
2054    }
2055
2056    fn as_any_mut(&mut self) -> &mut dyn Any {
2057        self
2058    }
2059
2060    fn release(&mut self, cx: &mut MutableAppContext) {
2061        self.release(cx);
2062    }
2063
2064    fn app_will_quit(
2065        &mut self,
2066        cx: &mut MutableAppContext,
2067    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2068        self.app_will_quit(cx)
2069    }
2070
2071    fn ui_name(&self) -> &'static str {
2072        T::ui_name()
2073    }
2074
2075    fn render<'a>(
2076        &mut self,
2077        window_id: usize,
2078        view_id: usize,
2079        titlebar_height: f32,
2080        refreshing: bool,
2081        cx: &mut MutableAppContext,
2082    ) -> ElementBox {
2083        View::render(
2084            self,
2085            &mut RenderContext {
2086                window_id,
2087                view_id,
2088                app: cx,
2089                view_type: PhantomData::<T>,
2090                titlebar_height,
2091                refreshing,
2092            },
2093        )
2094    }
2095
2096    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
2097        let mut cx = ViewContext::new(cx, window_id, view_id);
2098        View::on_focus(self, &mut cx);
2099    }
2100
2101    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
2102        let mut cx = ViewContext::new(cx, window_id, view_id);
2103        View::on_blur(self, &mut cx);
2104    }
2105
2106    fn keymap_context(&self, cx: &AppContext) -> keymap::Context {
2107        View::keymap_context(self, cx)
2108    }
2109}
2110
2111pub struct ModelContext<'a, T: ?Sized> {
2112    app: &'a mut MutableAppContext,
2113    model_id: usize,
2114    model_type: PhantomData<T>,
2115    halt_stream: bool,
2116}
2117
2118impl<'a, T: Entity> ModelContext<'a, T> {
2119    fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
2120        Self {
2121            app,
2122            model_id,
2123            model_type: PhantomData,
2124            halt_stream: false,
2125        }
2126    }
2127
2128    pub fn background(&self) -> &Arc<executor::Background> {
2129        &self.app.cx.background
2130    }
2131
2132    pub fn halt_stream(&mut self) {
2133        self.halt_stream = true;
2134    }
2135
2136    pub fn model_id(&self) -> usize {
2137        self.model_id
2138    }
2139
2140    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2141    where
2142        S: Entity,
2143        F: FnOnce(&mut ModelContext<S>) -> S,
2144    {
2145        self.app.add_model(build_model)
2146    }
2147
2148    pub fn emit(&mut self, payload: T::Event) {
2149        self.app.pending_effects.push_back(Effect::Event {
2150            entity_id: self.model_id,
2151            payload: Box::new(payload),
2152        });
2153    }
2154
2155    pub fn notify(&mut self) {
2156        self.app.notify_model(self.model_id);
2157    }
2158
2159    pub fn subscribe<S: Entity, F>(
2160        &mut self,
2161        handle: &ModelHandle<S>,
2162        mut callback: F,
2163    ) -> Subscription
2164    where
2165        S::Event: 'static,
2166        F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
2167    {
2168        let subscriber = self.weak_handle();
2169        self.app
2170            .subscribe_internal(handle, move |emitter, event, cx| {
2171                if let Some(subscriber) = subscriber.upgrade(cx) {
2172                    subscriber.update(cx, |subscriber, cx| {
2173                        callback(subscriber, emitter, event, cx);
2174                    });
2175                    true
2176                } else {
2177                    false
2178                }
2179            })
2180    }
2181
2182    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
2183    where
2184        S: Entity,
2185        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
2186    {
2187        let observer = self.weak_handle();
2188        self.app.observe_internal(handle, move |observed, cx| {
2189            if let Some(observer) = observer.upgrade(cx) {
2190                observer.update(cx, |observer, cx| {
2191                    callback(observer, observed, cx);
2192                });
2193                true
2194            } else {
2195                false
2196            }
2197        })
2198    }
2199
2200    pub fn observe_release<S, F>(
2201        &mut self,
2202        handle: &ModelHandle<S>,
2203        mut callback: F,
2204    ) -> Subscription
2205    where
2206        S: Entity,
2207        F: 'static + FnMut(&mut T, &mut ModelContext<T>),
2208    {
2209        let observer = self.weak_handle();
2210        self.app.observe_release(handle, move |cx| {
2211            if let Some(observer) = observer.upgrade(cx) {
2212                observer.update(cx, |observer, cx| {
2213                    callback(observer, cx);
2214                });
2215            }
2216        })
2217    }
2218
2219    pub fn handle(&self) -> ModelHandle<T> {
2220        ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
2221    }
2222
2223    pub fn weak_handle(&self) -> WeakModelHandle<T> {
2224        WeakModelHandle::new(self.model_id)
2225    }
2226
2227    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2228    where
2229        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
2230        Fut: 'static + Future<Output = S>,
2231        S: 'static,
2232    {
2233        let handle = self.handle();
2234        self.app.spawn(|cx| f(handle, cx))
2235    }
2236
2237    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
2238    where
2239        F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
2240        Fut: 'static + Future<Output = S>,
2241        S: 'static,
2242    {
2243        let handle = self.weak_handle();
2244        self.app.spawn(|cx| f(handle, cx))
2245    }
2246}
2247
2248impl<M> AsRef<AppContext> for ModelContext<'_, M> {
2249    fn as_ref(&self) -> &AppContext {
2250        &self.app.cx
2251    }
2252}
2253
2254impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
2255    fn as_mut(&mut self) -> &mut MutableAppContext {
2256        self.app
2257    }
2258}
2259
2260impl<M> ReadModel for ModelContext<'_, M> {
2261    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2262        self.app.read_model(handle)
2263    }
2264}
2265
2266impl<M> UpdateModel for ModelContext<'_, M> {
2267    fn update_model<T: Entity, V>(
2268        &mut self,
2269        handle: &ModelHandle<T>,
2270        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
2271    ) -> V {
2272        self.app.update_model(handle, update)
2273    }
2274}
2275
2276impl<M> UpgradeModelHandle for ModelContext<'_, M> {
2277    fn upgrade_model_handle<T: Entity>(
2278        &self,
2279        handle: &WeakModelHandle<T>,
2280    ) -> Option<ModelHandle<T>> {
2281        self.cx.upgrade_model_handle(handle)
2282    }
2283}
2284
2285impl<M> Deref for ModelContext<'_, M> {
2286    type Target = MutableAppContext;
2287
2288    fn deref(&self) -> &Self::Target {
2289        &self.app
2290    }
2291}
2292
2293impl<M> DerefMut for ModelContext<'_, M> {
2294    fn deref_mut(&mut self) -> &mut Self::Target {
2295        &mut self.app
2296    }
2297}
2298
2299pub struct ViewContext<'a, T: ?Sized> {
2300    app: &'a mut MutableAppContext,
2301    window_id: usize,
2302    view_id: usize,
2303    view_type: PhantomData<T>,
2304    halt_action_dispatch: bool,
2305}
2306
2307impl<'a, T: View> ViewContext<'a, T> {
2308    fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
2309        Self {
2310            app,
2311            window_id,
2312            view_id,
2313            view_type: PhantomData,
2314            halt_action_dispatch: true,
2315        }
2316    }
2317
2318    pub fn handle(&self) -> ViewHandle<T> {
2319        ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
2320    }
2321
2322    pub fn weak_handle(&self) -> WeakViewHandle<T> {
2323        WeakViewHandle::new(self.window_id, self.view_id)
2324    }
2325
2326    pub fn window_id(&self) -> usize {
2327        self.window_id
2328    }
2329
2330    pub fn view_id(&self) -> usize {
2331        self.view_id
2332    }
2333
2334    pub fn foreground(&self) -> &Rc<executor::Foreground> {
2335        self.app.foreground()
2336    }
2337
2338    pub fn background_executor(&self) -> &Arc<executor::Background> {
2339        &self.app.cx.background
2340    }
2341
2342    pub fn platform(&self) -> Arc<dyn Platform> {
2343        self.app.platform()
2344    }
2345
2346    pub fn prompt(
2347        &self,
2348        level: PromptLevel,
2349        msg: &str,
2350        answers: &[&str],
2351    ) -> oneshot::Receiver<usize> {
2352        self.app.prompt(self.window_id, level, msg, answers)
2353    }
2354
2355    pub fn prompt_for_paths(
2356        &self,
2357        options: PathPromptOptions,
2358    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2359        self.app.prompt_for_paths(options)
2360    }
2361
2362    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
2363        self.app.prompt_for_new_path(directory)
2364    }
2365
2366    pub fn debug_elements(&self) -> crate::json::Value {
2367        self.app.debug_elements(self.window_id).unwrap()
2368    }
2369
2370    pub fn focus<S>(&mut self, handle: S)
2371    where
2372        S: Into<AnyViewHandle>,
2373    {
2374        let handle = handle.into();
2375        self.app.pending_effects.push_back(Effect::Focus {
2376            window_id: handle.window_id,
2377            view_id: handle.view_id,
2378        });
2379    }
2380
2381    pub fn focus_self(&mut self) {
2382        self.app.pending_effects.push_back(Effect::Focus {
2383            window_id: self.window_id,
2384            view_id: self.view_id,
2385        });
2386    }
2387
2388    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2389    where
2390        S: Entity,
2391        F: FnOnce(&mut ModelContext<S>) -> S,
2392    {
2393        self.app.add_model(build_model)
2394    }
2395
2396    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
2397    where
2398        S: View,
2399        F: FnOnce(&mut ViewContext<S>) -> S,
2400    {
2401        self.app.add_view(self.window_id, build_view)
2402    }
2403
2404    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
2405    where
2406        S: View,
2407        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
2408    {
2409        self.app.add_option_view(self.window_id, build_view)
2410    }
2411
2412    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
2413    where
2414        E: Entity,
2415        E::Event: 'static,
2416        H: Handle<E>,
2417        F: 'static + FnMut(&mut T, H, &E::Event, &mut ViewContext<T>),
2418    {
2419        let subscriber = self.weak_handle();
2420        self.app
2421            .subscribe_internal(handle, move |emitter, event, cx| {
2422                if let Some(subscriber) = subscriber.upgrade(cx) {
2423                    subscriber.update(cx, |subscriber, cx| {
2424                        callback(subscriber, emitter, event, cx);
2425                    });
2426                    true
2427                } else {
2428                    false
2429                }
2430            })
2431    }
2432
2433    pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2434    where
2435        E: Entity,
2436        H: Handle<E>,
2437        F: 'static + FnMut(&mut T, H, &mut ViewContext<T>),
2438    {
2439        let observer = self.weak_handle();
2440        self.app.observe_internal(handle, move |observed, cx| {
2441            if let Some(observer) = observer.upgrade(cx) {
2442                observer.update(cx, |observer, cx| {
2443                    callback(observer, observed, cx);
2444                });
2445                true
2446            } else {
2447                false
2448            }
2449        })
2450    }
2451
2452    pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2453    where
2454        E: Entity,
2455        H: Handle<E>,
2456        F: 'static + FnMut(&mut T, &mut ViewContext<T>),
2457    {
2458        let observer = self.weak_handle();
2459        self.app.observe_release(handle, move |cx| {
2460            if let Some(observer) = observer.upgrade(cx) {
2461                observer.update(cx, |observer, cx| {
2462                    callback(observer, cx);
2463                });
2464            }
2465        })
2466    }
2467
2468    pub fn emit(&mut self, payload: T::Event) {
2469        self.app.pending_effects.push_back(Effect::Event {
2470            entity_id: self.view_id,
2471            payload: Box::new(payload),
2472        });
2473    }
2474
2475    pub fn notify(&mut self) {
2476        self.app.notify_view(self.window_id, self.view_id);
2477    }
2478
2479    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>)) {
2480        let handle = self.handle();
2481        self.app.defer(Box::new(move |cx| {
2482            handle.update(cx, |view, cx| {
2483                callback(view, cx);
2484            })
2485        }))
2486    }
2487
2488    pub fn propagate_action(&mut self) {
2489        self.halt_action_dispatch = false;
2490    }
2491
2492    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2493    where
2494        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
2495        Fut: 'static + Future<Output = S>,
2496        S: 'static,
2497    {
2498        let handle = self.handle();
2499        self.app.spawn(|cx| f(handle, cx))
2500    }
2501
2502    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
2503    where
2504        F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut,
2505        Fut: 'static + Future<Output = S>,
2506        S: 'static,
2507    {
2508        let handle = self.weak_handle();
2509        self.app.spawn(|cx| f(handle, cx))
2510    }
2511}
2512
2513pub struct RenderContext<'a, T: View> {
2514    pub app: &'a mut MutableAppContext,
2515    pub titlebar_height: f32,
2516    pub refreshing: bool,
2517    window_id: usize,
2518    view_id: usize,
2519    view_type: PhantomData<T>,
2520}
2521
2522impl<'a, T: View> RenderContext<'a, T> {
2523    pub fn handle(&self) -> WeakViewHandle<T> {
2524        WeakViewHandle::new(self.window_id, self.view_id)
2525    }
2526
2527    pub fn view_id(&self) -> usize {
2528        self.view_id
2529    }
2530}
2531
2532impl AsRef<AppContext> for &AppContext {
2533    fn as_ref(&self) -> &AppContext {
2534        self
2535    }
2536}
2537
2538impl<V: View> Deref for RenderContext<'_, V> {
2539    type Target = MutableAppContext;
2540
2541    fn deref(&self) -> &Self::Target {
2542        self.app
2543    }
2544}
2545
2546impl<V: View> DerefMut for RenderContext<'_, V> {
2547    fn deref_mut(&mut self) -> &mut Self::Target {
2548        self.app
2549    }
2550}
2551
2552impl<V: View> ReadModel for RenderContext<'_, V> {
2553    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2554        self.app.read_model(handle)
2555    }
2556}
2557
2558impl<V: View> UpdateModel for RenderContext<'_, V> {
2559    fn update_model<T: Entity, O>(
2560        &mut self,
2561        handle: &ModelHandle<T>,
2562        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
2563    ) -> O {
2564        self.app.update_model(handle, update)
2565    }
2566}
2567
2568impl<V: View> ReadView for RenderContext<'_, V> {
2569    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2570        self.app.read_view(handle)
2571    }
2572}
2573
2574impl<M> AsRef<AppContext> for ViewContext<'_, M> {
2575    fn as_ref(&self) -> &AppContext {
2576        &self.app.cx
2577    }
2578}
2579
2580impl<M> Deref for ViewContext<'_, M> {
2581    type Target = MutableAppContext;
2582
2583    fn deref(&self) -> &Self::Target {
2584        &self.app
2585    }
2586}
2587
2588impl<M> DerefMut for ViewContext<'_, M> {
2589    fn deref_mut(&mut self) -> &mut Self::Target {
2590        &mut self.app
2591    }
2592}
2593
2594impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
2595    fn as_mut(&mut self) -> &mut MutableAppContext {
2596        self.app
2597    }
2598}
2599
2600impl<V> ReadModel for ViewContext<'_, V> {
2601    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2602        self.app.read_model(handle)
2603    }
2604}
2605
2606impl<V> UpgradeModelHandle for ViewContext<'_, V> {
2607    fn upgrade_model_handle<T: Entity>(
2608        &self,
2609        handle: &WeakModelHandle<T>,
2610    ) -> Option<ModelHandle<T>> {
2611        self.cx.upgrade_model_handle(handle)
2612    }
2613}
2614
2615impl<V> UpgradeViewHandle for ViewContext<'_, V> {
2616    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2617        self.cx.upgrade_view_handle(handle)
2618    }
2619}
2620
2621impl<V: View> UpdateModel for ViewContext<'_, V> {
2622    fn update_model<T: Entity, O>(
2623        &mut self,
2624        handle: &ModelHandle<T>,
2625        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
2626    ) -> O {
2627        self.app.update_model(handle, update)
2628    }
2629}
2630
2631impl<V: View> ReadView for ViewContext<'_, V> {
2632    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2633        self.app.read_view(handle)
2634    }
2635}
2636
2637impl<V: View> UpdateView for ViewContext<'_, V> {
2638    fn update_view<T, S>(
2639        &mut self,
2640        handle: &ViewHandle<T>,
2641        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
2642    ) -> S
2643    where
2644        T: View,
2645    {
2646        self.app.update_view(handle, update)
2647    }
2648}
2649
2650pub trait Handle<T> {
2651    type Weak: 'static;
2652    fn id(&self) -> usize;
2653    fn location(&self) -> EntityLocation;
2654    fn downgrade(&self) -> Self::Weak;
2655    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2656    where
2657        Self: Sized;
2658}
2659
2660#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
2661pub enum EntityLocation {
2662    Model(usize),
2663    View(usize, usize),
2664}
2665
2666pub struct ModelHandle<T> {
2667    model_id: usize,
2668    model_type: PhantomData<T>,
2669    ref_counts: Arc<Mutex<RefCounts>>,
2670}
2671
2672impl<T: Entity> ModelHandle<T> {
2673    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2674        ref_counts.lock().inc_model(model_id);
2675        Self {
2676            model_id,
2677            model_type: PhantomData,
2678            ref_counts: ref_counts.clone(),
2679        }
2680    }
2681
2682    pub fn downgrade(&self) -> WeakModelHandle<T> {
2683        WeakModelHandle::new(self.model_id)
2684    }
2685
2686    pub fn id(&self) -> usize {
2687        self.model_id
2688    }
2689
2690    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
2691        cx.read_model(self)
2692    }
2693
2694    pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
2695    where
2696        C: ReadModelWith,
2697        F: FnOnce(&T, &AppContext) -> S,
2698    {
2699        let mut read = Some(read);
2700        cx.read_model_with(self, &mut |model, cx| {
2701            let read = read.take().unwrap();
2702            read(model, cx)
2703        })
2704    }
2705
2706    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2707    where
2708        C: UpdateModel,
2709        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2710    {
2711        let mut update = Some(update);
2712        cx.update_model(self, &mut |model, cx| {
2713            let update = update.take().unwrap();
2714            update(model, cx)
2715        })
2716    }
2717
2718    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
2719        let (mut tx, mut rx) = mpsc::channel(1);
2720        let mut cx = cx.cx.borrow_mut();
2721        let subscription = cx.observe(self, move |_, _| {
2722            tx.try_send(()).ok();
2723        });
2724
2725        let duration = if std::env::var("CI").is_ok() {
2726            Duration::from_secs(5)
2727        } else {
2728            Duration::from_secs(1)
2729        };
2730
2731        async move {
2732            let notification = timeout(duration, rx.recv())
2733                .await
2734                .expect("next notification timed out");
2735            drop(subscription);
2736            notification.expect("model dropped while test was waiting for its next notification")
2737        }
2738    }
2739
2740    pub fn next_event(&self, cx: &TestAppContext) -> impl Future<Output = T::Event>
2741    where
2742        T::Event: Clone,
2743    {
2744        let (mut tx, mut rx) = mpsc::channel(1);
2745        let mut cx = cx.cx.borrow_mut();
2746        let subscription = cx.subscribe(self, move |_, event, _| {
2747            tx.blocking_send(event.clone()).ok();
2748        });
2749
2750        let duration = if std::env::var("CI").is_ok() {
2751            Duration::from_secs(5)
2752        } else {
2753            Duration::from_secs(1)
2754        };
2755
2756        async move {
2757            let event = timeout(duration, rx.recv())
2758                .await
2759                .expect("next event timed out");
2760            drop(subscription);
2761            event.expect("model dropped while test was waiting for its next event")
2762        }
2763    }
2764
2765    pub fn condition(
2766        &self,
2767        cx: &TestAppContext,
2768        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2769    ) -> impl Future<Output = ()> {
2770        let (tx, mut rx) = mpsc::channel(1024);
2771
2772        let mut cx = cx.cx.borrow_mut();
2773        let subscriptions = (
2774            cx.observe(self, {
2775                let mut tx = tx.clone();
2776                move |_, _| {
2777                    tx.blocking_send(()).ok();
2778                }
2779            }),
2780            cx.subscribe(self, {
2781                let mut tx = tx.clone();
2782                move |_, _, _| {
2783                    tx.blocking_send(()).ok();
2784                }
2785            }),
2786        );
2787
2788        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2789        let handle = self.downgrade();
2790        let duration = if std::env::var("CI").is_ok() {
2791            Duration::from_secs(5)
2792        } else {
2793            Duration::from_secs(1)
2794        };
2795
2796        async move {
2797            timeout(duration, async move {
2798                loop {
2799                    {
2800                        let cx = cx.borrow();
2801                        let cx = cx.as_ref();
2802                        if predicate(
2803                            handle
2804                                .upgrade(cx)
2805                                .expect("model dropped with pending condition")
2806                                .read(cx),
2807                            cx,
2808                        ) {
2809                            break;
2810                        }
2811                    }
2812
2813                    cx.borrow().foreground().start_waiting();
2814                    rx.recv()
2815                        .await
2816                        .expect("model dropped with pending condition");
2817                    cx.borrow().foreground().finish_waiting();
2818                }
2819            })
2820            .await
2821            .expect("condition timed out");
2822            drop(subscriptions);
2823        }
2824    }
2825}
2826
2827impl<T> Clone for ModelHandle<T> {
2828    fn clone(&self) -> Self {
2829        self.ref_counts.lock().inc_model(self.model_id);
2830        Self {
2831            model_id: self.model_id,
2832            model_type: PhantomData,
2833            ref_counts: self.ref_counts.clone(),
2834        }
2835    }
2836}
2837
2838impl<T> PartialEq for ModelHandle<T> {
2839    fn eq(&self, other: &Self) -> bool {
2840        self.model_id == other.model_id
2841    }
2842}
2843
2844impl<T> Eq for ModelHandle<T> {}
2845
2846impl<T> Hash for ModelHandle<T> {
2847    fn hash<H: Hasher>(&self, state: &mut H) {
2848        self.model_id.hash(state);
2849    }
2850}
2851
2852impl<T> std::borrow::Borrow<usize> for ModelHandle<T> {
2853    fn borrow(&self) -> &usize {
2854        &self.model_id
2855    }
2856}
2857
2858impl<T> Debug for ModelHandle<T> {
2859    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2860        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
2861            .field(&self.model_id)
2862            .finish()
2863    }
2864}
2865
2866unsafe impl<T> Send for ModelHandle<T> {}
2867unsafe impl<T> Sync for ModelHandle<T> {}
2868
2869impl<T> Drop for ModelHandle<T> {
2870    fn drop(&mut self) {
2871        self.ref_counts.lock().dec_model(self.model_id);
2872    }
2873}
2874
2875impl<T: Entity> Handle<T> for ModelHandle<T> {
2876    type Weak = WeakModelHandle<T>;
2877
2878    fn id(&self) -> usize {
2879        self.model_id
2880    }
2881
2882    fn location(&self) -> EntityLocation {
2883        EntityLocation::Model(self.model_id)
2884    }
2885
2886    fn downgrade(&self) -> Self::Weak {
2887        self.downgrade()
2888    }
2889
2890    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2891    where
2892        Self: Sized,
2893    {
2894        weak.upgrade(cx)
2895    }
2896}
2897
2898pub struct WeakModelHandle<T> {
2899    model_id: usize,
2900    model_type: PhantomData<T>,
2901}
2902
2903unsafe impl<T> Send for WeakModelHandle<T> {}
2904unsafe impl<T> Sync for WeakModelHandle<T> {}
2905
2906impl<T: Entity> WeakModelHandle<T> {
2907    fn new(model_id: usize) -> Self {
2908        Self {
2909            model_id,
2910            model_type: PhantomData,
2911        }
2912    }
2913
2914    pub fn id(&self) -> usize {
2915        self.model_id
2916    }
2917
2918    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
2919        cx.upgrade_model_handle(self)
2920    }
2921}
2922
2923impl<T> Hash for WeakModelHandle<T> {
2924    fn hash<H: Hasher>(&self, state: &mut H) {
2925        self.model_id.hash(state)
2926    }
2927}
2928
2929impl<T> PartialEq for WeakModelHandle<T> {
2930    fn eq(&self, other: &Self) -> bool {
2931        self.model_id == other.model_id
2932    }
2933}
2934
2935impl<T> Eq for WeakModelHandle<T> {}
2936
2937impl<T> Clone for WeakModelHandle<T> {
2938    fn clone(&self) -> Self {
2939        Self {
2940            model_id: self.model_id,
2941            model_type: PhantomData,
2942        }
2943    }
2944}
2945
2946impl<T> Copy for WeakModelHandle<T> {}
2947
2948pub struct ViewHandle<T> {
2949    window_id: usize,
2950    view_id: usize,
2951    view_type: PhantomData<T>,
2952    ref_counts: Arc<Mutex<RefCounts>>,
2953}
2954
2955impl<T: View> ViewHandle<T> {
2956    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2957        ref_counts.lock().inc_view(window_id, view_id);
2958        Self {
2959            window_id,
2960            view_id,
2961            view_type: PhantomData,
2962            ref_counts: ref_counts.clone(),
2963        }
2964    }
2965
2966    pub fn downgrade(&self) -> WeakViewHandle<T> {
2967        WeakViewHandle::new(self.window_id, self.view_id)
2968    }
2969
2970    pub fn window_id(&self) -> usize {
2971        self.window_id
2972    }
2973
2974    pub fn id(&self) -> usize {
2975        self.view_id
2976    }
2977
2978    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
2979        cx.read_view(self)
2980    }
2981
2982    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
2983    where
2984        C: ReadViewWith,
2985        F: FnOnce(&T, &AppContext) -> S,
2986    {
2987        let mut read = Some(read);
2988        cx.read_view_with(self, &mut |view, cx| {
2989            let read = read.take().unwrap();
2990            read(view, cx)
2991        })
2992    }
2993
2994    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2995    where
2996        C: UpdateView,
2997        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2998    {
2999        let mut update = Some(update);
3000        cx.update_view(self, &mut |view, cx| {
3001            let update = update.take().unwrap();
3002            update(view, cx)
3003        })
3004    }
3005
3006    pub fn defer<C, F>(&self, cx: &mut C, update: F)
3007    where
3008        C: AsMut<MutableAppContext>,
3009        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
3010    {
3011        let this = self.clone();
3012        cx.as_mut().defer(Box::new(move |cx| {
3013            this.update(cx, |view, cx| update(view, cx));
3014        }));
3015    }
3016
3017    pub fn is_focused(&self, cx: &AppContext) -> bool {
3018        cx.focused_view_id(self.window_id)
3019            .map_or(false, |focused_id| focused_id == self.view_id)
3020    }
3021
3022    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
3023        let (mut tx, mut rx) = mpsc::channel(1);
3024        let mut cx = cx.cx.borrow_mut();
3025        let subscription = cx.observe(self, move |_, _| {
3026            tx.try_send(()).ok();
3027        });
3028
3029        let duration = if std::env::var("CI").is_ok() {
3030            Duration::from_secs(5)
3031        } else {
3032            Duration::from_secs(1)
3033        };
3034
3035        async move {
3036            let notification = timeout(duration, rx.recv())
3037                .await
3038                .expect("next notification timed out");
3039            drop(subscription);
3040            notification.expect("model dropped while test was waiting for its next notification")
3041        }
3042    }
3043
3044    pub fn condition(
3045        &self,
3046        cx: &TestAppContext,
3047        mut predicate: impl FnMut(&T, &AppContext) -> bool,
3048    ) -> impl Future<Output = ()> {
3049        let (tx, mut rx) = mpsc::channel(1024);
3050
3051        let mut cx = cx.cx.borrow_mut();
3052        let subscriptions = self.update(&mut *cx, |_, cx| {
3053            (
3054                cx.observe(self, {
3055                    let mut tx = tx.clone();
3056                    move |_, _, _| {
3057                        tx.blocking_send(()).ok();
3058                    }
3059                }),
3060                cx.subscribe(self, {
3061                    let mut tx = tx.clone();
3062                    move |_, _, _, _| {
3063                        tx.blocking_send(()).ok();
3064                    }
3065                }),
3066            )
3067        });
3068
3069        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
3070        let handle = self.downgrade();
3071        let duration = if std::env::var("CI").is_ok() {
3072            Duration::from_secs(2)
3073        } else {
3074            Duration::from_millis(500)
3075        };
3076
3077        async move {
3078            timeout(duration, async move {
3079                loop {
3080                    {
3081                        let cx = cx.borrow();
3082                        let cx = cx.as_ref();
3083                        if predicate(
3084                            handle
3085                                .upgrade(cx)
3086                                .expect("view dropped with pending condition")
3087                                .read(cx),
3088                            cx,
3089                        ) {
3090                            break;
3091                        }
3092                    }
3093
3094                    cx.borrow().foreground().start_waiting();
3095                    rx.recv()
3096                        .await
3097                        .expect("view dropped with pending condition");
3098                    cx.borrow().foreground().finish_waiting();
3099                }
3100            })
3101            .await
3102            .expect("condition timed out");
3103            drop(subscriptions);
3104        }
3105    }
3106}
3107
3108impl<T> Clone for ViewHandle<T> {
3109    fn clone(&self) -> Self {
3110        self.ref_counts
3111            .lock()
3112            .inc_view(self.window_id, self.view_id);
3113        Self {
3114            window_id: self.window_id,
3115            view_id: self.view_id,
3116            view_type: PhantomData,
3117            ref_counts: self.ref_counts.clone(),
3118        }
3119    }
3120}
3121
3122impl<T> PartialEq for ViewHandle<T> {
3123    fn eq(&self, other: &Self) -> bool {
3124        self.window_id == other.window_id && self.view_id == other.view_id
3125    }
3126}
3127
3128impl<T> Eq for ViewHandle<T> {}
3129
3130impl<T> Debug for ViewHandle<T> {
3131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3132        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
3133            .field("window_id", &self.window_id)
3134            .field("view_id", &self.view_id)
3135            .finish()
3136    }
3137}
3138
3139impl<T> Drop for ViewHandle<T> {
3140    fn drop(&mut self) {
3141        self.ref_counts
3142            .lock()
3143            .dec_view(self.window_id, self.view_id);
3144    }
3145}
3146
3147impl<T: View> Handle<T> for ViewHandle<T> {
3148    type Weak = WeakViewHandle<T>;
3149
3150    fn id(&self) -> usize {
3151        self.view_id
3152    }
3153
3154    fn location(&self) -> EntityLocation {
3155        EntityLocation::View(self.window_id, self.view_id)
3156    }
3157
3158    fn downgrade(&self) -> Self::Weak {
3159        self.downgrade()
3160    }
3161
3162    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3163    where
3164        Self: Sized,
3165    {
3166        weak.upgrade(cx)
3167    }
3168}
3169
3170pub struct AnyViewHandle {
3171    window_id: usize,
3172    view_id: usize,
3173    view_type: TypeId,
3174    ref_counts: Arc<Mutex<RefCounts>>,
3175}
3176
3177impl AnyViewHandle {
3178    pub fn id(&self) -> usize {
3179        self.view_id
3180    }
3181
3182    pub fn is<T: 'static>(&self) -> bool {
3183        TypeId::of::<T>() == self.view_type
3184    }
3185
3186    pub fn is_focused(&self, cx: &AppContext) -> bool {
3187        cx.focused_view_id(self.window_id)
3188            .map_or(false, |focused_id| focused_id == self.view_id)
3189    }
3190
3191    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
3192        if self.is::<T>() {
3193            let result = Some(ViewHandle {
3194                window_id: self.window_id,
3195                view_id: self.view_id,
3196                ref_counts: self.ref_counts.clone(),
3197                view_type: PhantomData,
3198            });
3199            unsafe {
3200                Arc::decrement_strong_count(&self.ref_counts);
3201            }
3202            std::mem::forget(self);
3203            result
3204        } else {
3205            None
3206        }
3207    }
3208}
3209
3210impl Clone for AnyViewHandle {
3211    fn clone(&self) -> Self {
3212        self.ref_counts
3213            .lock()
3214            .inc_view(self.window_id, self.view_id);
3215        Self {
3216            window_id: self.window_id,
3217            view_id: self.view_id,
3218            view_type: self.view_type,
3219            ref_counts: self.ref_counts.clone(),
3220        }
3221    }
3222}
3223
3224impl From<&AnyViewHandle> for AnyViewHandle {
3225    fn from(handle: &AnyViewHandle) -> Self {
3226        handle.clone()
3227    }
3228}
3229
3230impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
3231    fn from(handle: &ViewHandle<T>) -> Self {
3232        handle
3233            .ref_counts
3234            .lock()
3235            .inc_view(handle.window_id, handle.view_id);
3236        AnyViewHandle {
3237            window_id: handle.window_id,
3238            view_id: handle.view_id,
3239            view_type: TypeId::of::<T>(),
3240            ref_counts: handle.ref_counts.clone(),
3241        }
3242    }
3243}
3244
3245impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
3246    fn from(handle: ViewHandle<T>) -> Self {
3247        let any_handle = AnyViewHandle {
3248            window_id: handle.window_id,
3249            view_id: handle.view_id,
3250            view_type: TypeId::of::<T>(),
3251            ref_counts: handle.ref_counts.clone(),
3252        };
3253        unsafe {
3254            Arc::decrement_strong_count(&handle.ref_counts);
3255        }
3256        std::mem::forget(handle);
3257        any_handle
3258    }
3259}
3260
3261impl Drop for AnyViewHandle {
3262    fn drop(&mut self) {
3263        self.ref_counts
3264            .lock()
3265            .dec_view(self.window_id, self.view_id);
3266    }
3267}
3268
3269pub struct AnyModelHandle {
3270    model_id: usize,
3271    model_type: TypeId,
3272    ref_counts: Arc<Mutex<RefCounts>>,
3273}
3274
3275impl AnyModelHandle {
3276    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
3277        if self.is::<T>() {
3278            let result = Some(ModelHandle {
3279                model_id: self.model_id,
3280                model_type: PhantomData,
3281                ref_counts: self.ref_counts.clone(),
3282            });
3283            unsafe {
3284                Arc::decrement_strong_count(&self.ref_counts);
3285            }
3286            std::mem::forget(self);
3287            result
3288        } else {
3289            None
3290        }
3291    }
3292
3293    pub fn is<T: Entity>(&self) -> bool {
3294        self.model_type == TypeId::of::<T>()
3295    }
3296}
3297
3298impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
3299    fn from(handle: ModelHandle<T>) -> Self {
3300        handle.ref_counts.lock().inc_model(handle.model_id);
3301        Self {
3302            model_id: handle.model_id,
3303            model_type: TypeId::of::<T>(),
3304            ref_counts: handle.ref_counts.clone(),
3305        }
3306    }
3307}
3308
3309impl Drop for AnyModelHandle {
3310    fn drop(&mut self) {
3311        self.ref_counts.lock().dec_model(self.model_id);
3312    }
3313}
3314
3315pub struct WeakViewHandle<T> {
3316    window_id: usize,
3317    view_id: usize,
3318    view_type: PhantomData<T>,
3319}
3320
3321impl<T: View> WeakViewHandle<T> {
3322    fn new(window_id: usize, view_id: usize) -> Self {
3323        Self {
3324            window_id,
3325            view_id,
3326            view_type: PhantomData,
3327        }
3328    }
3329
3330    pub fn id(&self) -> usize {
3331        self.view_id
3332    }
3333
3334    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
3335        cx.upgrade_view_handle(self)
3336    }
3337}
3338
3339impl<T> Clone for WeakViewHandle<T> {
3340    fn clone(&self) -> Self {
3341        Self {
3342            window_id: self.window_id,
3343            view_id: self.view_id,
3344            view_type: PhantomData,
3345        }
3346    }
3347}
3348
3349impl<T> PartialEq for WeakViewHandle<T> {
3350    fn eq(&self, other: &Self) -> bool {
3351        self.window_id == other.window_id && self.view_id == other.view_id
3352    }
3353}
3354
3355impl<T> Eq for WeakViewHandle<T> {}
3356
3357impl<T> Hash for WeakViewHandle<T> {
3358    fn hash<H: Hasher>(&self, state: &mut H) {
3359        self.window_id.hash(state);
3360        self.view_id.hash(state);
3361    }
3362}
3363
3364#[derive(Clone, Copy, PartialEq, Eq, Hash)]
3365pub struct ElementStateId(usize, usize);
3366
3367impl From<usize> for ElementStateId {
3368    fn from(id: usize) -> Self {
3369        Self(id, 0)
3370    }
3371}
3372
3373impl From<(usize, usize)> for ElementStateId {
3374    fn from(id: (usize, usize)) -> Self {
3375        Self(id.0, id.1)
3376    }
3377}
3378
3379pub struct ElementStateHandle<T> {
3380    value_type: PhantomData<T>,
3381    tag_type_id: TypeId,
3382    id: ElementStateId,
3383    ref_counts: Weak<Mutex<RefCounts>>,
3384}
3385
3386impl<T: 'static> ElementStateHandle<T> {
3387    fn new(
3388        tag_type_id: TypeId,
3389        id: ElementStateId,
3390        frame_id: usize,
3391        ref_counts: &Arc<Mutex<RefCounts>>,
3392    ) -> Self {
3393        ref_counts
3394            .lock()
3395            .inc_element_state(tag_type_id, id, frame_id);
3396        Self {
3397            value_type: PhantomData,
3398            tag_type_id,
3399            id,
3400            ref_counts: Arc::downgrade(ref_counts),
3401        }
3402    }
3403
3404    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3405        cx.element_states
3406            .get(&(self.tag_type_id, self.id))
3407            .unwrap()
3408            .downcast_ref()
3409            .unwrap()
3410    }
3411
3412    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
3413    where
3414        C: DerefMut<Target = MutableAppContext>,
3415    {
3416        let mut element_state = cx
3417            .deref_mut()
3418            .cx
3419            .element_states
3420            .remove(&(self.tag_type_id, self.id))
3421            .unwrap();
3422        let result = f(element_state.downcast_mut().unwrap(), cx);
3423        cx.deref_mut()
3424            .cx
3425            .element_states
3426            .insert((self.tag_type_id, self.id), element_state);
3427        result
3428    }
3429}
3430
3431impl<T> Drop for ElementStateHandle<T> {
3432    fn drop(&mut self) {
3433        if let Some(ref_counts) = self.ref_counts.upgrade() {
3434            ref_counts
3435                .lock()
3436                .dec_element_state(self.tag_type_id, self.id);
3437        }
3438    }
3439}
3440
3441pub struct CursorStyleHandle {
3442    id: usize,
3443    next_cursor_style_handle_id: Arc<AtomicUsize>,
3444    platform: Arc<dyn Platform>,
3445}
3446
3447impl Drop for CursorStyleHandle {
3448    fn drop(&mut self) {
3449        if self.id + 1 == self.next_cursor_style_handle_id.load(SeqCst) {
3450            self.platform.set_cursor_style(CursorStyle::Arrow);
3451        }
3452    }
3453}
3454
3455#[must_use]
3456pub enum Subscription {
3457    Subscription {
3458        id: usize,
3459        entity_id: usize,
3460        subscriptions: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>>,
3461    },
3462    Observation {
3463        id: usize,
3464        entity_id: usize,
3465        observations: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ObservationCallback>>>>>,
3466    },
3467    ReleaseObservation {
3468        id: usize,
3469        entity_id: usize,
3470        observations:
3471            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>>,
3472    },
3473}
3474
3475impl Subscription {
3476    pub fn detach(&mut self) {
3477        match self {
3478            Subscription::Subscription { subscriptions, .. } => {
3479                subscriptions.take();
3480            }
3481            Subscription::Observation { observations, .. } => {
3482                observations.take();
3483            }
3484            Subscription::ReleaseObservation { observations, .. } => {
3485                observations.take();
3486            }
3487        }
3488    }
3489}
3490
3491impl Drop for Subscription {
3492    fn drop(&mut self) {
3493        match self {
3494            Subscription::Observation {
3495                id,
3496                entity_id,
3497                observations,
3498            } => {
3499                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3500                    if let Some(observations) = observations.lock().get_mut(entity_id) {
3501                        observations.remove(id);
3502                    }
3503                }
3504            }
3505            Subscription::ReleaseObservation {
3506                id,
3507                entity_id,
3508                observations,
3509            } => {
3510                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3511                    if let Some(observations) = observations.lock().get_mut(entity_id) {
3512                        observations.remove(id);
3513                    }
3514                }
3515            }
3516            Subscription::Subscription {
3517                id,
3518                entity_id,
3519                subscriptions,
3520            } => {
3521                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
3522                    if let Some(subscriptions) = subscriptions.lock().get_mut(entity_id) {
3523                        subscriptions.remove(id);
3524                    }
3525                }
3526            }
3527        }
3528    }
3529}
3530
3531#[derive(Default)]
3532struct RefCounts {
3533    entity_counts: HashMap<usize, usize>,
3534    element_state_counts: HashMap<(TypeId, ElementStateId), ElementStateRefCount>,
3535    dropped_models: HashSet<usize>,
3536    dropped_views: HashSet<(usize, usize)>,
3537    dropped_element_states: HashSet<(TypeId, ElementStateId)>,
3538}
3539
3540struct ElementStateRefCount {
3541    ref_count: usize,
3542    frame_id: usize,
3543}
3544
3545impl RefCounts {
3546    fn inc_model(&mut self, model_id: usize) {
3547        match self.entity_counts.entry(model_id) {
3548            Entry::Occupied(mut entry) => {
3549                *entry.get_mut() += 1;
3550            }
3551            Entry::Vacant(entry) => {
3552                entry.insert(1);
3553                self.dropped_models.remove(&model_id);
3554            }
3555        }
3556    }
3557
3558    fn inc_view(&mut self, window_id: usize, view_id: usize) {
3559        match self.entity_counts.entry(view_id) {
3560            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3561            Entry::Vacant(entry) => {
3562                entry.insert(1);
3563                self.dropped_views.remove(&(window_id, view_id));
3564            }
3565        }
3566    }
3567
3568    fn inc_element_state(&mut self, tag_type_id: TypeId, id: ElementStateId, frame_id: usize) {
3569        match self.element_state_counts.entry((tag_type_id, id)) {
3570            Entry::Occupied(mut entry) => {
3571                let entry = entry.get_mut();
3572                if entry.frame_id == frame_id || entry.ref_count >= 2 {
3573                    panic!("used the same element state more than once in the same frame");
3574                }
3575                entry.ref_count += 1;
3576                entry.frame_id = frame_id;
3577            }
3578            Entry::Vacant(entry) => {
3579                entry.insert(ElementStateRefCount {
3580                    ref_count: 1,
3581                    frame_id,
3582                });
3583                self.dropped_element_states.remove(&(tag_type_id, id));
3584            }
3585        }
3586    }
3587
3588    fn dec_model(&mut self, model_id: usize) {
3589        let count = self.entity_counts.get_mut(&model_id).unwrap();
3590        *count -= 1;
3591        if *count == 0 {
3592            self.entity_counts.remove(&model_id);
3593            self.dropped_models.insert(model_id);
3594        }
3595    }
3596
3597    fn dec_view(&mut self, window_id: usize, view_id: usize) {
3598        let count = self.entity_counts.get_mut(&view_id).unwrap();
3599        *count -= 1;
3600        if *count == 0 {
3601            self.entity_counts.remove(&view_id);
3602            self.dropped_views.insert((window_id, view_id));
3603        }
3604    }
3605
3606    fn dec_element_state(&mut self, tag_type_id: TypeId, id: ElementStateId) {
3607        let key = (tag_type_id, id);
3608        let entry = self.element_state_counts.get_mut(&key).unwrap();
3609        entry.ref_count -= 1;
3610        if entry.ref_count == 0 {
3611            self.element_state_counts.remove(&key);
3612            self.dropped_element_states.insert(key);
3613        }
3614    }
3615
3616    fn is_entity_alive(&self, entity_id: usize) -> bool {
3617        self.entity_counts.contains_key(&entity_id)
3618    }
3619
3620    fn take_dropped(
3621        &mut self,
3622    ) -> (
3623        HashSet<usize>,
3624        HashSet<(usize, usize)>,
3625        HashSet<(TypeId, ElementStateId)>,
3626    ) {
3627        (
3628            std::mem::take(&mut self.dropped_models),
3629            std::mem::take(&mut self.dropped_views),
3630            std::mem::take(&mut self.dropped_element_states),
3631        )
3632    }
3633}
3634
3635#[cfg(test)]
3636mod tests {
3637    use super::*;
3638    use crate::elements::*;
3639    use smol::future::poll_once;
3640    use std::{
3641        cell::Cell,
3642        sync::atomic::{AtomicUsize, Ordering::SeqCst},
3643    };
3644
3645    #[crate::test(self)]
3646    fn test_model_handles(cx: &mut MutableAppContext) {
3647        struct Model {
3648            other: Option<ModelHandle<Model>>,
3649            events: Vec<String>,
3650        }
3651
3652        impl Entity for Model {
3653            type Event = usize;
3654        }
3655
3656        impl Model {
3657            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
3658                if let Some(other) = other.as_ref() {
3659                    cx.observe(other, |me, _, _| {
3660                        me.events.push("notified".into());
3661                    })
3662                    .detach();
3663                    cx.subscribe(other, |me, _, event, _| {
3664                        me.events.push(format!("observed event {}", event));
3665                    })
3666                    .detach();
3667                }
3668
3669                Self {
3670                    other,
3671                    events: Vec::new(),
3672                }
3673            }
3674        }
3675
3676        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
3677        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
3678        assert_eq!(cx.cx.models.len(), 2);
3679
3680        handle_1.update(cx, |model, cx| {
3681            model.events.push("updated".into());
3682            cx.emit(1);
3683            cx.notify();
3684            cx.emit(2);
3685        });
3686        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3687        assert_eq!(
3688            handle_2.read(cx).events,
3689            vec![
3690                "observed event 1".to_string(),
3691                "notified".to_string(),
3692                "observed event 2".to_string(),
3693            ]
3694        );
3695
3696        handle_2.update(cx, |model, _| {
3697            drop(handle_1);
3698            model.other.take();
3699        });
3700
3701        assert_eq!(cx.cx.models.len(), 1);
3702        assert!(cx.subscriptions.lock().is_empty());
3703        assert!(cx.observations.lock().is_empty());
3704    }
3705
3706    #[crate::test(self)]
3707    fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) {
3708        #[derive(Default)]
3709        struct Model {
3710            events: Vec<usize>,
3711        }
3712
3713        impl Entity for Model {
3714            type Event = usize;
3715        }
3716
3717        let handle_1 = cx.add_model(|_| Model::default());
3718        let handle_2 = cx.add_model(|_| Model::default());
3719        let handle_2b = handle_2.clone();
3720
3721        handle_1.update(cx, |_, c| {
3722            c.subscribe(&handle_2, move |model: &mut Model, _, event, c| {
3723                model.events.push(*event);
3724
3725                c.subscribe(&handle_2b, |model, _, event, _| {
3726                    model.events.push(*event * 2);
3727                })
3728                .detach();
3729            })
3730            .detach();
3731        });
3732
3733        handle_2.update(cx, |_, c| c.emit(7));
3734        assert_eq!(handle_1.read(cx).events, vec![7]);
3735
3736        handle_2.update(cx, |_, c| c.emit(5));
3737        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
3738    }
3739
3740    #[crate::test(self)]
3741    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
3742        #[derive(Default)]
3743        struct Model {
3744            count: usize,
3745            events: Vec<usize>,
3746        }
3747
3748        impl Entity for Model {
3749            type Event = ();
3750        }
3751
3752        let handle_1 = cx.add_model(|_| Model::default());
3753        let handle_2 = cx.add_model(|_| Model::default());
3754        let handle_2b = handle_2.clone();
3755
3756        handle_1.update(cx, |_, c| {
3757            c.observe(&handle_2, move |model, observed, c| {
3758                model.events.push(observed.read(c).count);
3759                c.observe(&handle_2b, |model, observed, c| {
3760                    model.events.push(observed.read(c).count * 2);
3761                })
3762                .detach();
3763            })
3764            .detach();
3765        });
3766
3767        handle_2.update(cx, |model, c| {
3768            model.count = 7;
3769            c.notify()
3770        });
3771        assert_eq!(handle_1.read(cx).events, vec![7]);
3772
3773        handle_2.update(cx, |model, c| {
3774            model.count = 5;
3775            c.notify()
3776        });
3777        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
3778    }
3779
3780    #[crate::test(self)]
3781    fn test_view_handles(cx: &mut MutableAppContext) {
3782        struct View {
3783            other: Option<ViewHandle<View>>,
3784            events: Vec<String>,
3785        }
3786
3787        impl Entity for View {
3788            type Event = usize;
3789        }
3790
3791        impl super::View for View {
3792            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3793                Empty::new().boxed()
3794            }
3795
3796            fn ui_name() -> &'static str {
3797                "View"
3798            }
3799        }
3800
3801        impl View {
3802            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
3803                if let Some(other) = other.as_ref() {
3804                    cx.subscribe(other, |me, _, event, _| {
3805                        me.events.push(format!("observed event {}", event));
3806                    })
3807                    .detach();
3808                }
3809                Self {
3810                    other,
3811                    events: Vec::new(),
3812                }
3813            }
3814        }
3815
3816        let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
3817        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
3818        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
3819        assert_eq!(cx.cx.views.len(), 3);
3820
3821        handle_1.update(cx, |view, cx| {
3822            view.events.push("updated".into());
3823            cx.emit(1);
3824            cx.emit(2);
3825        });
3826        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3827        assert_eq!(
3828            handle_2.read(cx).events,
3829            vec![
3830                "observed event 1".to_string(),
3831                "observed event 2".to_string(),
3832            ]
3833        );
3834
3835        handle_2.update(cx, |view, _| {
3836            drop(handle_1);
3837            view.other.take();
3838        });
3839
3840        assert_eq!(cx.cx.views.len(), 2);
3841        assert!(cx.subscriptions.lock().is_empty());
3842        assert!(cx.observations.lock().is_empty());
3843    }
3844
3845    #[crate::test(self)]
3846    fn test_add_window(cx: &mut MutableAppContext) {
3847        struct View {
3848            mouse_down_count: Arc<AtomicUsize>,
3849        }
3850
3851        impl Entity for View {
3852            type Event = ();
3853        }
3854
3855        impl super::View for View {
3856            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3857                let mouse_down_count = self.mouse_down_count.clone();
3858                EventHandler::new(Empty::new().boxed())
3859                    .on_mouse_down(move |_| {
3860                        mouse_down_count.fetch_add(1, SeqCst);
3861                        true
3862                    })
3863                    .boxed()
3864            }
3865
3866            fn ui_name() -> &'static str {
3867                "View"
3868            }
3869        }
3870
3871        let mouse_down_count = Arc::new(AtomicUsize::new(0));
3872        let (window_id, _) = cx.add_window(Default::default(), |_| View {
3873            mouse_down_count: mouse_down_count.clone(),
3874        });
3875        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
3876        // Ensure window's root element is in a valid lifecycle state.
3877        presenter.borrow_mut().dispatch_event(
3878            Event::LeftMouseDown {
3879                position: Default::default(),
3880                ctrl: false,
3881                alt: false,
3882                shift: false,
3883                cmd: false,
3884                click_count: 1,
3885            },
3886            cx,
3887        );
3888        assert_eq!(mouse_down_count.load(SeqCst), 1);
3889    }
3890
3891    #[crate::test(self)]
3892    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
3893        struct Model {
3894            released: Rc<Cell<bool>>,
3895        }
3896
3897        struct View {
3898            released: Rc<Cell<bool>>,
3899        }
3900
3901        impl Entity for Model {
3902            type Event = ();
3903
3904            fn release(&mut self, _: &mut MutableAppContext) {
3905                self.released.set(true);
3906            }
3907        }
3908
3909        impl Entity for View {
3910            type Event = ();
3911
3912            fn release(&mut self, _: &mut MutableAppContext) {
3913                self.released.set(true);
3914            }
3915        }
3916
3917        impl super::View for View {
3918            fn ui_name() -> &'static str {
3919                "View"
3920            }
3921
3922            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3923                Empty::new().boxed()
3924            }
3925        }
3926
3927        let model_released = Rc::new(Cell::new(false));
3928        let model_release_observed = Rc::new(Cell::new(false));
3929        let view_released = Rc::new(Cell::new(false));
3930        let view_release_observed = Rc::new(Cell::new(false));
3931
3932        let model = cx.add_model(|_| Model {
3933            released: model_released.clone(),
3934        });
3935        let (window_id, view) = cx.add_window(Default::default(), |_| View {
3936            released: view_released.clone(),
3937        });
3938        assert!(!model_released.get());
3939        assert!(!view_released.get());
3940
3941        cx.observe_release(&model, {
3942            let model_release_observed = model_release_observed.clone();
3943            move |_| model_release_observed.set(true)
3944        })
3945        .detach();
3946        cx.observe_release(&view, {
3947            let view_release_observed = view_release_observed.clone();
3948            move |_| view_release_observed.set(true)
3949        })
3950        .detach();
3951
3952        cx.update(move |_| {
3953            drop(model);
3954        });
3955        assert!(model_released.get());
3956        assert!(model_release_observed.get());
3957
3958        drop(view);
3959        cx.remove_window(window_id);
3960        assert!(view_released.get());
3961        assert!(view_release_observed.get());
3962    }
3963
3964    #[crate::test(self)]
3965    fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) {
3966        #[derive(Default)]
3967        struct View {
3968            events: Vec<usize>,
3969        }
3970
3971        impl Entity for View {
3972            type Event = usize;
3973        }
3974
3975        impl super::View for View {
3976            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3977                Empty::new().boxed()
3978            }
3979
3980            fn ui_name() -> &'static str {
3981                "View"
3982            }
3983        }
3984
3985        struct Model;
3986
3987        impl Entity for Model {
3988            type Event = usize;
3989        }
3990
3991        let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
3992        let handle_2 = cx.add_view(window_id, |_| View::default());
3993        let handle_2b = handle_2.clone();
3994        let handle_3 = cx.add_model(|_| Model);
3995
3996        handle_1.update(cx, |_, c| {
3997            c.subscribe(&handle_2, move |me, _, event, c| {
3998                me.events.push(*event);
3999
4000                c.subscribe(&handle_2b, |me, _, event, _| {
4001                    me.events.push(*event * 2);
4002                })
4003                .detach();
4004            })
4005            .detach();
4006
4007            c.subscribe(&handle_3, |me, _, event, _| {
4008                me.events.push(*event);
4009            })
4010            .detach();
4011        });
4012
4013        handle_2.update(cx, |_, c| c.emit(7));
4014        assert_eq!(handle_1.read(cx).events, vec![7]);
4015
4016        handle_2.update(cx, |_, c| c.emit(5));
4017        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4018
4019        handle_3.update(cx, |_, c| c.emit(9));
4020        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
4021    }
4022
4023    #[crate::test(self)]
4024    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
4025        struct View;
4026
4027        impl Entity for View {
4028            type Event = ();
4029        }
4030
4031        impl super::View for View {
4032            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4033                Empty::new().boxed()
4034            }
4035
4036            fn ui_name() -> &'static str {
4037                "View"
4038            }
4039        }
4040
4041        struct Model;
4042
4043        impl Entity for Model {
4044            type Event = ();
4045        }
4046
4047        let (window_id, _) = cx.add_window(Default::default(), |_| View);
4048        let observing_view = cx.add_view(window_id, |_| View);
4049        let emitting_view = cx.add_view(window_id, |_| View);
4050        let observing_model = cx.add_model(|_| Model);
4051        let observed_model = cx.add_model(|_| Model);
4052
4053        observing_view.update(cx, |_, cx| {
4054            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
4055            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4056        });
4057        observing_model.update(cx, |_, cx| {
4058            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4059        });
4060
4061        cx.update(|_| {
4062            drop(observing_view);
4063            drop(observing_model);
4064        });
4065
4066        emitting_view.update(cx, |_, cx| cx.emit(()));
4067        observed_model.update(cx, |_, cx| cx.emit(()));
4068    }
4069
4070    #[crate::test(self)]
4071    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
4072        #[derive(Default)]
4073        struct View {
4074            events: Vec<usize>,
4075        }
4076
4077        impl Entity for View {
4078            type Event = usize;
4079        }
4080
4081        impl super::View for View {
4082            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4083                Empty::new().boxed()
4084            }
4085
4086            fn ui_name() -> &'static str {
4087                "View"
4088            }
4089        }
4090
4091        #[derive(Default)]
4092        struct Model {
4093            count: usize,
4094        }
4095
4096        impl Entity for Model {
4097            type Event = ();
4098        }
4099
4100        let (_, view) = cx.add_window(Default::default(), |_| View::default());
4101        let model = cx.add_model(|_| Model::default());
4102
4103        view.update(cx, |_, c| {
4104            c.observe(&model, |me, observed, c| {
4105                me.events.push(observed.read(c).count)
4106            })
4107            .detach();
4108        });
4109
4110        model.update(cx, |model, c| {
4111            model.count = 11;
4112            c.notify();
4113        });
4114        assert_eq!(view.read(cx).events, vec![11]);
4115    }
4116
4117    #[crate::test(self)]
4118    fn test_dropping_observers(cx: &mut MutableAppContext) {
4119        struct View;
4120
4121        impl Entity for View {
4122            type Event = ();
4123        }
4124
4125        impl super::View for View {
4126            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4127                Empty::new().boxed()
4128            }
4129
4130            fn ui_name() -> &'static str {
4131                "View"
4132            }
4133        }
4134
4135        struct Model;
4136
4137        impl Entity for Model {
4138            type Event = ();
4139        }
4140
4141        let (window_id, _) = cx.add_window(Default::default(), |_| View);
4142        let observing_view = cx.add_view(window_id, |_| View);
4143        let observing_model = cx.add_model(|_| Model);
4144        let observed_model = cx.add_model(|_| Model);
4145
4146        observing_view.update(cx, |_, cx| {
4147            cx.observe(&observed_model, |_, _, _| {}).detach();
4148        });
4149        observing_model.update(cx, |_, cx| {
4150            cx.observe(&observed_model, |_, _, _| {}).detach();
4151        });
4152
4153        cx.update(|_| {
4154            drop(observing_view);
4155            drop(observing_model);
4156        });
4157
4158        observed_model.update(cx, |_, cx| cx.notify());
4159    }
4160
4161    #[crate::test(self)]
4162    fn test_focus(cx: &mut MutableAppContext) {
4163        struct View {
4164            name: String,
4165            events: Arc<Mutex<Vec<String>>>,
4166        }
4167
4168        impl Entity for View {
4169            type Event = ();
4170        }
4171
4172        impl super::View for View {
4173            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4174                Empty::new().boxed()
4175            }
4176
4177            fn ui_name() -> &'static str {
4178                "View"
4179            }
4180
4181            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
4182                self.events.lock().push(format!("{} focused", &self.name));
4183            }
4184
4185            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
4186                self.events.lock().push(format!("{} blurred", &self.name));
4187            }
4188        }
4189
4190        let events: Arc<Mutex<Vec<String>>> = Default::default();
4191        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
4192            events: events.clone(),
4193            name: "view 1".to_string(),
4194        });
4195        let view_2 = cx.add_view(window_id, |_| View {
4196            events: events.clone(),
4197            name: "view 2".to_string(),
4198        });
4199
4200        view_1.update(cx, |_, cx| cx.focus(&view_2));
4201        view_1.update(cx, |_, cx| cx.focus(&view_1));
4202        view_1.update(cx, |_, cx| cx.focus(&view_2));
4203        view_1.update(cx, |_, _| drop(view_2));
4204
4205        assert_eq!(
4206            *events.lock(),
4207            [
4208                "view 1 focused".to_string(),
4209                "view 1 blurred".to_string(),
4210                "view 2 focused".to_string(),
4211                "view 2 blurred".to_string(),
4212                "view 1 focused".to_string(),
4213                "view 1 blurred".to_string(),
4214                "view 2 focused".to_string(),
4215                "view 1 focused".to_string(),
4216            ],
4217        );
4218    }
4219
4220    #[crate::test(self)]
4221    fn test_dispatch_action(cx: &mut MutableAppContext) {
4222        struct ViewA {
4223            id: usize,
4224        }
4225
4226        impl Entity for ViewA {
4227            type Event = ();
4228        }
4229
4230        impl View for ViewA {
4231            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4232                Empty::new().boxed()
4233            }
4234
4235            fn ui_name() -> &'static str {
4236                "View"
4237            }
4238        }
4239
4240        struct ViewB {
4241            id: usize,
4242        }
4243
4244        impl Entity for ViewB {
4245            type Event = ();
4246        }
4247
4248        impl View for ViewB {
4249            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4250                Empty::new().boxed()
4251            }
4252
4253            fn ui_name() -> &'static str {
4254                "View"
4255            }
4256        }
4257
4258        action!(Action, &'static str);
4259
4260        let actions = Rc::new(RefCell::new(Vec::new()));
4261
4262        let actions_clone = actions.clone();
4263        cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
4264            actions_clone.borrow_mut().push("global".to_string());
4265        });
4266
4267        let actions_clone = actions.clone();
4268        cx.add_action(move |view: &mut ViewA, action: &Action, cx| {
4269            assert_eq!(action.0, "bar");
4270            cx.propagate_action();
4271            actions_clone.borrow_mut().push(format!("{} a", view.id));
4272        });
4273
4274        let actions_clone = actions.clone();
4275        cx.add_action(move |view: &mut ViewA, _: &Action, cx| {
4276            if view.id != 1 {
4277                cx.propagate_action();
4278            }
4279            actions_clone.borrow_mut().push(format!("{} b", view.id));
4280        });
4281
4282        let actions_clone = actions.clone();
4283        cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
4284            cx.propagate_action();
4285            actions_clone.borrow_mut().push(format!("{} c", view.id));
4286        });
4287
4288        let actions_clone = actions.clone();
4289        cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
4290            cx.propagate_action();
4291            actions_clone.borrow_mut().push(format!("{} d", view.id));
4292        });
4293
4294        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
4295        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
4296        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
4297        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
4298
4299        cx.dispatch_action(
4300            window_id,
4301            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
4302            &Action("bar"),
4303        );
4304
4305        assert_eq!(
4306            *actions.borrow(),
4307            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "1 b"]
4308        );
4309
4310        // Remove view_1, which doesn't propagate the action
4311        actions.borrow_mut().clear();
4312        cx.dispatch_action(
4313            window_id,
4314            vec![view_2.id(), view_3.id(), view_4.id()],
4315            &Action("bar"),
4316        );
4317
4318        assert_eq!(
4319            *actions.borrow(),
4320            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "global"]
4321        );
4322    }
4323
4324    #[crate::test(self)]
4325    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
4326        use std::cell::Cell;
4327
4328        action!(Action, &'static str);
4329
4330        struct View {
4331            id: usize,
4332            keymap_context: keymap::Context,
4333        }
4334
4335        impl Entity for View {
4336            type Event = ();
4337        }
4338
4339        impl super::View for View {
4340            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4341                Empty::new().boxed()
4342            }
4343
4344            fn ui_name() -> &'static str {
4345                "View"
4346            }
4347
4348            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
4349                self.keymap_context.clone()
4350            }
4351        }
4352
4353        impl View {
4354            fn new(id: usize) -> Self {
4355                View {
4356                    id,
4357                    keymap_context: keymap::Context::default(),
4358                }
4359            }
4360        }
4361
4362        let mut view_1 = View::new(1);
4363        let mut view_2 = View::new(2);
4364        let mut view_3 = View::new(3);
4365        view_1.keymap_context.set.insert("a".into());
4366        view_2.keymap_context.set.insert("a".into());
4367        view_2.keymap_context.set.insert("b".into());
4368        view_3.keymap_context.set.insert("a".into());
4369        view_3.keymap_context.set.insert("b".into());
4370        view_3.keymap_context.set.insert("c".into());
4371
4372        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
4373        let view_2 = cx.add_view(window_id, |_| view_2);
4374        let view_3 = cx.add_view(window_id, |_| view_3);
4375
4376        // This keymap's only binding dispatches an action on view 2 because that view will have
4377        // "a" and "b" in its context, but not "c".
4378        cx.add_bindings(vec![keymap::Binding::new(
4379            "a",
4380            Action("a"),
4381            Some("a && b && !c"),
4382        )]);
4383
4384        let handled_action = Rc::new(Cell::new(false));
4385        let handled_action_clone = handled_action.clone();
4386        cx.add_action(move |view: &mut View, action: &Action, _| {
4387            handled_action_clone.set(true);
4388            assert_eq!(view.id, 2);
4389            assert_eq!(action.0, "a");
4390        });
4391
4392        cx.dispatch_keystroke(
4393            window_id,
4394            vec![view_1.id(), view_2.id(), view_3.id()],
4395            &Keystroke::parse("a").unwrap(),
4396        )
4397        .unwrap();
4398
4399        assert!(handled_action.get());
4400    }
4401
4402    #[crate::test(self)]
4403    async fn test_model_condition(mut cx: TestAppContext) {
4404        struct Counter(usize);
4405
4406        impl super::Entity for Counter {
4407            type Event = ();
4408        }
4409
4410        impl Counter {
4411            fn inc(&mut self, cx: &mut ModelContext<Self>) {
4412                self.0 += 1;
4413                cx.notify();
4414            }
4415        }
4416
4417        let model = cx.add_model(|_| Counter(0));
4418
4419        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
4420        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
4421        smol::pin!(condition1, condition2);
4422
4423        model.update(&mut cx, |model, cx| model.inc(cx));
4424        assert_eq!(poll_once(&mut condition1).await, None);
4425        assert_eq!(poll_once(&mut condition2).await, None);
4426
4427        model.update(&mut cx, |model, cx| model.inc(cx));
4428        assert_eq!(poll_once(&mut condition1).await, Some(()));
4429        assert_eq!(poll_once(&mut condition2).await, None);
4430
4431        model.update(&mut cx, |model, cx| model.inc(cx));
4432        assert_eq!(poll_once(&mut condition2).await, Some(()));
4433
4434        model.update(&mut cx, |_, cx| cx.notify());
4435    }
4436
4437    #[crate::test(self)]
4438    #[should_panic]
4439    async fn test_model_condition_timeout(mut cx: TestAppContext) {
4440        struct Model;
4441
4442        impl super::Entity for Model {
4443            type Event = ();
4444        }
4445
4446        let model = cx.add_model(|_| Model);
4447        model.condition(&cx, |_, _| false).await;
4448    }
4449
4450    #[crate::test(self)]
4451    #[should_panic(expected = "model dropped with pending condition")]
4452    async fn test_model_condition_panic_on_drop(mut cx: TestAppContext) {
4453        struct Model;
4454
4455        impl super::Entity for Model {
4456            type Event = ();
4457        }
4458
4459        let model = cx.add_model(|_| Model);
4460        let condition = model.condition(&cx, |_, _| false);
4461        cx.update(|_| drop(model));
4462        condition.await;
4463    }
4464
4465    #[crate::test(self)]
4466    async fn test_view_condition(mut cx: TestAppContext) {
4467        struct Counter(usize);
4468
4469        impl super::Entity for Counter {
4470            type Event = ();
4471        }
4472
4473        impl super::View for Counter {
4474            fn ui_name() -> &'static str {
4475                "test view"
4476            }
4477
4478            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4479                Empty::new().boxed()
4480            }
4481        }
4482
4483        impl Counter {
4484            fn inc(&mut self, cx: &mut ViewContext<Self>) {
4485                self.0 += 1;
4486                cx.notify();
4487            }
4488        }
4489
4490        let (_, view) = cx.add_window(|_| Counter(0));
4491
4492        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
4493        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
4494        smol::pin!(condition1, condition2);
4495
4496        view.update(&mut cx, |view, cx| view.inc(cx));
4497        assert_eq!(poll_once(&mut condition1).await, None);
4498        assert_eq!(poll_once(&mut condition2).await, None);
4499
4500        view.update(&mut cx, |view, cx| view.inc(cx));
4501        assert_eq!(poll_once(&mut condition1).await, Some(()));
4502        assert_eq!(poll_once(&mut condition2).await, None);
4503
4504        view.update(&mut cx, |view, cx| view.inc(cx));
4505        assert_eq!(poll_once(&mut condition2).await, Some(()));
4506        view.update(&mut cx, |_, cx| cx.notify());
4507    }
4508
4509    #[crate::test(self)]
4510    #[should_panic]
4511    async fn test_view_condition_timeout(mut cx: TestAppContext) {
4512        struct View;
4513
4514        impl super::Entity for View {
4515            type Event = ();
4516        }
4517
4518        impl super::View for View {
4519            fn ui_name() -> &'static str {
4520                "test view"
4521            }
4522
4523            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4524                Empty::new().boxed()
4525            }
4526        }
4527
4528        let (_, view) = cx.add_window(|_| View);
4529        view.condition(&cx, |_, _| false).await;
4530    }
4531
4532    #[crate::test(self)]
4533    #[should_panic(expected = "view dropped with pending condition")]
4534    async fn test_view_condition_panic_on_drop(mut cx: TestAppContext) {
4535        struct View;
4536
4537        impl super::Entity for View {
4538            type Event = ();
4539        }
4540
4541        impl super::View for View {
4542            fn ui_name() -> &'static str {
4543                "test view"
4544            }
4545
4546            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4547                Empty::new().boxed()
4548            }
4549        }
4550
4551        let window_id = cx.add_window(|_| View).0;
4552        let view = cx.add_view(window_id, |_| View);
4553
4554        let condition = view.condition(&cx, |_, _| false);
4555        cx.update(|_| drop(view));
4556        condition.await;
4557    }
4558}