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