app.rs

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