app.rs

   1use crate::{
   2    elements::ElementBox,
   3    executor,
   4    keymap::{self, Keystroke},
   5    platform::{self, Platform, PromptLevel, WindowOptions},
   6    presenter::Presenter,
   7    util::{post_inc, timeout},
   8    AssetCache, AssetSource, ClipboardItem, EventContext, FontCache, PathPromptOptions,
   9    TextLayoutCache,
  10};
  11use anyhow::{anyhow, Result};
  12use async_task::Task;
  13use keymap::MatchResult;
  14use parking_lot::{Mutex, RwLock};
  15use platform::Event;
  16use postage::{mpsc, sink::Sink as _, stream::Stream as _};
  17use smol::prelude::*;
  18use std::{
  19    any::{type_name, Any, TypeId},
  20    cell::RefCell,
  21    collections::{hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque},
  22    fmt::{self, Debug},
  23    hash::{Hash, Hasher},
  24    marker::PhantomData,
  25    mem,
  26    ops::{Deref, DerefMut},
  27    path::{Path, PathBuf},
  28    rc::{self, Rc},
  29    sync::{Arc, Weak},
  30    time::Duration,
  31};
  32
  33pub trait Entity: 'static {
  34    type Event;
  35
  36    fn release(&mut self, _: &mut MutableAppContext) {}
  37}
  38
  39pub trait View: Entity + Sized {
  40    fn ui_name() -> &'static str;
  41    fn render(&self, cx: &RenderContext<'_, Self>) -> ElementBox;
  42    fn on_focus(&mut self, _: &mut ViewContext<Self>) {}
  43    fn on_blur(&mut self, _: &mut ViewContext<Self>) {}
  44    fn keymap_context(&self, _: &AppContext) -> keymap::Context {
  45        Self::default_keymap_context()
  46    }
  47    fn default_keymap_context() -> keymap::Context {
  48        let mut cx = keymap::Context::default();
  49        cx.set.insert(Self::ui_name().into());
  50        cx
  51    }
  52}
  53
  54pub trait ReadModel {
  55    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T;
  56}
  57
  58pub trait ReadModelWith {
  59    fn read_model_with<E: Entity, F: FnOnce(&E, &AppContext) -> T, T>(
  60        &self,
  61        handle: &ModelHandle<E>,
  62        read: F,
  63    ) -> T;
  64}
  65
  66pub trait UpdateModel {
  67    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
  68    where
  69        T: Entity,
  70        F: FnOnce(&mut T, &mut ModelContext<T>) -> S;
  71}
  72
  73pub trait UpgradeModelHandle {
  74    fn upgrade_model_handle<T: Entity>(&self, handle: WeakModelHandle<T>)
  75        -> Option<ModelHandle<T>>;
  76}
  77
  78pub trait ReadView {
  79    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T;
  80}
  81
  82pub trait ReadViewWith {
  83    fn read_view_with<V, F, T>(&self, handle: &ViewHandle<V>, read: F) -> T
  84    where
  85        V: View,
  86        F: FnOnce(&V, &AppContext) -> T;
  87}
  88
  89pub trait UpdateView {
  90    fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
  91    where
  92        T: View,
  93        F: FnOnce(&mut T, &mut ViewContext<T>) -> S;
  94}
  95
  96pub trait Action: 'static + AnyAction {
  97    type Argument: 'static + Clone;
  98}
  99
 100pub trait AnyAction {
 101    fn id(&self) -> TypeId;
 102    fn name(&self) -> &'static str;
 103    fn as_any(&self) -> &dyn Any;
 104    fn boxed_clone(&self) -> Box<dyn AnyAction>;
 105    fn boxed_clone_as_any(&self) -> Box<dyn Any>;
 106}
 107
 108#[macro_export]
 109macro_rules! action {
 110    ($name:ident, $arg:ty) => {
 111        #[derive(Clone)]
 112        pub struct $name(pub $arg);
 113
 114        impl $crate::Action for $name {
 115            type Argument = $arg;
 116        }
 117
 118        impl $crate::AnyAction for $name {
 119            fn id(&self) -> std::any::TypeId {
 120                std::any::TypeId::of::<$name>()
 121            }
 122
 123            fn name(&self) -> &'static str {
 124                stringify!($name)
 125            }
 126
 127            fn as_any(&self) -> &dyn std::any::Any {
 128                self
 129            }
 130
 131            fn boxed_clone(&self) -> Box<dyn $crate::AnyAction> {
 132                Box::new(self.clone())
 133            }
 134
 135            fn boxed_clone_as_any(&self) -> Box<dyn std::any::Any> {
 136                Box::new(self.clone())
 137            }
 138        }
 139    };
 140
 141    ($name:ident) => {
 142        #[derive(Clone, Debug, Eq, PartialEq)]
 143        pub struct $name;
 144
 145        impl $crate::Action for $name {
 146            type Argument = ();
 147        }
 148
 149        impl $crate::AnyAction for $name {
 150            fn id(&self) -> std::any::TypeId {
 151                std::any::TypeId::of::<$name>()
 152            }
 153
 154            fn name(&self) -> &'static str {
 155                stringify!($name)
 156            }
 157
 158            fn as_any(&self) -> &dyn std::any::Any {
 159                self
 160            }
 161
 162            fn boxed_clone(&self) -> Box<dyn $crate::AnyAction> {
 163                Box::new(self.clone())
 164            }
 165
 166            fn boxed_clone_as_any(&self) -> Box<dyn std::any::Any> {
 167                Box::new(self.clone())
 168            }
 169        }
 170    };
 171}
 172
 173pub struct Menu<'a> {
 174    pub name: &'a str,
 175    pub items: Vec<MenuItem<'a>>,
 176}
 177
 178pub enum MenuItem<'a> {
 179    Action {
 180        name: &'a str,
 181        keystroke: Option<&'a str>,
 182        action: Box<dyn AnyAction>,
 183    },
 184    Separator,
 185}
 186
 187#[derive(Clone)]
 188pub struct App(Rc<RefCell<MutableAppContext>>);
 189
 190#[derive(Clone)]
 191pub struct AsyncAppContext(Rc<RefCell<MutableAppContext>>);
 192
 193pub struct BackgroundAppContext(*const RefCell<MutableAppContext>);
 194
 195#[derive(Clone)]
 196pub struct TestAppContext {
 197    cx: Rc<RefCell<MutableAppContext>>,
 198    foreground_platform: Rc<platform::test::ForegroundPlatform>,
 199}
 200
 201impl App {
 202    pub fn new(asset_source: impl AssetSource) -> Result<Self> {
 203        let platform = platform::current::platform();
 204        let foreground_platform = platform::current::foreground_platform();
 205        let foreground = Rc::new(executor::Foreground::platform(platform.dispatcher())?);
 206        let app = Self(Rc::new(RefCell::new(MutableAppContext::new(
 207            foreground,
 208            Arc::new(executor::Background::new()),
 209            platform.clone(),
 210            foreground_platform.clone(),
 211            Arc::new(FontCache::new(platform.fonts())),
 212            asset_source,
 213        ))));
 214
 215        let cx = app.0.clone();
 216        foreground_platform.on_menu_command(Box::new(move |action| {
 217            let mut cx = cx.borrow_mut();
 218            if let Some(key_window_id) = cx.cx.platform.key_window_id() {
 219                if let Some((presenter, _)) = cx.presenters_and_platform_windows.get(&key_window_id)
 220                {
 221                    let presenter = presenter.clone();
 222                    let path = presenter.borrow().dispatch_path(cx.as_ref());
 223                    cx.dispatch_action_any(key_window_id, &path, action);
 224                } else {
 225                    cx.dispatch_global_action_any(action);
 226                }
 227            } else {
 228                cx.dispatch_global_action_any(action);
 229            }
 230        }));
 231
 232        app.0.borrow_mut().weak_self = Some(Rc::downgrade(&app.0));
 233        Ok(app)
 234    }
 235
 236    pub fn on_become_active<F>(self, mut callback: F) -> Self
 237    where
 238        F: 'static + FnMut(&mut MutableAppContext),
 239    {
 240        let cx = self.0.clone();
 241        self.0
 242            .borrow_mut()
 243            .foreground_platform
 244            .on_become_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 245        self
 246    }
 247
 248    pub fn on_resign_active<F>(self, mut callback: F) -> Self
 249    where
 250        F: 'static + FnMut(&mut MutableAppContext),
 251    {
 252        let cx = self.0.clone();
 253        self.0
 254            .borrow_mut()
 255            .foreground_platform
 256            .on_resign_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 257        self
 258    }
 259
 260    pub fn on_event<F>(self, mut callback: F) -> Self
 261    where
 262        F: 'static + FnMut(Event, &mut MutableAppContext) -> bool,
 263    {
 264        let cx = self.0.clone();
 265        self.0
 266            .borrow_mut()
 267            .foreground_platform
 268            .on_event(Box::new(move |event| {
 269                callback(event, &mut *cx.borrow_mut())
 270            }));
 271        self
 272    }
 273
 274    pub fn on_open_files<F>(self, mut callback: F) -> Self
 275    where
 276        F: 'static + FnMut(Vec<PathBuf>, &mut MutableAppContext),
 277    {
 278        let cx = self.0.clone();
 279        self.0
 280            .borrow_mut()
 281            .foreground_platform
 282            .on_open_files(Box::new(move |paths| {
 283                callback(paths, &mut *cx.borrow_mut())
 284            }));
 285        self
 286    }
 287
 288    pub fn run<F>(self, on_finish_launching: F)
 289    where
 290        F: 'static + FnOnce(&mut MutableAppContext),
 291    {
 292        let platform = self.0.borrow().foreground_platform.clone();
 293        platform.run(Box::new(move || {
 294            let mut cx = self.0.borrow_mut();
 295            on_finish_launching(&mut *cx);
 296        }))
 297    }
 298
 299    pub fn font_cache(&self) -> Arc<FontCache> {
 300        self.0.borrow().cx.font_cache.clone()
 301    }
 302
 303    fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 304        let mut state = self.0.borrow_mut();
 305        state.pending_flushes += 1;
 306        let result = callback(&mut *state);
 307        state.flush_effects();
 308        result
 309    }
 310}
 311
 312impl TestAppContext {
 313    pub fn new(
 314        foreground_platform: Rc<platform::test::ForegroundPlatform>,
 315        platform: Arc<dyn Platform>,
 316        foreground: Rc<executor::Foreground>,
 317        background: Arc<executor::Background>,
 318        font_cache: Arc<FontCache>,
 319        first_entity_id: usize,
 320    ) -> Self {
 321        let mut cx = MutableAppContext::new(
 322            foreground.clone(),
 323            background,
 324            platform,
 325            foreground_platform.clone(),
 326            font_cache,
 327            (),
 328        );
 329        cx.next_entity_id = first_entity_id;
 330        let cx = TestAppContext {
 331            cx: Rc::new(RefCell::new(cx)),
 332            foreground_platform,
 333        };
 334        cx.cx.borrow_mut().weak_self = Some(Rc::downgrade(&cx.cx));
 335        cx
 336    }
 337
 338    pub fn dispatch_action<A: Action>(
 339        &self,
 340        window_id: usize,
 341        responder_chain: Vec<usize>,
 342        action: A,
 343    ) {
 344        self.cx
 345            .borrow_mut()
 346            .dispatch_action_any(window_id, &responder_chain, &action);
 347    }
 348
 349    pub fn dispatch_global_action<A: Action>(&self, action: A) {
 350        self.cx.borrow_mut().dispatch_global_action(action);
 351    }
 352
 353    pub fn dispatch_keystroke(
 354        &self,
 355        window_id: usize,
 356        responder_chain: Vec<usize>,
 357        keystroke: &Keystroke,
 358    ) -> Result<bool> {
 359        let mut state = self.cx.borrow_mut();
 360        state.dispatch_keystroke(window_id, responder_chain, keystroke)
 361    }
 362
 363    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 364    where
 365        T: Entity,
 366        F: FnOnce(&mut ModelContext<T>) -> T,
 367    {
 368        let mut state = self.cx.borrow_mut();
 369        state.pending_flushes += 1;
 370        let handle = state.add_model(build_model);
 371        state.flush_effects();
 372        handle
 373    }
 374
 375    pub fn add_window<T, F>(&mut self, build_root_view: F) -> (usize, ViewHandle<T>)
 376    where
 377        T: View,
 378        F: FnOnce(&mut ViewContext<T>) -> T,
 379    {
 380        self.cx
 381            .borrow_mut()
 382            .add_window(Default::default(), build_root_view)
 383    }
 384
 385    pub fn window_ids(&self) -> Vec<usize> {
 386        self.cx.borrow().window_ids().collect()
 387    }
 388
 389    pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
 390        self.cx.borrow().root_view(window_id)
 391    }
 392
 393    pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
 394    where
 395        T: View,
 396        F: FnOnce(&mut ViewContext<T>) -> T,
 397    {
 398        let mut state = self.cx.borrow_mut();
 399        state.pending_flushes += 1;
 400        let handle = state.add_view(window_id, build_view);
 401        state.flush_effects();
 402        handle
 403    }
 404
 405    pub fn add_option_view<T, F>(
 406        &mut self,
 407        window_id: usize,
 408        build_view: F,
 409    ) -> Option<ViewHandle<T>>
 410    where
 411        T: View,
 412        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
 413    {
 414        let mut state = self.cx.borrow_mut();
 415        state.pending_flushes += 1;
 416        let handle = state.add_option_view(window_id, build_view);
 417        state.flush_effects();
 418        handle
 419    }
 420
 421    pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
 422        callback(self.cx.borrow().as_ref())
 423    }
 424
 425    pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 426        let mut state = self.cx.borrow_mut();
 427        // Don't increment pending flushes in order to effects to be flushed before the callback
 428        // completes, which is helpful in tests.
 429        let result = callback(&mut *state);
 430        // Flush effects after the callback just in case there are any. This can happen in edge
 431        // cases such as the closure dropping handles.
 432        state.flush_effects();
 433        result
 434    }
 435
 436    pub fn to_async(&self) -> AsyncAppContext {
 437        AsyncAppContext(self.cx.clone())
 438    }
 439
 440    pub fn font_cache(&self) -> Arc<FontCache> {
 441        self.cx.borrow().cx.font_cache.clone()
 442    }
 443
 444    pub fn platform(&self) -> Arc<dyn platform::Platform> {
 445        self.cx.borrow().cx.platform.clone()
 446    }
 447
 448    pub fn foreground(&self) -> Rc<executor::Foreground> {
 449        self.cx.borrow().foreground().clone()
 450    }
 451
 452    pub fn background(&self) -> Arc<executor::Background> {
 453        self.cx.borrow().background().clone()
 454    }
 455
 456    pub fn simulate_new_path_selection(&self, result: impl FnOnce(PathBuf) -> Option<PathBuf>) {
 457        self.foreground_platform.simulate_new_path_selection(result);
 458    }
 459
 460    pub fn did_prompt_for_new_path(&self) -> bool {
 461        self.foreground_platform.as_ref().did_prompt_for_new_path()
 462    }
 463
 464    pub fn simulate_prompt_answer(&self, window_id: usize, answer: usize) {
 465        let mut state = self.cx.borrow_mut();
 466        let (_, window) = state
 467            .presenters_and_platform_windows
 468            .get_mut(&window_id)
 469            .unwrap();
 470        let test_window = window
 471            .as_any_mut()
 472            .downcast_mut::<platform::test::Window>()
 473            .unwrap();
 474        let callback = test_window
 475            .last_prompt
 476            .take()
 477            .expect("prompt was not called");
 478        (callback)(answer);
 479    }
 480}
 481
 482impl AsyncAppContext {
 483    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
 484    where
 485        F: FnOnce(AsyncAppContext) -> Fut,
 486        Fut: 'static + Future<Output = T>,
 487        T: 'static,
 488    {
 489        self.0.borrow().foreground.spawn(f(self.clone()))
 490    }
 491
 492    pub fn read<T, F: FnOnce(&AppContext) -> T>(&mut self, callback: F) -> T {
 493        callback(self.0.borrow().as_ref())
 494    }
 495
 496    pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 497        let mut state = self.0.borrow_mut();
 498        state.pending_flushes += 1;
 499        let result = callback(&mut *state);
 500        state.flush_effects();
 501        result
 502    }
 503
 504    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 505    where
 506        T: Entity,
 507        F: FnOnce(&mut ModelContext<T>) -> T,
 508    {
 509        self.update(|cx| cx.add_model(build_model))
 510    }
 511
 512    pub fn platform(&self) -> Arc<dyn Platform> {
 513        self.0.borrow().platform()
 514    }
 515
 516    pub fn foreground(&self) -> Rc<executor::Foreground> {
 517        self.0.borrow().foreground.clone()
 518    }
 519
 520    pub fn background(&self) -> Arc<executor::Background> {
 521        self.0.borrow().cx.background.clone()
 522    }
 523}
 524
 525impl UpdateModel for AsyncAppContext {
 526    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
 527    where
 528        T: Entity,
 529        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
 530    {
 531        let mut state = self.0.borrow_mut();
 532        state.pending_flushes += 1;
 533        let result = state.update_model(handle, update);
 534        state.flush_effects();
 535        result
 536    }
 537}
 538
 539impl UpgradeModelHandle for AsyncAppContext {
 540    fn upgrade_model_handle<T: Entity>(
 541        &self,
 542        handle: WeakModelHandle<T>,
 543    ) -> Option<ModelHandle<T>> {
 544        self.0.borrow_mut().upgrade_model_handle(handle)
 545    }
 546}
 547
 548impl ReadModelWith for AsyncAppContext {
 549    fn read_model_with<E: Entity, F: FnOnce(&E, &AppContext) -> T, T>(
 550        &self,
 551        handle: &ModelHandle<E>,
 552        read: F,
 553    ) -> T {
 554        let cx = self.0.borrow();
 555        let cx = cx.as_ref();
 556        read(handle.read(cx), cx)
 557    }
 558}
 559
 560impl UpdateView for AsyncAppContext {
 561    fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
 562    where
 563        T: View,
 564        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
 565    {
 566        let mut state = self.0.borrow_mut();
 567        state.pending_flushes += 1;
 568        let result = state.update_view(handle, update);
 569        state.flush_effects();
 570        result
 571    }
 572}
 573
 574impl ReadViewWith for AsyncAppContext {
 575    fn read_view_with<V, F, T>(&self, handle: &ViewHandle<V>, read: F) -> T
 576    where
 577        V: View,
 578        F: FnOnce(&V, &AppContext) -> T,
 579    {
 580        let cx = self.0.borrow();
 581        let cx = cx.as_ref();
 582        read(handle.read(cx), cx)
 583    }
 584}
 585
 586impl UpdateModel for TestAppContext {
 587    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
 588    where
 589        T: Entity,
 590        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
 591    {
 592        let mut state = self.cx.borrow_mut();
 593        state.pending_flushes += 1;
 594        let result = state.update_model(handle, update);
 595        state.flush_effects();
 596        result
 597    }
 598}
 599
 600impl ReadModelWith for TestAppContext {
 601    fn read_model_with<E: Entity, F: FnOnce(&E, &AppContext) -> T, T>(
 602        &self,
 603        handle: &ModelHandle<E>,
 604        read: F,
 605    ) -> T {
 606        let cx = self.cx.borrow();
 607        let cx = cx.as_ref();
 608        read(handle.read(cx), cx)
 609    }
 610}
 611
 612impl UpdateView for TestAppContext {
 613    fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
 614    where
 615        T: View,
 616        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
 617    {
 618        let mut state = self.cx.borrow_mut();
 619        state.pending_flushes += 1;
 620        let result = state.update_view(handle, update);
 621        state.flush_effects();
 622        result
 623    }
 624}
 625
 626impl ReadViewWith for TestAppContext {
 627    fn read_view_with<V, F, T>(&self, handle: &ViewHandle<V>, read: F) -> T
 628    where
 629        V: View,
 630        F: FnOnce(&V, &AppContext) -> T,
 631    {
 632        let cx = self.cx.borrow();
 633        let cx = cx.as_ref();
 634        read(handle.read(cx), cx)
 635    }
 636}
 637
 638type ActionCallback =
 639    dyn FnMut(&mut dyn AnyView, &dyn AnyAction, &mut MutableAppContext, usize, usize) -> bool;
 640type GlobalActionCallback = dyn FnMut(&dyn AnyAction, &mut MutableAppContext);
 641
 642type SubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut MutableAppContext) -> bool>;
 643type ObservationCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>;
 644
 645pub struct MutableAppContext {
 646    weak_self: Option<rc::Weak<RefCell<Self>>>,
 647    foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 648    assets: Arc<AssetCache>,
 649    cx: AppContext,
 650    actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 651    global_actions: HashMap<TypeId, Vec<Box<GlobalActionCallback>>>,
 652    keystroke_matcher: keymap::Matcher,
 653    next_entity_id: usize,
 654    next_window_id: usize,
 655    next_subscription_id: usize,
 656    subscriptions: Arc<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>,
 657    observations: Arc<Mutex<HashMap<usize, BTreeMap<usize, ObservationCallback>>>>,
 658    presenters_and_platform_windows:
 659        HashMap<usize, (Rc<RefCell<Presenter>>, Box<dyn platform::Window>)>,
 660    debug_elements_callbacks: HashMap<usize, Box<dyn Fn(&AppContext) -> crate::json::Value>>,
 661    foreground: Rc<executor::Foreground>,
 662    pending_effects: VecDeque<Effect>,
 663    pending_flushes: usize,
 664    flushing_effects: bool,
 665}
 666
 667impl MutableAppContext {
 668    fn new(
 669        foreground: Rc<executor::Foreground>,
 670        background: Arc<executor::Background>,
 671        platform: Arc<dyn platform::Platform>,
 672        foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 673        font_cache: Arc<FontCache>,
 674        asset_source: impl AssetSource,
 675    ) -> Self {
 676        Self {
 677            weak_self: None,
 678            foreground_platform,
 679            assets: Arc::new(AssetCache::new(asset_source)),
 680            cx: AppContext {
 681                models: Default::default(),
 682                views: Default::default(),
 683                windows: Default::default(),
 684                values: Default::default(),
 685                ref_counts: Arc::new(Mutex::new(RefCounts::default())),
 686                background,
 687                font_cache,
 688                platform,
 689            },
 690            actions: HashMap::new(),
 691            global_actions: HashMap::new(),
 692            keystroke_matcher: keymap::Matcher::default(),
 693            next_entity_id: 0,
 694            next_window_id: 0,
 695            next_subscription_id: 0,
 696            subscriptions: Default::default(),
 697            observations: Default::default(),
 698            presenters_and_platform_windows: HashMap::new(),
 699            debug_elements_callbacks: HashMap::new(),
 700            foreground,
 701            pending_effects: VecDeque::new(),
 702            pending_flushes: 0,
 703            flushing_effects: false,
 704        }
 705    }
 706
 707    pub fn upgrade(&self) -> App {
 708        App(self.weak_self.as_ref().unwrap().upgrade().unwrap())
 709    }
 710
 711    pub fn platform(&self) -> Arc<dyn platform::Platform> {
 712        self.cx.platform.clone()
 713    }
 714
 715    pub fn font_cache(&self) -> &Arc<FontCache> {
 716        &self.cx.font_cache
 717    }
 718
 719    pub fn foreground(&self) -> &Rc<executor::Foreground> {
 720        &self.foreground
 721    }
 722
 723    pub fn background(&self) -> &Arc<executor::Background> {
 724        &self.cx.background
 725    }
 726
 727    pub fn on_debug_elements<F>(&mut self, window_id: usize, callback: F)
 728    where
 729        F: 'static + Fn(&AppContext) -> crate::json::Value,
 730    {
 731        self.debug_elements_callbacks
 732            .insert(window_id, Box::new(callback));
 733    }
 734
 735    pub fn debug_elements(&self, window_id: usize) -> Option<crate::json::Value> {
 736        self.debug_elements_callbacks
 737            .get(&window_id)
 738            .map(|debug_elements| debug_elements(&self.cx))
 739    }
 740
 741    pub fn add_action<A, V, F>(&mut self, mut handler: F)
 742    where
 743        A: Action,
 744        V: View,
 745        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
 746    {
 747        let handler = Box::new(
 748            move |view: &mut dyn AnyView,
 749                  action: &dyn AnyAction,
 750                  cx: &mut MutableAppContext,
 751                  window_id: usize,
 752                  view_id: usize| {
 753                let action = action.as_any().downcast_ref().unwrap();
 754                let mut cx = ViewContext::new(cx, window_id, view_id);
 755                handler(
 756                    view.as_any_mut()
 757                        .downcast_mut()
 758                        .expect("downcast is type safe"),
 759                    action,
 760                    &mut cx,
 761                );
 762                cx.halt_action_dispatch
 763            },
 764        );
 765
 766        self.actions
 767            .entry(TypeId::of::<V>())
 768            .or_default()
 769            .entry(TypeId::of::<A>())
 770            .or_default()
 771            .push(handler);
 772    }
 773
 774    pub fn add_global_action<A, F>(&mut self, mut handler: F)
 775    where
 776        A: Action,
 777        F: 'static + FnMut(&A, &mut MutableAppContext),
 778    {
 779        let handler = Box::new(move |action: &dyn AnyAction, cx: &mut MutableAppContext| {
 780            let action = action.as_any().downcast_ref().unwrap();
 781            handler(action, cx);
 782        });
 783
 784        self.global_actions
 785            .entry(TypeId::of::<A>())
 786            .or_default()
 787            .push(handler);
 788    }
 789
 790    pub fn window_ids(&self) -> impl Iterator<Item = usize> + '_ {
 791        self.cx.windows.keys().cloned()
 792    }
 793
 794    pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
 795        self.cx
 796            .windows
 797            .get(&window_id)
 798            .and_then(|window| window.root_view.clone().downcast::<T>())
 799    }
 800
 801    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
 802        self.cx.root_view_id(window_id)
 803    }
 804
 805    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
 806        self.cx.focused_view_id(window_id)
 807    }
 808
 809    pub fn render_views(
 810        &self,
 811        window_id: usize,
 812        titlebar_height: f32,
 813    ) -> HashMap<usize, ElementBox> {
 814        self.cx.render_views(window_id, titlebar_height)
 815    }
 816
 817    pub fn update<T, F: FnOnce() -> T>(&mut self, callback: F) -> T {
 818        self.pending_flushes += 1;
 819        let result = callback();
 820        self.flush_effects();
 821        result
 822    }
 823
 824    pub fn set_menus(&mut self, menus: Vec<Menu>) {
 825        self.foreground_platform.set_menus(menus);
 826    }
 827
 828    fn prompt<F>(
 829        &self,
 830        window_id: usize,
 831        level: PromptLevel,
 832        msg: &str,
 833        answers: &[&str],
 834        done_fn: F,
 835    ) where
 836        F: 'static + FnOnce(usize, &mut MutableAppContext),
 837    {
 838        let app = self.weak_self.as_ref().unwrap().upgrade().unwrap();
 839        let foreground = self.foreground.clone();
 840        let (_, window) = &self.presenters_and_platform_windows[&window_id];
 841        window.prompt(
 842            level,
 843            msg,
 844            answers,
 845            Box::new(move |answer| {
 846                foreground
 847                    .spawn(async move { (done_fn)(answer, &mut *app.borrow_mut()) })
 848                    .detach();
 849            }),
 850        );
 851    }
 852
 853    pub fn prompt_for_paths<F>(&self, options: PathPromptOptions, done_fn: F)
 854    where
 855        F: 'static + FnOnce(Option<Vec<PathBuf>>, &mut MutableAppContext),
 856    {
 857        let app = self.weak_self.as_ref().unwrap().upgrade().unwrap();
 858        let foreground = self.foreground.clone();
 859        self.foreground_platform.prompt_for_paths(
 860            options,
 861            Box::new(move |paths| {
 862                foreground
 863                    .spawn(async move { (done_fn)(paths, &mut *app.borrow_mut()) })
 864                    .detach();
 865            }),
 866        );
 867    }
 868
 869    pub fn prompt_for_new_path<F>(&self, directory: &Path, done_fn: F)
 870    where
 871        F: 'static + FnOnce(Option<PathBuf>, &mut MutableAppContext),
 872    {
 873        let app = self.weak_self.as_ref().unwrap().upgrade().unwrap();
 874        let foreground = self.foreground.clone();
 875        self.foreground_platform.prompt_for_new_path(
 876            directory,
 877            Box::new(move |path| {
 878                foreground
 879                    .spawn(async move { (done_fn)(path, &mut *app.borrow_mut()) })
 880                    .detach();
 881            }),
 882        );
 883    }
 884
 885    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 886    where
 887        E: Entity,
 888        E::Event: 'static,
 889        H: Handle<E>,
 890        F: 'static + FnMut(H, &E::Event, &mut Self),
 891    {
 892        self.subscribe_internal(handle, move |handle, event, cx| {
 893            callback(handle, event, cx);
 894            true
 895        })
 896    }
 897
 898    fn observe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 899    where
 900        E: Entity,
 901        E::Event: 'static,
 902        H: Handle<E>,
 903        F: 'static + FnMut(H, &mut Self),
 904    {
 905        self.observe_internal(handle, move |handle, cx| {
 906            callback(handle, cx);
 907            true
 908        })
 909    }
 910
 911    pub fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 912    where
 913        E: Entity,
 914        E::Event: 'static,
 915        H: Handle<E>,
 916        F: 'static + FnMut(H, &E::Event, &mut Self) -> bool,
 917    {
 918        let id = post_inc(&mut self.next_subscription_id);
 919        let emitter = handle.downgrade();
 920        self.subscriptions
 921            .lock()
 922            .entry(handle.id())
 923            .or_default()
 924            .insert(
 925                id,
 926                Box::new(move |payload, cx| {
 927                    if let Some(emitter) = H::upgrade_from(&emitter, cx.as_ref()) {
 928                        let payload = payload.downcast_ref().expect("downcast is type safe");
 929                        callback(emitter, payload, cx)
 930                    } else {
 931                        false
 932                    }
 933                }),
 934            );
 935        Subscription::Subscription {
 936            id,
 937            entity_id: handle.id(),
 938            subscriptions: Some(Arc::downgrade(&self.subscriptions)),
 939        }
 940    }
 941
 942    fn observe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 943    where
 944        E: Entity,
 945        E::Event: 'static,
 946        H: Handle<E>,
 947        F: 'static + FnMut(H, &mut Self) -> bool,
 948    {
 949        let id = post_inc(&mut self.next_subscription_id);
 950        let observed = handle.downgrade();
 951        self.observations
 952            .lock()
 953            .entry(handle.id())
 954            .or_default()
 955            .insert(
 956                id,
 957                Box::new(move |cx| {
 958                    if let Some(observed) = H::upgrade_from(&observed, cx) {
 959                        callback(observed, cx)
 960                    } else {
 961                        false
 962                    }
 963                }),
 964            );
 965        Subscription::Observation {
 966            id,
 967            entity_id: handle.id(),
 968            observations: Some(Arc::downgrade(&self.observations)),
 969        }
 970    }
 971
 972    pub(crate) fn notify_view(&mut self, window_id: usize, view_id: usize) {
 973        self.pending_effects
 974            .push_back(Effect::ViewNotification { window_id, view_id });
 975    }
 976
 977    pub fn dispatch_action<A: Action>(
 978        &mut self,
 979        window_id: usize,
 980        responder_chain: Vec<usize>,
 981        action: &A,
 982    ) {
 983        self.dispatch_action_any(window_id, &responder_chain, action);
 984    }
 985
 986    pub(crate) fn dispatch_action_any(
 987        &mut self,
 988        window_id: usize,
 989        path: &[usize],
 990        action: &dyn AnyAction,
 991    ) -> bool {
 992        self.pending_flushes += 1;
 993        let mut halted_dispatch = false;
 994
 995        for view_id in path.iter().rev() {
 996            if let Some(mut view) = self.cx.views.remove(&(window_id, *view_id)) {
 997                let type_id = view.as_any().type_id();
 998
 999                if let Some((name, mut handlers)) = self
1000                    .actions
1001                    .get_mut(&type_id)
1002                    .and_then(|h| h.remove_entry(&action.id()))
1003                {
1004                    for handler in handlers.iter_mut().rev() {
1005                        let halt_dispatch =
1006                            handler(view.as_mut(), action, self, window_id, *view_id);
1007                        if halt_dispatch {
1008                            halted_dispatch = true;
1009                            break;
1010                        }
1011                    }
1012                    self.actions
1013                        .get_mut(&type_id)
1014                        .unwrap()
1015                        .insert(name, handlers);
1016                }
1017
1018                self.cx.views.insert((window_id, *view_id), view);
1019
1020                if halted_dispatch {
1021                    break;
1022                }
1023            }
1024        }
1025
1026        if !halted_dispatch {
1027            self.dispatch_global_action_any(action);
1028        }
1029
1030        self.flush_effects();
1031        halted_dispatch
1032    }
1033
1034    pub fn dispatch_global_action<A: Action>(&mut self, action: A) {
1035        self.dispatch_global_action_any(&action);
1036    }
1037
1038    fn dispatch_global_action_any(&mut self, action: &dyn AnyAction) {
1039        if let Some((name, mut handlers)) = self.global_actions.remove_entry(&action.id()) {
1040            self.pending_flushes += 1;
1041            for handler in handlers.iter_mut().rev() {
1042                handler(action, self);
1043            }
1044            self.global_actions.insert(name, handlers);
1045            self.flush_effects();
1046        }
1047    }
1048
1049    pub fn add_bindings<T: IntoIterator<Item = keymap::Binding>>(&mut self, bindings: T) {
1050        self.keystroke_matcher.add_bindings(bindings);
1051    }
1052
1053    pub fn dispatch_keystroke(
1054        &mut self,
1055        window_id: usize,
1056        responder_chain: Vec<usize>,
1057        keystroke: &Keystroke,
1058    ) -> Result<bool> {
1059        let mut context_chain = Vec::new();
1060        let mut context = keymap::Context::default();
1061        for view_id in &responder_chain {
1062            if let Some(view) = self.cx.views.get(&(window_id, *view_id)) {
1063                context.extend(view.keymap_context(self.as_ref()));
1064                context_chain.push(context.clone());
1065            } else {
1066                return Err(anyhow!(
1067                    "View {} in responder chain does not exist",
1068                    view_id
1069                ));
1070            }
1071        }
1072
1073        let mut pending = false;
1074        for (i, cx) in context_chain.iter().enumerate().rev() {
1075            match self
1076                .keystroke_matcher
1077                .push_keystroke(keystroke.clone(), responder_chain[i], cx)
1078            {
1079                MatchResult::None => {}
1080                MatchResult::Pending => pending = true,
1081                MatchResult::Action(action) => {
1082                    if self.dispatch_action_any(window_id, &responder_chain[0..=i], action.as_ref())
1083                    {
1084                        return Ok(true);
1085                    }
1086                }
1087            }
1088        }
1089
1090        Ok(pending)
1091    }
1092
1093    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
1094    where
1095        T: Entity,
1096        F: FnOnce(&mut ModelContext<T>) -> T,
1097    {
1098        self.pending_flushes += 1;
1099        let model_id = post_inc(&mut self.next_entity_id);
1100        let handle = ModelHandle::new(model_id, &self.cx.ref_counts);
1101        let mut cx = ModelContext::new(self, model_id);
1102        let model = build_model(&mut cx);
1103        self.cx.models.insert(model_id, Box::new(model));
1104        self.flush_effects();
1105        handle
1106    }
1107
1108    pub fn add_window<T, F>(
1109        &mut self,
1110        window_options: WindowOptions,
1111        build_root_view: F,
1112    ) -> (usize, ViewHandle<T>)
1113    where
1114        T: View,
1115        F: FnOnce(&mut ViewContext<T>) -> T,
1116    {
1117        self.pending_flushes += 1;
1118        let window_id = post_inc(&mut self.next_window_id);
1119        let root_view = self.add_view(window_id, build_root_view);
1120
1121        self.cx.windows.insert(
1122            window_id,
1123            Window {
1124                root_view: root_view.clone().into(),
1125                focused_view_id: root_view.id(),
1126                invalidation: None,
1127            },
1128        );
1129        self.open_platform_window(window_id, window_options);
1130        root_view.update(self, |view, cx| {
1131            view.on_focus(cx);
1132            cx.notify();
1133        });
1134        self.flush_effects();
1135
1136        (window_id, root_view)
1137    }
1138
1139    pub fn remove_window(&mut self, window_id: usize) {
1140        self.cx.windows.remove(&window_id);
1141        self.presenters_and_platform_windows.remove(&window_id);
1142        self.remove_dropped_entities();
1143    }
1144
1145    fn open_platform_window(&mut self, window_id: usize, window_options: WindowOptions) {
1146        let mut window =
1147            self.cx
1148                .platform
1149                .open_window(window_id, window_options, self.foreground.clone());
1150        let presenter = Rc::new(RefCell::new(
1151            self.build_presenter(window_id, window.titlebar_height()),
1152        ));
1153
1154        {
1155            let mut app = self.upgrade();
1156            let presenter = presenter.clone();
1157            window.on_event(Box::new(move |event| {
1158                app.update(|cx| {
1159                    if let Event::KeyDown { keystroke, .. } = &event {
1160                        if cx
1161                            .dispatch_keystroke(
1162                                window_id,
1163                                presenter.borrow().dispatch_path(cx.as_ref()),
1164                                keystroke,
1165                            )
1166                            .unwrap()
1167                        {
1168                            return;
1169                        }
1170                    }
1171
1172                    presenter.borrow_mut().dispatch_event(event, cx);
1173                })
1174            }));
1175        }
1176
1177        {
1178            let mut app = self.upgrade();
1179            let presenter = presenter.clone();
1180            window.on_resize(Box::new(move |window| {
1181                app.update(|cx| {
1182                    let scene = presenter.borrow_mut().build_scene(
1183                        window.size(),
1184                        window.scale_factor(),
1185                        cx,
1186                    );
1187                    window.present_scene(scene);
1188                })
1189            }));
1190        }
1191
1192        {
1193            let mut app = self.upgrade();
1194            window.on_close(Box::new(move || {
1195                app.update(|cx| cx.remove_window(window_id));
1196            }));
1197        }
1198
1199        self.presenters_and_platform_windows
1200            .insert(window_id, (presenter.clone(), window));
1201
1202        self.on_debug_elements(window_id, move |cx| {
1203            presenter.borrow().debug_elements(cx).unwrap()
1204        });
1205    }
1206
1207    pub fn build_presenter(&self, window_id: usize, titlebar_height: f32) -> Presenter {
1208        Presenter::new(
1209            window_id,
1210            titlebar_height,
1211            self.cx.font_cache.clone(),
1212            TextLayoutCache::new(self.cx.platform.fonts()),
1213            self.assets.clone(),
1214            self,
1215        )
1216    }
1217
1218    pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
1219    where
1220        T: View,
1221        F: FnOnce(&mut ViewContext<T>) -> T,
1222    {
1223        self.add_option_view(window_id, |cx| Some(build_view(cx)))
1224            .unwrap()
1225    }
1226
1227    pub fn add_option_view<T, F>(
1228        &mut self,
1229        window_id: usize,
1230        build_view: F,
1231    ) -> Option<ViewHandle<T>>
1232    where
1233        T: View,
1234        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1235    {
1236        let view_id = post_inc(&mut self.next_entity_id);
1237        self.pending_flushes += 1;
1238        let handle = ViewHandle::new(window_id, view_id, &self.cx.ref_counts);
1239        let mut cx = ViewContext::new(self, window_id, view_id);
1240        let handle = if let Some(view) = build_view(&mut cx) {
1241            self.cx.views.insert((window_id, view_id), Box::new(view));
1242            if let Some(window) = self.cx.windows.get_mut(&window_id) {
1243                window
1244                    .invalidation
1245                    .get_or_insert_with(Default::default)
1246                    .updated
1247                    .insert(view_id);
1248            }
1249            Some(handle)
1250        } else {
1251            None
1252        };
1253        self.flush_effects();
1254        handle
1255    }
1256
1257    fn remove_dropped_entities(&mut self) {
1258        loop {
1259            let (dropped_models, dropped_views, dropped_values) =
1260                self.cx.ref_counts.lock().take_dropped();
1261            if dropped_models.is_empty() && dropped_views.is_empty() && dropped_values.is_empty() {
1262                break;
1263            }
1264
1265            for model_id in dropped_models {
1266                self.subscriptions.lock().remove(&model_id);
1267                self.observations.lock().remove(&model_id);
1268                let mut model = self.cx.models.remove(&model_id).unwrap();
1269                model.release(self);
1270            }
1271
1272            for (window_id, view_id) in dropped_views {
1273                self.subscriptions.lock().remove(&view_id);
1274                self.observations.lock().remove(&view_id);
1275                let mut view = self.cx.views.remove(&(window_id, view_id)).unwrap();
1276                view.release(self);
1277                let change_focus_to = self.cx.windows.get_mut(&window_id).and_then(|window| {
1278                    window
1279                        .invalidation
1280                        .get_or_insert_with(Default::default)
1281                        .removed
1282                        .push(view_id);
1283                    if window.focused_view_id == view_id {
1284                        Some(window.root_view.id())
1285                    } else {
1286                        None
1287                    }
1288                });
1289
1290                if let Some(view_id) = change_focus_to {
1291                    self.focus(window_id, view_id);
1292                }
1293            }
1294
1295            let mut values = self.cx.values.write();
1296            for key in dropped_values {
1297                values.remove(&key);
1298            }
1299        }
1300    }
1301
1302    fn flush_effects(&mut self) {
1303        self.pending_flushes = self.pending_flushes.saturating_sub(1);
1304
1305        if !self.flushing_effects && self.pending_flushes == 0 {
1306            self.flushing_effects = true;
1307
1308            let mut refreshing = false;
1309            loop {
1310                if let Some(effect) = self.pending_effects.pop_front() {
1311                    match effect {
1312                        Effect::Event { entity_id, payload } => self.emit_event(entity_id, payload),
1313                        Effect::ModelNotification { model_id } => {
1314                            self.notify_model_observers(model_id)
1315                        }
1316                        Effect::ViewNotification { window_id, view_id } => {
1317                            self.notify_view_observers(window_id, view_id)
1318                        }
1319                        Effect::Focus { window_id, view_id } => {
1320                            self.focus(window_id, view_id);
1321                        }
1322                        Effect::RefreshWindows => {
1323                            refreshing = true;
1324                        }
1325                    }
1326                    self.remove_dropped_entities();
1327                } else {
1328                    self.remove_dropped_entities();
1329                    if refreshing {
1330                        self.perform_window_refresh();
1331                    } else {
1332                        self.update_windows();
1333                    }
1334
1335                    if self.pending_effects.is_empty() {
1336                        self.flushing_effects = false;
1337                        break;
1338                    } else {
1339                        refreshing = false;
1340                    }
1341                }
1342            }
1343        }
1344    }
1345
1346    fn update_windows(&mut self) {
1347        let mut invalidations = HashMap::new();
1348        for (window_id, window) in &mut self.cx.windows {
1349            if let Some(invalidation) = window.invalidation.take() {
1350                invalidations.insert(*window_id, invalidation);
1351            }
1352        }
1353
1354        for (window_id, invalidation) in invalidations {
1355            if let Some((presenter, mut window)) =
1356                self.presenters_and_platform_windows.remove(&window_id)
1357            {
1358                {
1359                    let mut presenter = presenter.borrow_mut();
1360                    presenter.invalidate(invalidation, self.as_ref());
1361                    let scene = presenter.build_scene(window.size(), window.scale_factor(), self);
1362                    window.present_scene(scene);
1363                }
1364                self.presenters_and_platform_windows
1365                    .insert(window_id, (presenter, window));
1366            }
1367        }
1368    }
1369
1370    pub fn refresh_windows(&mut self) {
1371        self.pending_effects.push_back(Effect::RefreshWindows);
1372    }
1373
1374    fn perform_window_refresh(&mut self) {
1375        let mut presenters = mem::take(&mut self.presenters_and_platform_windows);
1376        for (window_id, (presenter, window)) in &mut presenters {
1377            let invalidation = self
1378                .cx
1379                .windows
1380                .get_mut(&window_id)
1381                .unwrap()
1382                .invalidation
1383                .take();
1384            let mut presenter = presenter.borrow_mut();
1385            presenter.refresh(invalidation, self.as_ref());
1386            let scene = presenter.build_scene(window.size(), window.scale_factor(), self);
1387            window.present_scene(scene);
1388        }
1389        self.presenters_and_platform_windows = presenters;
1390    }
1391
1392    fn emit_event(&mut self, entity_id: usize, payload: Box<dyn Any>) {
1393        let callbacks = self.subscriptions.lock().remove(&entity_id);
1394        if let Some(callbacks) = callbacks {
1395            for (id, mut callback) in callbacks {
1396                let alive = callback(payload.as_ref(), self);
1397                if alive {
1398                    self.subscriptions
1399                        .lock()
1400                        .entry(entity_id)
1401                        .or_default()
1402                        .insert(id, callback);
1403                }
1404            }
1405        }
1406    }
1407
1408    fn notify_model_observers(&mut self, observed_id: usize) {
1409        let callbacks = self.observations.lock().remove(&observed_id);
1410        if let Some(callbacks) = callbacks {
1411            if self.cx.models.contains_key(&observed_id) {
1412                for (id, mut callback) in callbacks {
1413                    let alive = callback(self);
1414                    if alive {
1415                        self.observations
1416                            .lock()
1417                            .entry(observed_id)
1418                            .or_default()
1419                            .insert(id, callback);
1420                    }
1421                }
1422            }
1423        }
1424    }
1425
1426    fn notify_view_observers(&mut self, observed_window_id: usize, observed_view_id: usize) {
1427        if let Some(window) = self.cx.windows.get_mut(&observed_window_id) {
1428            window
1429                .invalidation
1430                .get_or_insert_with(Default::default)
1431                .updated
1432                .insert(observed_view_id);
1433        }
1434
1435        let callbacks = self.observations.lock().remove(&observed_view_id);
1436        if let Some(callbacks) = callbacks {
1437            if self
1438                .cx
1439                .views
1440                .contains_key(&(observed_window_id, observed_view_id))
1441            {
1442                for (id, mut callback) in callbacks {
1443                    let alive = callback(self);
1444                    if alive {
1445                        self.observations
1446                            .lock()
1447                            .entry(observed_view_id)
1448                            .or_default()
1449                            .insert(id, callback);
1450                    }
1451                }
1452            }
1453        }
1454    }
1455
1456    fn focus(&mut self, window_id: usize, focused_id: usize) {
1457        if self
1458            .cx
1459            .windows
1460            .get(&window_id)
1461            .map(|w| w.focused_view_id)
1462            .map_or(false, |cur_focused| cur_focused == focused_id)
1463        {
1464            return;
1465        }
1466
1467        self.pending_flushes += 1;
1468
1469        let blurred_id = self.cx.windows.get_mut(&window_id).map(|window| {
1470            let blurred_id = window.focused_view_id;
1471            window.focused_view_id = focused_id;
1472            blurred_id
1473        });
1474
1475        if let Some(blurred_id) = blurred_id {
1476            if let Some(mut blurred_view) = self.cx.views.remove(&(window_id, blurred_id)) {
1477                blurred_view.on_blur(self, window_id, blurred_id);
1478                self.cx.views.insert((window_id, blurred_id), blurred_view);
1479            }
1480        }
1481
1482        if let Some(mut focused_view) = self.cx.views.remove(&(window_id, focused_id)) {
1483            focused_view.on_focus(self, window_id, focused_id);
1484            self.cx.views.insert((window_id, focused_id), focused_view);
1485        }
1486
1487        self.flush_effects();
1488    }
1489
1490    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
1491    where
1492        F: FnOnce(AsyncAppContext) -> Fut,
1493        Fut: 'static + Future<Output = T>,
1494        T: 'static,
1495    {
1496        let cx = self.to_async();
1497        self.foreground.spawn(f(cx))
1498    }
1499
1500    pub fn to_async(&self) -> AsyncAppContext {
1501        AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
1502    }
1503
1504    pub fn write_to_clipboard(&self, item: ClipboardItem) {
1505        self.cx.platform.write_to_clipboard(item);
1506    }
1507
1508    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1509        self.cx.platform.read_from_clipboard()
1510    }
1511}
1512
1513impl ReadModel for MutableAppContext {
1514    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1515        if let Some(model) = self.cx.models.get(&handle.model_id) {
1516            model
1517                .as_any()
1518                .downcast_ref()
1519                .expect("downcast is type safe")
1520        } else {
1521            panic!("circular model reference");
1522        }
1523    }
1524}
1525
1526impl UpdateModel for MutableAppContext {
1527    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
1528    where
1529        T: Entity,
1530        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
1531    {
1532        if let Some(mut model) = self.cx.models.remove(&handle.model_id) {
1533            self.pending_flushes += 1;
1534            let mut cx = ModelContext::new(self, handle.model_id);
1535            let result = update(
1536                model
1537                    .as_any_mut()
1538                    .downcast_mut()
1539                    .expect("downcast is type safe"),
1540                &mut cx,
1541            );
1542            self.cx.models.insert(handle.model_id, model);
1543            self.flush_effects();
1544            result
1545        } else {
1546            panic!("circular model update");
1547        }
1548    }
1549}
1550
1551impl UpgradeModelHandle for MutableAppContext {
1552    fn upgrade_model_handle<T: Entity>(
1553        &self,
1554        handle: WeakModelHandle<T>,
1555    ) -> Option<ModelHandle<T>> {
1556        self.cx.upgrade_model_handle(handle)
1557    }
1558}
1559
1560impl ReadView for MutableAppContext {
1561    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1562        if let Some(view) = self.cx.views.get(&(handle.window_id, handle.view_id)) {
1563            view.as_any().downcast_ref().expect("downcast is type safe")
1564        } else {
1565            panic!("circular view reference");
1566        }
1567    }
1568}
1569
1570impl UpdateView for MutableAppContext {
1571    fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
1572    where
1573        T: View,
1574        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
1575    {
1576        self.pending_flushes += 1;
1577        let mut view = self
1578            .cx
1579            .views
1580            .remove(&(handle.window_id, handle.view_id))
1581            .expect("circular view update");
1582
1583        let mut cx = ViewContext::new(self, handle.window_id, handle.view_id);
1584        let result = update(
1585            view.as_any_mut()
1586                .downcast_mut()
1587                .expect("downcast is type safe"),
1588            &mut cx,
1589        );
1590        self.cx
1591            .views
1592            .insert((handle.window_id, handle.view_id), view);
1593        self.flush_effects();
1594        result
1595    }
1596}
1597
1598impl AsRef<AppContext> for MutableAppContext {
1599    fn as_ref(&self) -> &AppContext {
1600        &self.cx
1601    }
1602}
1603
1604impl Deref for MutableAppContext {
1605    type Target = AppContext;
1606
1607    fn deref(&self) -> &Self::Target {
1608        &self.cx
1609    }
1610}
1611
1612pub struct AppContext {
1613    models: HashMap<usize, Box<dyn AnyModel>>,
1614    views: HashMap<(usize, usize), Box<dyn AnyView>>,
1615    windows: HashMap<usize, Window>,
1616    values: RwLock<HashMap<(TypeId, usize), Box<dyn Any>>>,
1617    background: Arc<executor::Background>,
1618    ref_counts: Arc<Mutex<RefCounts>>,
1619    font_cache: Arc<FontCache>,
1620    platform: Arc<dyn Platform>,
1621}
1622
1623impl AppContext {
1624    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
1625        self.windows
1626            .get(&window_id)
1627            .map(|window| window.root_view.id())
1628    }
1629
1630    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
1631        self.windows
1632            .get(&window_id)
1633            .map(|window| window.focused_view_id)
1634    }
1635
1636    pub fn render_view(
1637        &self,
1638        window_id: usize,
1639        view_id: usize,
1640        titlebar_height: f32,
1641        refreshing: bool,
1642    ) -> Result<ElementBox> {
1643        self.views
1644            .get(&(window_id, view_id))
1645            .map(|v| v.render(window_id, view_id, titlebar_height, refreshing, self))
1646            .ok_or(anyhow!("view not found"))
1647    }
1648
1649    pub fn render_views(
1650        &self,
1651        window_id: usize,
1652        titlebar_height: f32,
1653    ) -> HashMap<usize, ElementBox> {
1654        self.views
1655            .iter()
1656            .filter_map(|((win_id, view_id), view)| {
1657                if *win_id == window_id {
1658                    Some((
1659                        *view_id,
1660                        view.render(*win_id, *view_id, titlebar_height, false, self),
1661                    ))
1662                } else {
1663                    None
1664                }
1665            })
1666            .collect::<HashMap<_, ElementBox>>()
1667    }
1668
1669    pub fn render_cx<V: View>(
1670        &self,
1671        window_id: usize,
1672        view_id: usize,
1673        titlebar_height: f32,
1674        refreshing: bool,
1675    ) -> RenderContext<V> {
1676        RenderContext {
1677            app: self,
1678            titlebar_height,
1679            refreshing,
1680            window_id,
1681            view_id,
1682            view_type: PhantomData,
1683        }
1684    }
1685
1686    pub fn background(&self) -> &Arc<executor::Background> {
1687        &self.background
1688    }
1689
1690    pub fn font_cache(&self) -> &Arc<FontCache> {
1691        &self.font_cache
1692    }
1693
1694    pub fn platform(&self) -> &Arc<dyn Platform> {
1695        &self.platform
1696    }
1697
1698    pub fn value<Tag: 'static, T: 'static + Default>(&self, id: usize) -> ValueHandle<T> {
1699        let key = (TypeId::of::<Tag>(), id);
1700        self.values
1701            .write()
1702            .entry(key)
1703            .or_insert_with(|| Box::new(T::default()));
1704        ValueHandle::new(TypeId::of::<Tag>(), id, &self.ref_counts)
1705    }
1706}
1707
1708impl ReadModel for AppContext {
1709    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1710        if let Some(model) = self.models.get(&handle.model_id) {
1711            model
1712                .as_any()
1713                .downcast_ref()
1714                .expect("downcast should be type safe")
1715        } else {
1716            panic!("circular model reference");
1717        }
1718    }
1719}
1720
1721impl UpgradeModelHandle for AppContext {
1722    fn upgrade_model_handle<T: Entity>(
1723        &self,
1724        handle: WeakModelHandle<T>,
1725    ) -> Option<ModelHandle<T>> {
1726        if self.models.contains_key(&handle.model_id) {
1727            Some(ModelHandle::new(handle.model_id, &self.ref_counts))
1728        } else {
1729            None
1730        }
1731    }
1732}
1733
1734impl ReadView for AppContext {
1735    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1736        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
1737            view.as_any()
1738                .downcast_ref()
1739                .expect("downcast should be type safe")
1740        } else {
1741            panic!("circular view reference");
1742        }
1743    }
1744}
1745
1746struct Window {
1747    root_view: AnyViewHandle,
1748    focused_view_id: usize,
1749    invalidation: Option<WindowInvalidation>,
1750}
1751
1752#[derive(Default, Clone)]
1753pub struct WindowInvalidation {
1754    pub updated: HashSet<usize>,
1755    pub removed: Vec<usize>,
1756}
1757
1758pub enum Effect {
1759    Event {
1760        entity_id: usize,
1761        payload: Box<dyn Any>,
1762    },
1763    ModelNotification {
1764        model_id: usize,
1765    },
1766    ViewNotification {
1767        window_id: usize,
1768        view_id: usize,
1769    },
1770    Focus {
1771        window_id: usize,
1772        view_id: usize,
1773    },
1774    RefreshWindows,
1775}
1776
1777impl Debug for Effect {
1778    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1779        match self {
1780            Effect::Event { entity_id, .. } => f
1781                .debug_struct("Effect::Event")
1782                .field("entity_id", entity_id)
1783                .finish(),
1784            Effect::ModelNotification { model_id } => f
1785                .debug_struct("Effect::ModelNotification")
1786                .field("model_id", model_id)
1787                .finish(),
1788            Effect::ViewNotification { window_id, view_id } => f
1789                .debug_struct("Effect::ViewNotification")
1790                .field("window_id", window_id)
1791                .field("view_id", view_id)
1792                .finish(),
1793            Effect::Focus { window_id, view_id } => f
1794                .debug_struct("Effect::Focus")
1795                .field("window_id", window_id)
1796                .field("view_id", view_id)
1797                .finish(),
1798            Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
1799        }
1800    }
1801}
1802
1803pub trait AnyModel {
1804    fn as_any(&self) -> &dyn Any;
1805    fn as_any_mut(&mut self) -> &mut dyn Any;
1806    fn release(&mut self, cx: &mut MutableAppContext);
1807}
1808
1809impl<T> AnyModel for T
1810where
1811    T: Entity,
1812{
1813    fn as_any(&self) -> &dyn Any {
1814        self
1815    }
1816
1817    fn as_any_mut(&mut self) -> &mut dyn Any {
1818        self
1819    }
1820
1821    fn release(&mut self, cx: &mut MutableAppContext) {
1822        self.release(cx);
1823    }
1824}
1825
1826pub trait AnyView {
1827    fn as_any(&self) -> &dyn Any;
1828    fn as_any_mut(&mut self) -> &mut dyn Any;
1829    fn release(&mut self, cx: &mut MutableAppContext);
1830    fn ui_name(&self) -> &'static str;
1831    fn render<'a>(
1832        &self,
1833        window_id: usize,
1834        view_id: usize,
1835        titlebar_height: f32,
1836        refreshing: bool,
1837        cx: &AppContext,
1838    ) -> ElementBox;
1839    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
1840    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
1841    fn keymap_context(&self, cx: &AppContext) -> keymap::Context;
1842}
1843
1844impl<T> AnyView for T
1845where
1846    T: View,
1847{
1848    fn as_any(&self) -> &dyn Any {
1849        self
1850    }
1851
1852    fn as_any_mut(&mut self) -> &mut dyn Any {
1853        self
1854    }
1855
1856    fn release(&mut self, cx: &mut MutableAppContext) {
1857        self.release(cx);
1858    }
1859
1860    fn ui_name(&self) -> &'static str {
1861        T::ui_name()
1862    }
1863
1864    fn render<'a>(
1865        &self,
1866        window_id: usize,
1867        view_id: usize,
1868        titlebar_height: f32,
1869        refreshing: bool,
1870        cx: &AppContext,
1871    ) -> ElementBox {
1872        View::render(
1873            self,
1874            &RenderContext {
1875                window_id,
1876                view_id,
1877                app: cx,
1878                view_type: PhantomData::<T>,
1879                titlebar_height,
1880                refreshing,
1881            },
1882        )
1883    }
1884
1885    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
1886        let mut cx = ViewContext::new(cx, window_id, view_id);
1887        View::on_focus(self, &mut cx);
1888    }
1889
1890    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
1891        let mut cx = ViewContext::new(cx, window_id, view_id);
1892        View::on_blur(self, &mut cx);
1893    }
1894
1895    fn keymap_context(&self, cx: &AppContext) -> keymap::Context {
1896        View::keymap_context(self, cx)
1897    }
1898}
1899
1900pub struct ModelContext<'a, T: ?Sized> {
1901    app: &'a mut MutableAppContext,
1902    model_id: usize,
1903    model_type: PhantomData<T>,
1904    halt_stream: bool,
1905}
1906
1907impl<'a, T: Entity> ModelContext<'a, T> {
1908    fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
1909        Self {
1910            app,
1911            model_id,
1912            model_type: PhantomData,
1913            halt_stream: false,
1914        }
1915    }
1916
1917    pub fn background(&self) -> &Arc<executor::Background> {
1918        &self.app.cx.background
1919    }
1920
1921    pub fn halt_stream(&mut self) {
1922        self.halt_stream = true;
1923    }
1924
1925    pub fn model_id(&self) -> usize {
1926        self.model_id
1927    }
1928
1929    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
1930    where
1931        S: Entity,
1932        F: FnOnce(&mut ModelContext<S>) -> S,
1933    {
1934        self.app.add_model(build_model)
1935    }
1936
1937    pub fn emit(&mut self, payload: T::Event) {
1938        self.app.pending_effects.push_back(Effect::Event {
1939            entity_id: self.model_id,
1940            payload: Box::new(payload),
1941        });
1942    }
1943
1944    pub fn notify(&mut self) {
1945        self.app
1946            .pending_effects
1947            .push_back(Effect::ModelNotification {
1948                model_id: self.model_id,
1949            });
1950    }
1951
1952    pub fn subscribe<S: Entity, F>(
1953        &mut self,
1954        handle: &ModelHandle<S>,
1955        mut callback: F,
1956    ) -> Subscription
1957    where
1958        S::Event: 'static,
1959        F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
1960    {
1961        let subscriber = self.handle().downgrade();
1962        self.app
1963            .subscribe_internal(handle, move |emitter, event, cx| {
1964                if let Some(subscriber) = subscriber.upgrade(cx) {
1965                    subscriber.update(cx, |subscriber, cx| {
1966                        callback(subscriber, emitter, event, cx);
1967                    });
1968                    true
1969                } else {
1970                    false
1971                }
1972            })
1973    }
1974
1975    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
1976    where
1977        S: Entity,
1978        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
1979    {
1980        let observer = self.handle().downgrade();
1981        self.app.observe_internal(handle, move |observed, cx| {
1982            if let Some(observer) = observer.upgrade(cx) {
1983                observer.update(cx, |observer, cx| {
1984                    callback(observer, observed, cx);
1985                });
1986                true
1987            } else {
1988                false
1989            }
1990        })
1991    }
1992
1993    pub fn handle(&self) -> ModelHandle<T> {
1994        ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
1995    }
1996
1997    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
1998    where
1999        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
2000        Fut: 'static + Future<Output = S>,
2001        S: 'static,
2002    {
2003        let handle = self.handle();
2004        self.app.spawn(|cx| f(handle, cx))
2005    }
2006
2007    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
2008    where
2009        F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
2010        Fut: 'static + Future<Output = S>,
2011        S: 'static,
2012    {
2013        let handle = self.handle().downgrade();
2014        self.app.spawn(|cx| f(handle, cx))
2015    }
2016}
2017
2018impl<M> AsRef<AppContext> for ModelContext<'_, M> {
2019    fn as_ref(&self) -> &AppContext {
2020        &self.app.cx
2021    }
2022}
2023
2024impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
2025    fn as_mut(&mut self) -> &mut MutableAppContext {
2026        self.app
2027    }
2028}
2029
2030impl<M> ReadModel for ModelContext<'_, M> {
2031    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2032        self.app.read_model(handle)
2033    }
2034}
2035
2036impl<M> UpdateModel for ModelContext<'_, M> {
2037    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
2038    where
2039        T: Entity,
2040        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2041    {
2042        self.app.update_model(handle, update)
2043    }
2044}
2045
2046impl<M> UpgradeModelHandle for ModelContext<'_, M> {
2047    fn upgrade_model_handle<T: Entity>(
2048        &self,
2049        handle: WeakModelHandle<T>,
2050    ) -> Option<ModelHandle<T>> {
2051        self.cx.upgrade_model_handle(handle)
2052    }
2053}
2054
2055impl<M> Deref for ModelContext<'_, M> {
2056    type Target = MutableAppContext;
2057
2058    fn deref(&self) -> &Self::Target {
2059        &self.app
2060    }
2061}
2062
2063impl<M> DerefMut for ModelContext<'_, M> {
2064    fn deref_mut(&mut self) -> &mut Self::Target {
2065        &mut self.app
2066    }
2067}
2068
2069pub struct ViewContext<'a, T: ?Sized> {
2070    app: &'a mut MutableAppContext,
2071    window_id: usize,
2072    view_id: usize,
2073    view_type: PhantomData<T>,
2074    halt_action_dispatch: bool,
2075}
2076
2077impl<'a, T: View> ViewContext<'a, T> {
2078    fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
2079        Self {
2080            app,
2081            window_id,
2082            view_id,
2083            view_type: PhantomData,
2084            halt_action_dispatch: true,
2085        }
2086    }
2087
2088    pub fn handle(&self) -> ViewHandle<T> {
2089        ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
2090    }
2091
2092    pub fn window_id(&self) -> usize {
2093        self.window_id
2094    }
2095
2096    pub fn view_id(&self) -> usize {
2097        self.view_id
2098    }
2099
2100    pub fn foreground(&self) -> &Rc<executor::Foreground> {
2101        self.app.foreground()
2102    }
2103
2104    pub fn background_executor(&self) -> &Arc<executor::Background> {
2105        &self.app.cx.background
2106    }
2107
2108    pub fn platform(&self) -> Arc<dyn Platform> {
2109        self.app.platform()
2110    }
2111
2112    pub fn prompt<F>(&self, level: PromptLevel, msg: &str, answers: &[&str], done_fn: F)
2113    where
2114        F: 'static + FnOnce(usize, &mut MutableAppContext),
2115    {
2116        self.app
2117            .prompt(self.window_id, level, msg, answers, done_fn)
2118    }
2119
2120    pub fn prompt_for_paths<F>(&self, options: PathPromptOptions, done_fn: F)
2121    where
2122        F: 'static + FnOnce(Option<Vec<PathBuf>>, &mut MutableAppContext),
2123    {
2124        self.app.prompt_for_paths(options, done_fn)
2125    }
2126
2127    pub fn prompt_for_new_path<F>(&self, directory: &Path, done_fn: F)
2128    where
2129        F: 'static + FnOnce(Option<PathBuf>, &mut MutableAppContext),
2130    {
2131        self.app.prompt_for_new_path(directory, done_fn)
2132    }
2133
2134    pub fn debug_elements(&self) -> crate::json::Value {
2135        self.app.debug_elements(self.window_id).unwrap()
2136    }
2137
2138    pub fn focus<S>(&mut self, handle: S)
2139    where
2140        S: Into<AnyViewHandle>,
2141    {
2142        let handle = handle.into();
2143        self.app.pending_effects.push_back(Effect::Focus {
2144            window_id: handle.window_id,
2145            view_id: handle.view_id,
2146        });
2147    }
2148
2149    pub fn focus_self(&mut self) {
2150        self.app.pending_effects.push_back(Effect::Focus {
2151            window_id: self.window_id,
2152            view_id: self.view_id,
2153        });
2154    }
2155
2156    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2157    where
2158        S: Entity,
2159        F: FnOnce(&mut ModelContext<S>) -> S,
2160    {
2161        self.app.add_model(build_model)
2162    }
2163
2164    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
2165    where
2166        S: View,
2167        F: FnOnce(&mut ViewContext<S>) -> S,
2168    {
2169        self.app.add_view(self.window_id, build_view)
2170    }
2171
2172    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
2173    where
2174        S: View,
2175        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
2176    {
2177        self.app.add_option_view(self.window_id, build_view)
2178    }
2179
2180    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
2181    where
2182        E: Entity,
2183        E::Event: 'static,
2184        H: Handle<E>,
2185        F: 'static + FnMut(&mut T, H, &E::Event, &mut ViewContext<T>),
2186    {
2187        let subscriber = self.handle().downgrade();
2188        self.app
2189            .subscribe_internal(handle, move |emitter, event, cx| {
2190                if let Some(subscriber) = subscriber.upgrade(cx) {
2191                    subscriber.update(cx, |subscriber, cx| {
2192                        callback(subscriber, emitter, event, cx);
2193                    });
2194                    true
2195                } else {
2196                    false
2197                }
2198            })
2199    }
2200
2201    pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2202    where
2203        E: Entity,
2204        H: Handle<E>,
2205        F: 'static + FnMut(&mut T, H, &mut ViewContext<T>),
2206    {
2207        let observer = self.handle().downgrade();
2208        self.app.observe_internal(handle, move |observed, cx| {
2209            if let Some(observer) = observer.upgrade(cx) {
2210                observer.update(cx, |observer, cx| {
2211                    callback(observer, observed, cx);
2212                });
2213                true
2214            } else {
2215                false
2216            }
2217        })
2218    }
2219
2220    pub fn emit(&mut self, payload: T::Event) {
2221        self.app.pending_effects.push_back(Effect::Event {
2222            entity_id: self.view_id,
2223            payload: Box::new(payload),
2224        });
2225    }
2226
2227    pub fn notify(&mut self) {
2228        self.app.notify_view(self.window_id, self.view_id);
2229    }
2230
2231    pub fn propagate_action(&mut self) {
2232        self.halt_action_dispatch = false;
2233    }
2234
2235    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2236    where
2237        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
2238        Fut: 'static + Future<Output = S>,
2239        S: 'static,
2240    {
2241        let handle = self.handle();
2242        self.app.spawn(|cx| f(handle, cx))
2243    }
2244}
2245
2246pub struct RenderContext<'a, T: View> {
2247    pub app: &'a AppContext,
2248    pub titlebar_height: f32,
2249    pub refreshing: bool,
2250    window_id: usize,
2251    view_id: usize,
2252    view_type: PhantomData<T>,
2253}
2254
2255impl<'a, T: View> RenderContext<'a, T> {
2256    pub fn handle(&self) -> WeakViewHandle<T> {
2257        WeakViewHandle::new(self.window_id, self.view_id)
2258    }
2259}
2260
2261impl AsRef<AppContext> for &AppContext {
2262    fn as_ref(&self) -> &AppContext {
2263        self
2264    }
2265}
2266
2267impl<V: View> Deref for RenderContext<'_, V> {
2268    type Target = AppContext;
2269
2270    fn deref(&self) -> &Self::Target {
2271        &self.app
2272    }
2273}
2274
2275impl<V: View> ReadModel for RenderContext<'_, V> {
2276    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2277        self.app.read_model(handle)
2278    }
2279}
2280
2281impl<M> AsRef<AppContext> for ViewContext<'_, M> {
2282    fn as_ref(&self) -> &AppContext {
2283        &self.app.cx
2284    }
2285}
2286
2287impl<M> Deref for ViewContext<'_, M> {
2288    type Target = MutableAppContext;
2289
2290    fn deref(&self) -> &Self::Target {
2291        &self.app
2292    }
2293}
2294
2295impl<M> DerefMut for ViewContext<'_, M> {
2296    fn deref_mut(&mut self) -> &mut Self::Target {
2297        &mut self.app
2298    }
2299}
2300
2301impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
2302    fn as_mut(&mut self) -> &mut MutableAppContext {
2303        self.app
2304    }
2305}
2306
2307impl<V> ReadModel for ViewContext<'_, V> {
2308    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2309        self.app.read_model(handle)
2310    }
2311}
2312
2313impl<V> UpgradeModelHandle for ViewContext<'_, V> {
2314    fn upgrade_model_handle<T: Entity>(
2315        &self,
2316        handle: WeakModelHandle<T>,
2317    ) -> Option<ModelHandle<T>> {
2318        self.cx.upgrade_model_handle(handle)
2319    }
2320}
2321
2322impl<V: View> UpdateModel for ViewContext<'_, V> {
2323    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
2324    where
2325        T: Entity,
2326        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2327    {
2328        self.app.update_model(handle, update)
2329    }
2330}
2331
2332impl<V: View> ReadView for ViewContext<'_, V> {
2333    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2334        self.app.read_view(handle)
2335    }
2336}
2337
2338impl<V: View> UpdateView for ViewContext<'_, V> {
2339    fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
2340    where
2341        T: View,
2342        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2343    {
2344        self.app.update_view(handle, update)
2345    }
2346}
2347
2348pub trait Handle<T> {
2349    type Weak: 'static;
2350    fn id(&self) -> usize;
2351    fn location(&self) -> EntityLocation;
2352    fn downgrade(&self) -> Self::Weak;
2353    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2354    where
2355        Self: Sized;
2356}
2357
2358#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
2359pub enum EntityLocation {
2360    Model(usize),
2361    View(usize, usize),
2362}
2363
2364pub struct ModelHandle<T> {
2365    model_id: usize,
2366    model_type: PhantomData<T>,
2367    ref_counts: Arc<Mutex<RefCounts>>,
2368}
2369
2370impl<T: Entity> ModelHandle<T> {
2371    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2372        ref_counts.lock().inc_model(model_id);
2373        Self {
2374            model_id,
2375            model_type: PhantomData,
2376            ref_counts: ref_counts.clone(),
2377        }
2378    }
2379
2380    pub fn downgrade(&self) -> WeakModelHandle<T> {
2381        WeakModelHandle::new(self.model_id)
2382    }
2383
2384    pub fn id(&self) -> usize {
2385        self.model_id
2386    }
2387
2388    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
2389        cx.read_model(self)
2390    }
2391
2392    pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
2393    where
2394        C: ReadModelWith,
2395        F: FnOnce(&T, &AppContext) -> S,
2396    {
2397        cx.read_model_with(self, read)
2398    }
2399
2400    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2401    where
2402        C: UpdateModel,
2403        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2404    {
2405        cx.update_model(self, update)
2406    }
2407
2408    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
2409        let (mut tx, mut rx) = mpsc::channel(1);
2410        let mut cx = cx.cx.borrow_mut();
2411        let subscription = cx.observe(self, move |_, _| {
2412            tx.blocking_send(()).ok();
2413        });
2414
2415        let duration = if std::env::var("CI").is_ok() {
2416            Duration::from_secs(5)
2417        } else {
2418            Duration::from_secs(1)
2419        };
2420
2421        async move {
2422            let notification = timeout(duration, rx.recv())
2423                .await
2424                .expect("next notification timed out");
2425            drop(subscription);
2426            notification.expect("model dropped while test was waiting for its next notification")
2427        }
2428    }
2429
2430    pub fn next_event(&self, cx: &TestAppContext) -> impl Future<Output = T::Event>
2431    where
2432        T::Event: Clone,
2433    {
2434        let (mut tx, mut rx) = mpsc::channel(1);
2435        let mut cx = cx.cx.borrow_mut();
2436        let subscription = cx.subscribe(self, move |_, event, _| {
2437            tx.blocking_send(event.clone()).ok();
2438        });
2439
2440        let duration = if std::env::var("CI").is_ok() {
2441            Duration::from_secs(5)
2442        } else {
2443            Duration::from_secs(1)
2444        };
2445
2446        async move {
2447            let event = timeout(duration, rx.recv())
2448                .await
2449                .expect("next event timed out");
2450            drop(subscription);
2451            event.expect("model dropped while test was waiting for its next event")
2452        }
2453    }
2454
2455    pub fn condition(
2456        &self,
2457        cx: &TestAppContext,
2458        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2459    ) -> impl Future<Output = ()> {
2460        let (tx, mut rx) = mpsc::channel(1024);
2461
2462        let mut cx = cx.cx.borrow_mut();
2463        let subscriptions = (
2464            cx.observe(self, {
2465                let mut tx = tx.clone();
2466                move |_, _| {
2467                    tx.blocking_send(()).ok();
2468                }
2469            }),
2470            cx.subscribe(self, {
2471                let mut tx = tx.clone();
2472                move |_, _, _| {
2473                    tx.blocking_send(()).ok();
2474                }
2475            }),
2476        );
2477
2478        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2479        let handle = self.downgrade();
2480        let duration = if std::env::var("CI").is_ok() {
2481            Duration::from_secs(5)
2482        } else {
2483            Duration::from_secs(1)
2484        };
2485
2486        async move {
2487            timeout(duration, async move {
2488                loop {
2489                    {
2490                        let cx = cx.borrow();
2491                        let cx = cx.as_ref();
2492                        if predicate(
2493                            handle
2494                                .upgrade(cx)
2495                                .expect("model dropped with pending condition")
2496                                .read(cx),
2497                            cx,
2498                        ) {
2499                            break;
2500                        }
2501                    }
2502
2503                    rx.recv()
2504                        .await
2505                        .expect("model dropped with pending condition");
2506                }
2507            })
2508            .await
2509            .expect("condition timed out");
2510            drop(subscriptions);
2511        }
2512    }
2513}
2514
2515impl<T> Clone for ModelHandle<T> {
2516    fn clone(&self) -> Self {
2517        self.ref_counts.lock().inc_model(self.model_id);
2518        Self {
2519            model_id: self.model_id,
2520            model_type: PhantomData,
2521            ref_counts: self.ref_counts.clone(),
2522        }
2523    }
2524}
2525
2526impl<T> PartialEq for ModelHandle<T> {
2527    fn eq(&self, other: &Self) -> bool {
2528        self.model_id == other.model_id
2529    }
2530}
2531
2532impl<T> Eq for ModelHandle<T> {}
2533
2534impl<T> Hash for ModelHandle<T> {
2535    fn hash<H: Hasher>(&self, state: &mut H) {
2536        self.model_id.hash(state);
2537    }
2538}
2539
2540impl<T> std::borrow::Borrow<usize> for ModelHandle<T> {
2541    fn borrow(&self) -> &usize {
2542        &self.model_id
2543    }
2544}
2545
2546impl<T> Debug for ModelHandle<T> {
2547    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2548        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
2549            .field(&self.model_id)
2550            .finish()
2551    }
2552}
2553
2554unsafe impl<T> Send for ModelHandle<T> {}
2555unsafe impl<T> Sync for ModelHandle<T> {}
2556
2557impl<T> Drop for ModelHandle<T> {
2558    fn drop(&mut self) {
2559        self.ref_counts.lock().dec_model(self.model_id);
2560    }
2561}
2562
2563impl<T: Entity> Handle<T> for ModelHandle<T> {
2564    type Weak = WeakModelHandle<T>;
2565
2566    fn id(&self) -> usize {
2567        self.model_id
2568    }
2569
2570    fn location(&self) -> EntityLocation {
2571        EntityLocation::Model(self.model_id)
2572    }
2573
2574    fn downgrade(&self) -> Self::Weak {
2575        self.downgrade()
2576    }
2577
2578    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2579    where
2580        Self: Sized,
2581    {
2582        weak.upgrade(cx)
2583    }
2584}
2585
2586pub struct WeakModelHandle<T> {
2587    model_id: usize,
2588    model_type: PhantomData<T>,
2589}
2590
2591unsafe impl<T> Send for WeakModelHandle<T> {}
2592unsafe impl<T> Sync for WeakModelHandle<T> {}
2593
2594impl<T: Entity> WeakModelHandle<T> {
2595    fn new(model_id: usize) -> Self {
2596        Self {
2597            model_id,
2598            model_type: PhantomData,
2599        }
2600    }
2601
2602    pub fn upgrade(self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
2603        cx.upgrade_model_handle(self)
2604    }
2605}
2606
2607impl<T> Hash for WeakModelHandle<T> {
2608    fn hash<H: Hasher>(&self, state: &mut H) {
2609        self.model_id.hash(state)
2610    }
2611}
2612
2613impl<T> PartialEq for WeakModelHandle<T> {
2614    fn eq(&self, other: &Self) -> bool {
2615        self.model_id == other.model_id
2616    }
2617}
2618
2619impl<T> Eq for WeakModelHandle<T> {}
2620
2621impl<T> Clone for WeakModelHandle<T> {
2622    fn clone(&self) -> Self {
2623        Self {
2624            model_id: self.model_id,
2625            model_type: PhantomData,
2626        }
2627    }
2628}
2629
2630impl<T> Copy for WeakModelHandle<T> {}
2631
2632pub struct ViewHandle<T> {
2633    window_id: usize,
2634    view_id: usize,
2635    view_type: PhantomData<T>,
2636    ref_counts: Arc<Mutex<RefCounts>>,
2637}
2638
2639impl<T: View> ViewHandle<T> {
2640    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2641        ref_counts.lock().inc_view(window_id, view_id);
2642        Self {
2643            window_id,
2644            view_id,
2645            view_type: PhantomData,
2646            ref_counts: ref_counts.clone(),
2647        }
2648    }
2649
2650    pub fn downgrade(&self) -> WeakViewHandle<T> {
2651        WeakViewHandle::new(self.window_id, self.view_id)
2652    }
2653
2654    pub fn window_id(&self) -> usize {
2655        self.window_id
2656    }
2657
2658    pub fn id(&self) -> usize {
2659        self.view_id
2660    }
2661
2662    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
2663        cx.read_view(self)
2664    }
2665
2666    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
2667    where
2668        C: ReadViewWith,
2669        F: FnOnce(&T, &AppContext) -> S,
2670    {
2671        cx.read_view_with(self, read)
2672    }
2673
2674    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2675    where
2676        C: UpdateView,
2677        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2678    {
2679        cx.update_view(self, update)
2680    }
2681
2682    pub fn is_focused(&self, cx: &AppContext) -> bool {
2683        cx.focused_view_id(self.window_id)
2684            .map_or(false, |focused_id| focused_id == self.view_id)
2685    }
2686
2687    pub fn condition(
2688        &self,
2689        cx: &TestAppContext,
2690        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2691    ) -> impl Future<Output = ()> {
2692        let (tx, mut rx) = mpsc::channel(1024);
2693
2694        let mut cx = cx.cx.borrow_mut();
2695        let subscriptions = self.update(&mut *cx, |_, cx| {
2696            (
2697                cx.observe(self, {
2698                    let mut tx = tx.clone();
2699                    move |_, _, _| {
2700                        tx.blocking_send(()).ok();
2701                    }
2702                }),
2703                cx.subscribe(self, {
2704                    let mut tx = tx.clone();
2705                    move |_, _, _, _| {
2706                        tx.blocking_send(()).ok();
2707                    }
2708                }),
2709            )
2710        });
2711
2712        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2713        let handle = self.downgrade();
2714        let duration = if std::env::var("CI").is_ok() {
2715            Duration::from_secs(2)
2716        } else {
2717            Duration::from_millis(500)
2718        };
2719
2720        async move {
2721            timeout(duration, async move {
2722                loop {
2723                    {
2724                        let cx = cx.borrow();
2725                        let cx = cx.as_ref();
2726                        if predicate(
2727                            handle
2728                                .upgrade(cx)
2729                                .expect("view dropped with pending condition")
2730                                .read(cx),
2731                            cx,
2732                        ) {
2733                            break;
2734                        }
2735                    }
2736
2737                    rx.recv()
2738                        .await
2739                        .expect("view dropped with pending condition");
2740                }
2741            })
2742            .await
2743            .expect("condition timed out");
2744            drop(subscriptions);
2745        }
2746    }
2747}
2748
2749impl<T> Clone for ViewHandle<T> {
2750    fn clone(&self) -> Self {
2751        self.ref_counts
2752            .lock()
2753            .inc_view(self.window_id, self.view_id);
2754        Self {
2755            window_id: self.window_id,
2756            view_id: self.view_id,
2757            view_type: PhantomData,
2758            ref_counts: self.ref_counts.clone(),
2759        }
2760    }
2761}
2762
2763impl<T> PartialEq for ViewHandle<T> {
2764    fn eq(&self, other: &Self) -> bool {
2765        self.window_id == other.window_id && self.view_id == other.view_id
2766    }
2767}
2768
2769impl<T> Eq for ViewHandle<T> {}
2770
2771impl<T> Debug for ViewHandle<T> {
2772    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2773        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
2774            .field("window_id", &self.window_id)
2775            .field("view_id", &self.view_id)
2776            .finish()
2777    }
2778}
2779
2780impl<T> Drop for ViewHandle<T> {
2781    fn drop(&mut self) {
2782        self.ref_counts
2783            .lock()
2784            .dec_view(self.window_id, self.view_id);
2785    }
2786}
2787
2788impl<T: View> Handle<T> for ViewHandle<T> {
2789    type Weak = WeakViewHandle<T>;
2790
2791    fn id(&self) -> usize {
2792        self.view_id
2793    }
2794
2795    fn location(&self) -> EntityLocation {
2796        EntityLocation::View(self.window_id, self.view_id)
2797    }
2798
2799    fn downgrade(&self) -> Self::Weak {
2800        self.downgrade()
2801    }
2802
2803    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2804    where
2805        Self: Sized,
2806    {
2807        weak.upgrade(cx)
2808    }
2809}
2810
2811pub struct AnyViewHandle {
2812    window_id: usize,
2813    view_id: usize,
2814    view_type: TypeId,
2815    ref_counts: Arc<Mutex<RefCounts>>,
2816}
2817
2818impl AnyViewHandle {
2819    pub fn id(&self) -> usize {
2820        self.view_id
2821    }
2822
2823    pub fn is<T: 'static>(&self) -> bool {
2824        TypeId::of::<T>() == self.view_type
2825    }
2826
2827    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
2828        if self.is::<T>() {
2829            let result = Some(ViewHandle {
2830                window_id: self.window_id,
2831                view_id: self.view_id,
2832                ref_counts: self.ref_counts.clone(),
2833                view_type: PhantomData,
2834            });
2835            unsafe {
2836                Arc::decrement_strong_count(&self.ref_counts);
2837            }
2838            std::mem::forget(self);
2839            result
2840        } else {
2841            None
2842        }
2843    }
2844}
2845
2846impl Clone for AnyViewHandle {
2847    fn clone(&self) -> Self {
2848        self.ref_counts
2849            .lock()
2850            .inc_view(self.window_id, self.view_id);
2851        Self {
2852            window_id: self.window_id,
2853            view_id: self.view_id,
2854            view_type: self.view_type,
2855            ref_counts: self.ref_counts.clone(),
2856        }
2857    }
2858}
2859
2860impl From<&AnyViewHandle> for AnyViewHandle {
2861    fn from(handle: &AnyViewHandle) -> Self {
2862        handle.clone()
2863    }
2864}
2865
2866impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
2867    fn from(handle: &ViewHandle<T>) -> Self {
2868        handle
2869            .ref_counts
2870            .lock()
2871            .inc_view(handle.window_id, handle.view_id);
2872        AnyViewHandle {
2873            window_id: handle.window_id,
2874            view_id: handle.view_id,
2875            view_type: TypeId::of::<T>(),
2876            ref_counts: handle.ref_counts.clone(),
2877        }
2878    }
2879}
2880
2881impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
2882    fn from(handle: ViewHandle<T>) -> Self {
2883        let any_handle = AnyViewHandle {
2884            window_id: handle.window_id,
2885            view_id: handle.view_id,
2886            view_type: TypeId::of::<T>(),
2887            ref_counts: handle.ref_counts.clone(),
2888        };
2889        unsafe {
2890            Arc::decrement_strong_count(&handle.ref_counts);
2891        }
2892        std::mem::forget(handle);
2893        any_handle
2894    }
2895}
2896
2897impl Drop for AnyViewHandle {
2898    fn drop(&mut self) {
2899        self.ref_counts
2900            .lock()
2901            .dec_view(self.window_id, self.view_id);
2902    }
2903}
2904
2905pub struct AnyModelHandle {
2906    model_id: usize,
2907    ref_counts: Arc<Mutex<RefCounts>>,
2908}
2909
2910impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
2911    fn from(handle: ModelHandle<T>) -> Self {
2912        handle.ref_counts.lock().inc_model(handle.model_id);
2913        Self {
2914            model_id: handle.model_id,
2915            ref_counts: handle.ref_counts.clone(),
2916        }
2917    }
2918}
2919
2920impl Drop for AnyModelHandle {
2921    fn drop(&mut self) {
2922        self.ref_counts.lock().dec_model(self.model_id);
2923    }
2924}
2925pub struct WeakViewHandle<T> {
2926    window_id: usize,
2927    view_id: usize,
2928    view_type: PhantomData<T>,
2929}
2930
2931impl<T: View> WeakViewHandle<T> {
2932    fn new(window_id: usize, view_id: usize) -> Self {
2933        Self {
2934            window_id,
2935            view_id,
2936            view_type: PhantomData,
2937        }
2938    }
2939
2940    pub fn upgrade(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
2941        if cx.ref_counts.lock().is_entity_alive(self.view_id) {
2942            Some(ViewHandle::new(
2943                self.window_id,
2944                self.view_id,
2945                &cx.ref_counts,
2946            ))
2947        } else {
2948            None
2949        }
2950    }
2951}
2952
2953impl<T> Clone for WeakViewHandle<T> {
2954    fn clone(&self) -> Self {
2955        Self {
2956            window_id: self.window_id,
2957            view_id: self.view_id,
2958            view_type: PhantomData,
2959        }
2960    }
2961}
2962
2963pub struct ValueHandle<T> {
2964    value_type: PhantomData<T>,
2965    tag_type_id: TypeId,
2966    id: usize,
2967    ref_counts: Weak<Mutex<RefCounts>>,
2968}
2969
2970impl<T: 'static> ValueHandle<T> {
2971    fn new(tag_type_id: TypeId, id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2972        ref_counts.lock().inc_value(tag_type_id, id);
2973        Self {
2974            value_type: PhantomData,
2975            tag_type_id,
2976            id,
2977            ref_counts: Arc::downgrade(ref_counts),
2978        }
2979    }
2980
2981    pub fn read<R>(&self, cx: &AppContext, f: impl FnOnce(&T) -> R) -> R {
2982        f(cx.values
2983            .read()
2984            .get(&(self.tag_type_id, self.id))
2985            .unwrap()
2986            .downcast_ref()
2987            .unwrap())
2988    }
2989
2990    pub fn update<R>(
2991        &self,
2992        cx: &mut EventContext,
2993        f: impl FnOnce(&mut T, &mut EventContext) -> R,
2994    ) -> R {
2995        let mut value = cx
2996            .app
2997            .cx
2998            .values
2999            .write()
3000            .remove(&(self.tag_type_id, self.id))
3001            .unwrap();
3002        let result = f(value.downcast_mut().unwrap(), cx);
3003        cx.app
3004            .cx
3005            .values
3006            .write()
3007            .insert((self.tag_type_id, self.id), value);
3008        result
3009    }
3010}
3011
3012impl<T> Drop for ValueHandle<T> {
3013    fn drop(&mut self) {
3014        if let Some(ref_counts) = self.ref_counts.upgrade() {
3015            ref_counts.lock().dec_value(self.tag_type_id, self.id);
3016        }
3017    }
3018}
3019
3020#[must_use]
3021pub enum Subscription {
3022    Subscription {
3023        id: usize,
3024        entity_id: usize,
3025        subscriptions: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>>,
3026    },
3027    Observation {
3028        id: usize,
3029        entity_id: usize,
3030        observations: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ObservationCallback>>>>>,
3031    },
3032}
3033
3034impl Subscription {
3035    pub fn detach(&mut self) {
3036        match self {
3037            Subscription::Subscription { subscriptions, .. } => {
3038                subscriptions.take();
3039            }
3040            Subscription::Observation { observations, .. } => {
3041                observations.take();
3042            }
3043        }
3044    }
3045}
3046
3047impl Drop for Subscription {
3048    fn drop(&mut self) {
3049        match self {
3050            Subscription::Observation {
3051                id,
3052                entity_id,
3053                observations,
3054            } => {
3055                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3056                    if let Some(observations) = observations.lock().get_mut(entity_id) {
3057                        observations.remove(id);
3058                    }
3059                }
3060            }
3061            Subscription::Subscription {
3062                id,
3063                entity_id,
3064                subscriptions,
3065            } => {
3066                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
3067                    if let Some(subscriptions) = subscriptions.lock().get_mut(entity_id) {
3068                        subscriptions.remove(id);
3069                    }
3070                }
3071            }
3072        }
3073    }
3074}
3075
3076#[derive(Default)]
3077struct RefCounts {
3078    entity_counts: HashMap<usize, usize>,
3079    value_counts: HashMap<(TypeId, usize), usize>,
3080    dropped_models: HashSet<usize>,
3081    dropped_views: HashSet<(usize, usize)>,
3082    dropped_values: HashSet<(TypeId, usize)>,
3083}
3084
3085impl RefCounts {
3086    fn inc_model(&mut self, model_id: usize) {
3087        match self.entity_counts.entry(model_id) {
3088            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3089            Entry::Vacant(entry) => {
3090                entry.insert(1);
3091                self.dropped_models.remove(&model_id);
3092            }
3093        }
3094    }
3095
3096    fn inc_view(&mut self, window_id: usize, view_id: usize) {
3097        match self.entity_counts.entry(view_id) {
3098            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3099            Entry::Vacant(entry) => {
3100                entry.insert(1);
3101                self.dropped_views.remove(&(window_id, view_id));
3102            }
3103        }
3104    }
3105
3106    fn inc_value(&mut self, tag_type_id: TypeId, id: usize) {
3107        *self.value_counts.entry((tag_type_id, id)).or_insert(0) += 1;
3108    }
3109
3110    fn dec_model(&mut self, model_id: usize) {
3111        let count = self.entity_counts.get_mut(&model_id).unwrap();
3112        *count -= 1;
3113        if *count == 0 {
3114            self.entity_counts.remove(&model_id);
3115            self.dropped_models.insert(model_id);
3116        }
3117    }
3118
3119    fn dec_view(&mut self, window_id: usize, view_id: usize) {
3120        let count = self.entity_counts.get_mut(&view_id).unwrap();
3121        *count -= 1;
3122        if *count == 0 {
3123            self.entity_counts.remove(&view_id);
3124            self.dropped_views.insert((window_id, view_id));
3125        }
3126    }
3127
3128    fn dec_value(&mut self, tag_type_id: TypeId, id: usize) {
3129        let key = (tag_type_id, id);
3130        let count = self.value_counts.get_mut(&key).unwrap();
3131        *count -= 1;
3132        if *count == 0 {
3133            self.value_counts.remove(&key);
3134            self.dropped_values.insert(key);
3135        }
3136    }
3137
3138    fn is_entity_alive(&self, entity_id: usize) -> bool {
3139        self.entity_counts.contains_key(&entity_id)
3140    }
3141
3142    fn take_dropped(
3143        &mut self,
3144    ) -> (
3145        HashSet<usize>,
3146        HashSet<(usize, usize)>,
3147        HashSet<(TypeId, usize)>,
3148    ) {
3149        let mut dropped_models = HashSet::new();
3150        let mut dropped_views = HashSet::new();
3151        let mut dropped_values = HashSet::new();
3152        std::mem::swap(&mut self.dropped_models, &mut dropped_models);
3153        std::mem::swap(&mut self.dropped_views, &mut dropped_views);
3154        std::mem::swap(&mut self.dropped_values, &mut dropped_values);
3155        (dropped_models, dropped_views, dropped_values)
3156    }
3157}
3158
3159#[cfg(test)]
3160mod tests {
3161    use super::*;
3162    use crate::elements::*;
3163    use smol::future::poll_once;
3164    use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
3165
3166    #[crate::test(self)]
3167    fn test_model_handles(cx: &mut MutableAppContext) {
3168        struct Model {
3169            other: Option<ModelHandle<Model>>,
3170            events: Vec<String>,
3171        }
3172
3173        impl Entity for Model {
3174            type Event = usize;
3175        }
3176
3177        impl Model {
3178            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
3179                if let Some(other) = other.as_ref() {
3180                    cx.observe(other, |me, _, _| {
3181                        me.events.push("notified".into());
3182                    })
3183                    .detach();
3184                    cx.subscribe(other, |me, _, event, _| {
3185                        me.events.push(format!("observed event {}", event));
3186                    })
3187                    .detach();
3188                }
3189
3190                Self {
3191                    other,
3192                    events: Vec::new(),
3193                }
3194            }
3195        }
3196
3197        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
3198        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
3199        assert_eq!(cx.cx.models.len(), 2);
3200
3201        handle_1.update(cx, |model, cx| {
3202            model.events.push("updated".into());
3203            cx.emit(1);
3204            cx.notify();
3205            cx.emit(2);
3206        });
3207        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3208        assert_eq!(
3209            handle_2.read(cx).events,
3210            vec![
3211                "observed event 1".to_string(),
3212                "notified".to_string(),
3213                "observed event 2".to_string(),
3214            ]
3215        );
3216
3217        handle_2.update(cx, |model, _| {
3218            drop(handle_1);
3219            model.other.take();
3220        });
3221
3222        assert_eq!(cx.cx.models.len(), 1);
3223        assert!(cx.subscriptions.lock().is_empty());
3224        assert!(cx.observations.lock().is_empty());
3225    }
3226
3227    #[crate::test(self)]
3228    fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) {
3229        #[derive(Default)]
3230        struct Model {
3231            events: Vec<usize>,
3232        }
3233
3234        impl Entity for Model {
3235            type Event = usize;
3236        }
3237
3238        let handle_1 = cx.add_model(|_| Model::default());
3239        let handle_2 = cx.add_model(|_| Model::default());
3240        let handle_2b = handle_2.clone();
3241
3242        handle_1.update(cx, |_, c| {
3243            c.subscribe(&handle_2, move |model: &mut Model, _, event, c| {
3244                model.events.push(*event);
3245
3246                c.subscribe(&handle_2b, |model, _, event, _| {
3247                    model.events.push(*event * 2);
3248                })
3249                .detach();
3250            })
3251            .detach();
3252        });
3253
3254        handle_2.update(cx, |_, c| c.emit(7));
3255        assert_eq!(handle_1.read(cx).events, vec![7]);
3256
3257        handle_2.update(cx, |_, c| c.emit(5));
3258        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
3259    }
3260
3261    #[crate::test(self)]
3262    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
3263        #[derive(Default)]
3264        struct Model {
3265            count: usize,
3266            events: Vec<usize>,
3267        }
3268
3269        impl Entity for Model {
3270            type Event = ();
3271        }
3272
3273        let handle_1 = cx.add_model(|_| Model::default());
3274        let handle_2 = cx.add_model(|_| Model::default());
3275        let handle_2b = handle_2.clone();
3276
3277        handle_1.update(cx, |_, c| {
3278            c.observe(&handle_2, move |model, observed, c| {
3279                model.events.push(observed.read(c).count);
3280                c.observe(&handle_2b, |model, observed, c| {
3281                    model.events.push(observed.read(c).count * 2);
3282                })
3283                .detach();
3284            })
3285            .detach();
3286        });
3287
3288        handle_2.update(cx, |model, c| {
3289            model.count = 7;
3290            c.notify()
3291        });
3292        assert_eq!(handle_1.read(cx).events, vec![7]);
3293
3294        handle_2.update(cx, |model, c| {
3295            model.count = 5;
3296            c.notify()
3297        });
3298        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
3299    }
3300
3301    #[crate::test(self)]
3302    fn test_view_handles(cx: &mut MutableAppContext) {
3303        struct View {
3304            other: Option<ViewHandle<View>>,
3305            events: Vec<String>,
3306        }
3307
3308        impl Entity for View {
3309            type Event = usize;
3310        }
3311
3312        impl super::View for View {
3313            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3314                Empty::new().boxed()
3315            }
3316
3317            fn ui_name() -> &'static str {
3318                "View"
3319            }
3320        }
3321
3322        impl View {
3323            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
3324                if let Some(other) = other.as_ref() {
3325                    cx.subscribe(other, |me, _, event, _| {
3326                        me.events.push(format!("observed event {}", event));
3327                    })
3328                    .detach();
3329                }
3330                Self {
3331                    other,
3332                    events: Vec::new(),
3333                }
3334            }
3335        }
3336
3337        let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
3338        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
3339        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
3340        assert_eq!(cx.cx.views.len(), 3);
3341
3342        handle_1.update(cx, |view, cx| {
3343            view.events.push("updated".into());
3344            cx.emit(1);
3345            cx.emit(2);
3346        });
3347        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3348        assert_eq!(
3349            handle_2.read(cx).events,
3350            vec![
3351                "observed event 1".to_string(),
3352                "observed event 2".to_string(),
3353            ]
3354        );
3355
3356        handle_2.update(cx, |view, _| {
3357            drop(handle_1);
3358            view.other.take();
3359        });
3360
3361        assert_eq!(cx.cx.views.len(), 2);
3362        assert!(cx.subscriptions.lock().is_empty());
3363        assert!(cx.observations.lock().is_empty());
3364    }
3365
3366    #[crate::test(self)]
3367    fn test_add_window(cx: &mut MutableAppContext) {
3368        struct View {
3369            mouse_down_count: Arc<AtomicUsize>,
3370        }
3371
3372        impl Entity for View {
3373            type Event = ();
3374        }
3375
3376        impl super::View for View {
3377            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3378                let mouse_down_count = self.mouse_down_count.clone();
3379                EventHandler::new(Empty::new().boxed())
3380                    .on_mouse_down(move |_| {
3381                        mouse_down_count.fetch_add(1, SeqCst);
3382                        true
3383                    })
3384                    .boxed()
3385            }
3386
3387            fn ui_name() -> &'static str {
3388                "View"
3389            }
3390        }
3391
3392        let mouse_down_count = Arc::new(AtomicUsize::new(0));
3393        let (window_id, _) = cx.add_window(Default::default(), |_| View {
3394            mouse_down_count: mouse_down_count.clone(),
3395        });
3396        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
3397        // Ensure window's root element is in a valid lifecycle state.
3398        presenter.borrow_mut().dispatch_event(
3399            Event::LeftMouseDown {
3400                position: Default::default(),
3401                cmd: false,
3402            },
3403            cx,
3404        );
3405        assert_eq!(mouse_down_count.load(SeqCst), 1);
3406    }
3407
3408    #[crate::test(self)]
3409    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
3410        struct Model {
3411            released: Arc<Mutex<bool>>,
3412        }
3413
3414        struct View {
3415            released: Arc<Mutex<bool>>,
3416        }
3417
3418        impl Entity for Model {
3419            type Event = ();
3420
3421            fn release(&mut self, _: &mut MutableAppContext) {
3422                *self.released.lock() = true;
3423            }
3424        }
3425
3426        impl Entity for View {
3427            type Event = ();
3428
3429            fn release(&mut self, _: &mut MutableAppContext) {
3430                *self.released.lock() = true;
3431            }
3432        }
3433
3434        impl super::View for View {
3435            fn ui_name() -> &'static str {
3436                "View"
3437            }
3438
3439            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3440                Empty::new().boxed()
3441            }
3442        }
3443
3444        let model_released = Arc::new(Mutex::new(false));
3445        let view_released = Arc::new(Mutex::new(false));
3446
3447        let model = cx.add_model(|_| Model {
3448            released: model_released.clone(),
3449        });
3450
3451        let (window_id, _) = cx.add_window(Default::default(), |_| View {
3452            released: view_released.clone(),
3453        });
3454
3455        assert!(!*model_released.lock());
3456        assert!(!*view_released.lock());
3457
3458        cx.update(move || {
3459            drop(model);
3460        });
3461        assert!(*model_released.lock());
3462
3463        drop(cx.remove_window(window_id));
3464        assert!(*view_released.lock());
3465    }
3466
3467    #[crate::test(self)]
3468    fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) {
3469        #[derive(Default)]
3470        struct View {
3471            events: Vec<usize>,
3472        }
3473
3474        impl Entity for View {
3475            type Event = usize;
3476        }
3477
3478        impl super::View for View {
3479            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3480                Empty::new().boxed()
3481            }
3482
3483            fn ui_name() -> &'static str {
3484                "View"
3485            }
3486        }
3487
3488        struct Model;
3489
3490        impl Entity for Model {
3491            type Event = usize;
3492        }
3493
3494        let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
3495        let handle_2 = cx.add_view(window_id, |_| View::default());
3496        let handle_2b = handle_2.clone();
3497        let handle_3 = cx.add_model(|_| Model);
3498
3499        handle_1.update(cx, |_, c| {
3500            c.subscribe(&handle_2, move |me, _, event, c| {
3501                me.events.push(*event);
3502
3503                c.subscribe(&handle_2b, |me, _, event, _| {
3504                    me.events.push(*event * 2);
3505                })
3506                .detach();
3507            })
3508            .detach();
3509
3510            c.subscribe(&handle_3, |me, _, event, _| {
3511                me.events.push(*event);
3512            })
3513            .detach();
3514        });
3515
3516        handle_2.update(cx, |_, c| c.emit(7));
3517        assert_eq!(handle_1.read(cx).events, vec![7]);
3518
3519        handle_2.update(cx, |_, c| c.emit(5));
3520        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
3521
3522        handle_3.update(cx, |_, c| c.emit(9));
3523        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
3524    }
3525
3526    #[crate::test(self)]
3527    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
3528        struct View;
3529
3530        impl Entity for View {
3531            type Event = ();
3532        }
3533
3534        impl super::View for View {
3535            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3536                Empty::new().boxed()
3537            }
3538
3539            fn ui_name() -> &'static str {
3540                "View"
3541            }
3542        }
3543
3544        struct Model;
3545
3546        impl Entity for Model {
3547            type Event = ();
3548        }
3549
3550        let (window_id, _) = cx.add_window(Default::default(), |_| View);
3551        let observing_view = cx.add_view(window_id, |_| View);
3552        let emitting_view = cx.add_view(window_id, |_| View);
3553        let observing_model = cx.add_model(|_| Model);
3554        let observed_model = cx.add_model(|_| Model);
3555
3556        observing_view.update(cx, |_, cx| {
3557            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
3558            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
3559        });
3560        observing_model.update(cx, |_, cx| {
3561            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
3562        });
3563
3564        cx.update(|| {
3565            drop(observing_view);
3566            drop(observing_model);
3567        });
3568
3569        emitting_view.update(cx, |_, cx| cx.emit(()));
3570        observed_model.update(cx, |_, cx| cx.emit(()));
3571    }
3572
3573    #[crate::test(self)]
3574    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
3575        #[derive(Default)]
3576        struct View {
3577            events: Vec<usize>,
3578        }
3579
3580        impl Entity for View {
3581            type Event = usize;
3582        }
3583
3584        impl super::View for View {
3585            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3586                Empty::new().boxed()
3587            }
3588
3589            fn ui_name() -> &'static str {
3590                "View"
3591            }
3592        }
3593
3594        #[derive(Default)]
3595        struct Model {
3596            count: usize,
3597        }
3598
3599        impl Entity for Model {
3600            type Event = ();
3601        }
3602
3603        let (_, view) = cx.add_window(Default::default(), |_| View::default());
3604        let model = cx.add_model(|_| Model::default());
3605
3606        view.update(cx, |_, c| {
3607            c.observe(&model, |me, observed, c| {
3608                me.events.push(observed.read(c).count)
3609            })
3610            .detach();
3611        });
3612
3613        model.update(cx, |model, c| {
3614            model.count = 11;
3615            c.notify();
3616        });
3617        assert_eq!(view.read(cx).events, vec![11]);
3618    }
3619
3620    #[crate::test(self)]
3621    fn test_dropping_observers(cx: &mut MutableAppContext) {
3622        struct View;
3623
3624        impl Entity for View {
3625            type Event = ();
3626        }
3627
3628        impl super::View for View {
3629            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3630                Empty::new().boxed()
3631            }
3632
3633            fn ui_name() -> &'static str {
3634                "View"
3635            }
3636        }
3637
3638        struct Model;
3639
3640        impl Entity for Model {
3641            type Event = ();
3642        }
3643
3644        let (window_id, _) = cx.add_window(Default::default(), |_| View);
3645        let observing_view = cx.add_view(window_id, |_| View);
3646        let observing_model = cx.add_model(|_| Model);
3647        let observed_model = cx.add_model(|_| Model);
3648
3649        observing_view.update(cx, |_, cx| {
3650            cx.observe(&observed_model, |_, _, _| {}).detach();
3651        });
3652        observing_model.update(cx, |_, cx| {
3653            cx.observe(&observed_model, |_, _, _| {}).detach();
3654        });
3655
3656        cx.update(|| {
3657            drop(observing_view);
3658            drop(observing_model);
3659        });
3660
3661        observed_model.update(cx, |_, cx| cx.notify());
3662    }
3663
3664    #[crate::test(self)]
3665    fn test_focus(cx: &mut MutableAppContext) {
3666        struct View {
3667            name: String,
3668            events: Arc<Mutex<Vec<String>>>,
3669        }
3670
3671        impl Entity for View {
3672            type Event = ();
3673        }
3674
3675        impl super::View for View {
3676            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3677                Empty::new().boxed()
3678            }
3679
3680            fn ui_name() -> &'static str {
3681                "View"
3682            }
3683
3684            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
3685                self.events.lock().push(format!("{} focused", &self.name));
3686            }
3687
3688            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
3689                self.events.lock().push(format!("{} blurred", &self.name));
3690            }
3691        }
3692
3693        let events: Arc<Mutex<Vec<String>>> = Default::default();
3694        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
3695            events: events.clone(),
3696            name: "view 1".to_string(),
3697        });
3698        let view_2 = cx.add_view(window_id, |_| View {
3699            events: events.clone(),
3700            name: "view 2".to_string(),
3701        });
3702
3703        view_1.update(cx, |_, cx| cx.focus(&view_2));
3704        view_1.update(cx, |_, cx| cx.focus(&view_1));
3705        view_1.update(cx, |_, cx| cx.focus(&view_2));
3706        view_1.update(cx, |_, _| drop(view_2));
3707
3708        assert_eq!(
3709            *events.lock(),
3710            [
3711                "view 1 focused".to_string(),
3712                "view 1 blurred".to_string(),
3713                "view 2 focused".to_string(),
3714                "view 2 blurred".to_string(),
3715                "view 1 focused".to_string(),
3716                "view 1 blurred".to_string(),
3717                "view 2 focused".to_string(),
3718                "view 1 focused".to_string(),
3719            ],
3720        );
3721    }
3722
3723    #[crate::test(self)]
3724    fn test_dispatch_action(cx: &mut MutableAppContext) {
3725        struct ViewA {
3726            id: usize,
3727        }
3728
3729        impl Entity for ViewA {
3730            type Event = ();
3731        }
3732
3733        impl View for ViewA {
3734            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3735                Empty::new().boxed()
3736            }
3737
3738            fn ui_name() -> &'static str {
3739                "View"
3740            }
3741        }
3742
3743        struct ViewB {
3744            id: usize,
3745        }
3746
3747        impl Entity for ViewB {
3748            type Event = ();
3749        }
3750
3751        impl View for ViewB {
3752            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3753                Empty::new().boxed()
3754            }
3755
3756            fn ui_name() -> &'static str {
3757                "View"
3758            }
3759        }
3760
3761        action!(Action, &'static str);
3762
3763        let actions = Rc::new(RefCell::new(Vec::new()));
3764
3765        let actions_clone = actions.clone();
3766        cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
3767            actions_clone.borrow_mut().push("global a".to_string());
3768        });
3769
3770        let actions_clone = actions.clone();
3771        cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
3772            actions_clone.borrow_mut().push("global b".to_string());
3773        });
3774
3775        let actions_clone = actions.clone();
3776        cx.add_action(move |view: &mut ViewA, action: &Action, cx| {
3777            assert_eq!(action.0, "bar");
3778            cx.propagate_action();
3779            actions_clone.borrow_mut().push(format!("{} a", view.id));
3780        });
3781
3782        let actions_clone = actions.clone();
3783        cx.add_action(move |view: &mut ViewA, _: &Action, cx| {
3784            if view.id != 1 {
3785                cx.propagate_action();
3786            }
3787            actions_clone.borrow_mut().push(format!("{} b", view.id));
3788        });
3789
3790        let actions_clone = actions.clone();
3791        cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
3792            cx.propagate_action();
3793            actions_clone.borrow_mut().push(format!("{} c", view.id));
3794        });
3795
3796        let actions_clone = actions.clone();
3797        cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
3798            cx.propagate_action();
3799            actions_clone.borrow_mut().push(format!("{} d", view.id));
3800        });
3801
3802        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
3803        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
3804        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
3805        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
3806
3807        cx.dispatch_action(
3808            window_id,
3809            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
3810            &Action("bar"),
3811        );
3812
3813        assert_eq!(
3814            *actions.borrow(),
3815            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "1 b"]
3816        );
3817
3818        // Remove view_1, which doesn't propagate the action
3819        actions.borrow_mut().clear();
3820        cx.dispatch_action(
3821            window_id,
3822            vec![view_2.id(), view_3.id(), view_4.id()],
3823            &Action("bar"),
3824        );
3825
3826        assert_eq!(
3827            *actions.borrow(),
3828            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "global b", "global a"]
3829        );
3830    }
3831
3832    #[crate::test(self)]
3833    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
3834        use std::cell::Cell;
3835
3836        action!(Action, &'static str);
3837
3838        struct View {
3839            id: usize,
3840            keymap_context: keymap::Context,
3841        }
3842
3843        impl Entity for View {
3844            type Event = ();
3845        }
3846
3847        impl super::View for View {
3848            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3849                Empty::new().boxed()
3850            }
3851
3852            fn ui_name() -> &'static str {
3853                "View"
3854            }
3855
3856            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
3857                self.keymap_context.clone()
3858            }
3859        }
3860
3861        impl View {
3862            fn new(id: usize) -> Self {
3863                View {
3864                    id,
3865                    keymap_context: keymap::Context::default(),
3866                }
3867            }
3868        }
3869
3870        let mut view_1 = View::new(1);
3871        let mut view_2 = View::new(2);
3872        let mut view_3 = View::new(3);
3873        view_1.keymap_context.set.insert("a".into());
3874        view_2.keymap_context.set.insert("b".into());
3875        view_3.keymap_context.set.insert("c".into());
3876
3877        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
3878        let view_2 = cx.add_view(window_id, |_| view_2);
3879        let view_3 = cx.add_view(window_id, |_| view_3);
3880
3881        // This keymap's only binding dispatches an action on view 2 because that view will have
3882        // "a" and "b" in its context, but not "c".
3883        cx.add_bindings(vec![keymap::Binding::new(
3884            "a",
3885            Action("a"),
3886            Some("a && b && !c"),
3887        )]);
3888
3889        let handled_action = Rc::new(Cell::new(false));
3890        let handled_action_clone = handled_action.clone();
3891        cx.add_action(move |view: &mut View, action: &Action, _| {
3892            handled_action_clone.set(true);
3893            assert_eq!(view.id, 2);
3894            assert_eq!(action.0, "a");
3895        });
3896
3897        cx.dispatch_keystroke(
3898            window_id,
3899            vec![view_1.id(), view_2.id(), view_3.id()],
3900            &Keystroke::parse("a").unwrap(),
3901        )
3902        .unwrap();
3903
3904        assert!(handled_action.get());
3905    }
3906
3907    #[crate::test(self)]
3908    async fn test_model_condition(mut cx: TestAppContext) {
3909        struct Counter(usize);
3910
3911        impl super::Entity for Counter {
3912            type Event = ();
3913        }
3914
3915        impl Counter {
3916            fn inc(&mut self, cx: &mut ModelContext<Self>) {
3917                self.0 += 1;
3918                cx.notify();
3919            }
3920        }
3921
3922        let model = cx.add_model(|_| Counter(0));
3923
3924        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
3925        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
3926        smol::pin!(condition1, condition2);
3927
3928        model.update(&mut cx, |model, cx| model.inc(cx));
3929        assert_eq!(poll_once(&mut condition1).await, None);
3930        assert_eq!(poll_once(&mut condition2).await, None);
3931
3932        model.update(&mut cx, |model, cx| model.inc(cx));
3933        assert_eq!(poll_once(&mut condition1).await, Some(()));
3934        assert_eq!(poll_once(&mut condition2).await, None);
3935
3936        model.update(&mut cx, |model, cx| model.inc(cx));
3937        assert_eq!(poll_once(&mut condition2).await, Some(()));
3938
3939        model.update(&mut cx, |_, cx| cx.notify());
3940    }
3941
3942    #[crate::test(self)]
3943    #[should_panic]
3944    async fn test_model_condition_timeout(mut cx: TestAppContext) {
3945        struct Model;
3946
3947        impl super::Entity for Model {
3948            type Event = ();
3949        }
3950
3951        let model = cx.add_model(|_| Model);
3952        model.condition(&cx, |_, _| false).await;
3953    }
3954
3955    #[crate::test(self)]
3956    #[should_panic(expected = "model dropped with pending condition")]
3957    async fn test_model_condition_panic_on_drop(mut cx: TestAppContext) {
3958        struct Model;
3959
3960        impl super::Entity for Model {
3961            type Event = ();
3962        }
3963
3964        let model = cx.add_model(|_| Model);
3965        let condition = model.condition(&cx, |_, _| false);
3966        cx.update(|_| drop(model));
3967        condition.await;
3968    }
3969
3970    #[crate::test(self)]
3971    async fn test_view_condition(mut cx: TestAppContext) {
3972        struct Counter(usize);
3973
3974        impl super::Entity for Counter {
3975            type Event = ();
3976        }
3977
3978        impl super::View for Counter {
3979            fn ui_name() -> &'static str {
3980                "test view"
3981            }
3982
3983            fn render(&self, _: &RenderContext<Self>) -> ElementBox {
3984                Empty::new().boxed()
3985            }
3986        }
3987
3988        impl Counter {
3989            fn inc(&mut self, cx: &mut ViewContext<Self>) {
3990                self.0 += 1;
3991                cx.notify();
3992            }
3993        }
3994
3995        let (_, view) = cx.add_window(|_| Counter(0));
3996
3997        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
3998        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
3999        smol::pin!(condition1, condition2);
4000
4001        view.update(&mut cx, |view, cx| view.inc(cx));
4002        assert_eq!(poll_once(&mut condition1).await, None);
4003        assert_eq!(poll_once(&mut condition2).await, None);
4004
4005        view.update(&mut cx, |view, cx| view.inc(cx));
4006        assert_eq!(poll_once(&mut condition1).await, Some(()));
4007        assert_eq!(poll_once(&mut condition2).await, None);
4008
4009        view.update(&mut cx, |view, cx| view.inc(cx));
4010        assert_eq!(poll_once(&mut condition2).await, Some(()));
4011        view.update(&mut cx, |_, cx| cx.notify());
4012    }
4013
4014    #[crate::test(self)]
4015    #[should_panic]
4016    async fn test_view_condition_timeout(mut cx: TestAppContext) {
4017        struct View;
4018
4019        impl super::Entity for View {
4020            type Event = ();
4021        }
4022
4023        impl super::View for View {
4024            fn ui_name() -> &'static str {
4025                "test view"
4026            }
4027
4028            fn render(&self, _: &RenderContext<Self>) -> ElementBox {
4029                Empty::new().boxed()
4030            }
4031        }
4032
4033        let (_, view) = cx.add_window(|_| View);
4034        view.condition(&cx, |_, _| false).await;
4035    }
4036
4037    #[crate::test(self)]
4038    #[should_panic(expected = "view dropped with pending condition")]
4039    async fn test_view_condition_panic_on_drop(mut cx: TestAppContext) {
4040        struct View;
4041
4042        impl super::Entity for View {
4043            type Event = ();
4044        }
4045
4046        impl super::View for View {
4047            fn ui_name() -> &'static str {
4048                "test view"
4049            }
4050
4051            fn render(&self, _: &RenderContext<Self>) -> ElementBox {
4052                Empty::new().boxed()
4053            }
4054        }
4055
4056        let window_id = cx.add_window(|_| View).0;
4057        let view = cx.add_view(window_id, |_| View);
4058
4059        let condition = view.condition(&cx, |_, _| false);
4060        cx.update(|_| drop(view));
4061        condition.await;
4062    }
4063}