app.rs

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