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