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