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