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