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