app.rs

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