app.rs

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