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 + Send + Sync {
  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: Send + Sync {
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: Send + Sync {
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
2518impl<T: Entity> WeakModelHandle<T> {
2519    fn new(model_id: usize) -> Self {
2520        Self {
2521            model_id,
2522            model_type: PhantomData,
2523        }
2524    }
2525
2526    pub fn upgrade(self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
2527        cx.upgrade_model_handle(self)
2528    }
2529}
2530
2531impl<T> Hash for WeakModelHandle<T> {
2532    fn hash<H: Hasher>(&self, state: &mut H) {
2533        self.model_id.hash(state)
2534    }
2535}
2536
2537impl<T> PartialEq for WeakModelHandle<T> {
2538    fn eq(&self, other: &Self) -> bool {
2539        self.model_id == other.model_id
2540    }
2541}
2542
2543impl<T> Eq for WeakModelHandle<T> {}
2544
2545impl<T> Clone for WeakModelHandle<T> {
2546    fn clone(&self) -> Self {
2547        Self {
2548            model_id: self.model_id,
2549            model_type: PhantomData,
2550        }
2551    }
2552}
2553
2554impl<T> Copy for WeakModelHandle<T> {}
2555
2556pub struct ViewHandle<T> {
2557    window_id: usize,
2558    view_id: usize,
2559    view_type: PhantomData<T>,
2560    ref_counts: Arc<Mutex<RefCounts>>,
2561}
2562
2563impl<T: View> ViewHandle<T> {
2564    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2565        ref_counts.lock().inc_view(window_id, view_id);
2566        Self {
2567            window_id,
2568            view_id,
2569            view_type: PhantomData,
2570            ref_counts: ref_counts.clone(),
2571        }
2572    }
2573
2574    pub fn downgrade(&self) -> WeakViewHandle<T> {
2575        WeakViewHandle::new(self.window_id, self.view_id)
2576    }
2577
2578    pub fn window_id(&self) -> usize {
2579        self.window_id
2580    }
2581
2582    pub fn id(&self) -> usize {
2583        self.view_id
2584    }
2585
2586    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
2587        cx.read_view(self)
2588    }
2589
2590    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
2591    where
2592        C: ReadViewWith,
2593        F: FnOnce(&T, &AppContext) -> S,
2594    {
2595        cx.read_view_with(self, read)
2596    }
2597
2598    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2599    where
2600        C: UpdateView,
2601        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2602    {
2603        cx.update_view(self, update)
2604    }
2605
2606    pub fn is_focused(&self, cx: &AppContext) -> bool {
2607        cx.focused_view_id(self.window_id)
2608            .map_or(false, |focused_id| focused_id == self.view_id)
2609    }
2610
2611    pub fn condition(
2612        &self,
2613        cx: &TestAppContext,
2614        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2615    ) -> impl Future<Output = ()> {
2616        let (tx, mut rx) = mpsc::channel(1024);
2617
2618        let mut cx = cx.cx.borrow_mut();
2619        self.update(&mut *cx, |_, cx| {
2620            cx.observe_view(self, {
2621                let mut tx = tx.clone();
2622                move |_, _, _| {
2623                    tx.blocking_send(()).ok();
2624                }
2625            });
2626
2627            cx.subscribe(self, {
2628                let mut tx = tx.clone();
2629                move |_, _, _| {
2630                    tx.blocking_send(()).ok();
2631                }
2632            })
2633        });
2634
2635        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2636        let handle = self.downgrade();
2637        let duration = if std::env::var("CI").is_ok() {
2638            Duration::from_secs(2)
2639        } else {
2640            Duration::from_millis(500)
2641        };
2642
2643        async move {
2644            timeout(duration, async move {
2645                loop {
2646                    {
2647                        let cx = cx.borrow();
2648                        let cx = cx.as_ref();
2649                        if predicate(
2650                            handle
2651                                .upgrade(cx)
2652                                .expect("view dropped with pending condition")
2653                                .read(cx),
2654                            cx,
2655                        ) {
2656                            break;
2657                        }
2658                    }
2659
2660                    rx.recv()
2661                        .await
2662                        .expect("view dropped with pending condition");
2663                }
2664            })
2665            .await
2666            .expect("condition timed out");
2667        }
2668    }
2669}
2670
2671impl<T> Clone for ViewHandle<T> {
2672    fn clone(&self) -> Self {
2673        self.ref_counts
2674            .lock()
2675            .inc_view(self.window_id, self.view_id);
2676        Self {
2677            window_id: self.window_id,
2678            view_id: self.view_id,
2679            view_type: PhantomData,
2680            ref_counts: self.ref_counts.clone(),
2681        }
2682    }
2683}
2684
2685impl<T> PartialEq for ViewHandle<T> {
2686    fn eq(&self, other: &Self) -> bool {
2687        self.window_id == other.window_id && self.view_id == other.view_id
2688    }
2689}
2690
2691impl<T> Eq for ViewHandle<T> {}
2692
2693impl<T> Debug for ViewHandle<T> {
2694    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2695        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
2696            .field("window_id", &self.window_id)
2697            .field("view_id", &self.view_id)
2698            .finish()
2699    }
2700}
2701
2702impl<T> Drop for ViewHandle<T> {
2703    fn drop(&mut self) {
2704        self.ref_counts
2705            .lock()
2706            .dec_view(self.window_id, self.view_id);
2707    }
2708}
2709
2710impl<T> Handle<T> for ViewHandle<T> {
2711    fn id(&self) -> usize {
2712        self.view_id
2713    }
2714
2715    fn location(&self) -> EntityLocation {
2716        EntityLocation::View(self.window_id, self.view_id)
2717    }
2718}
2719
2720pub struct AnyViewHandle {
2721    window_id: usize,
2722    view_id: usize,
2723    view_type: TypeId,
2724    ref_counts: Arc<Mutex<RefCounts>>,
2725}
2726
2727impl AnyViewHandle {
2728    pub fn id(&self) -> usize {
2729        self.view_id
2730    }
2731
2732    pub fn is<T: 'static>(&self) -> bool {
2733        TypeId::of::<T>() == self.view_type
2734    }
2735
2736    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
2737        if self.is::<T>() {
2738            let result = Some(ViewHandle {
2739                window_id: self.window_id,
2740                view_id: self.view_id,
2741                ref_counts: self.ref_counts.clone(),
2742                view_type: PhantomData,
2743            });
2744            unsafe {
2745                Arc::decrement_strong_count(&self.ref_counts);
2746            }
2747            std::mem::forget(self);
2748            result
2749        } else {
2750            None
2751        }
2752    }
2753}
2754
2755impl Clone for AnyViewHandle {
2756    fn clone(&self) -> Self {
2757        self.ref_counts
2758            .lock()
2759            .inc_view(self.window_id, self.view_id);
2760        Self {
2761            window_id: self.window_id,
2762            view_id: self.view_id,
2763            view_type: self.view_type,
2764            ref_counts: self.ref_counts.clone(),
2765        }
2766    }
2767}
2768
2769impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
2770    fn from(handle: &ViewHandle<T>) -> Self {
2771        handle
2772            .ref_counts
2773            .lock()
2774            .inc_view(handle.window_id, handle.view_id);
2775        AnyViewHandle {
2776            window_id: handle.window_id,
2777            view_id: handle.view_id,
2778            view_type: TypeId::of::<T>(),
2779            ref_counts: handle.ref_counts.clone(),
2780        }
2781    }
2782}
2783
2784impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
2785    fn from(handle: ViewHandle<T>) -> Self {
2786        let any_handle = AnyViewHandle {
2787            window_id: handle.window_id,
2788            view_id: handle.view_id,
2789            view_type: TypeId::of::<T>(),
2790            ref_counts: handle.ref_counts.clone(),
2791        };
2792        unsafe {
2793            Arc::decrement_strong_count(&handle.ref_counts);
2794        }
2795        std::mem::forget(handle);
2796        any_handle
2797    }
2798}
2799
2800impl Drop for AnyViewHandle {
2801    fn drop(&mut self) {
2802        self.ref_counts
2803            .lock()
2804            .dec_view(self.window_id, self.view_id);
2805    }
2806}
2807
2808pub struct AnyModelHandle {
2809    model_id: usize,
2810    ref_counts: Arc<Mutex<RefCounts>>,
2811}
2812
2813impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
2814    fn from(handle: ModelHandle<T>) -> Self {
2815        handle.ref_counts.lock().inc_model(handle.model_id);
2816        Self {
2817            model_id: handle.model_id,
2818            ref_counts: handle.ref_counts.clone(),
2819        }
2820    }
2821}
2822
2823impl Drop for AnyModelHandle {
2824    fn drop(&mut self) {
2825        self.ref_counts.lock().dec_model(self.model_id);
2826    }
2827}
2828pub struct WeakViewHandle<T> {
2829    window_id: usize,
2830    view_id: usize,
2831    view_type: PhantomData<T>,
2832}
2833
2834impl<T: View> WeakViewHandle<T> {
2835    fn new(window_id: usize, view_id: usize) -> Self {
2836        Self {
2837            window_id,
2838            view_id,
2839            view_type: PhantomData,
2840        }
2841    }
2842
2843    pub fn upgrade(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
2844        if cx.ref_counts.lock().is_entity_alive(self.view_id) {
2845            Some(ViewHandle::new(
2846                self.window_id,
2847                self.view_id,
2848                &cx.ref_counts,
2849            ))
2850        } else {
2851            None
2852        }
2853    }
2854}
2855
2856impl<T> Clone for WeakViewHandle<T> {
2857    fn clone(&self) -> Self {
2858        Self {
2859            window_id: self.window_id,
2860            view_id: self.view_id,
2861            view_type: PhantomData,
2862        }
2863    }
2864}
2865
2866pub struct ValueHandle<T> {
2867    value_type: PhantomData<T>,
2868    tag_type_id: TypeId,
2869    id: usize,
2870    ref_counts: Weak<Mutex<RefCounts>>,
2871}
2872
2873impl<T: 'static> ValueHandle<T> {
2874    fn new(tag_type_id: TypeId, id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2875        ref_counts.lock().inc_value(tag_type_id, id);
2876        Self {
2877            value_type: PhantomData,
2878            tag_type_id,
2879            id,
2880            ref_counts: Arc::downgrade(ref_counts),
2881        }
2882    }
2883
2884    pub fn read<R>(&self, cx: &AppContext, f: impl FnOnce(&T) -> R) -> R {
2885        f(cx.values
2886            .read()
2887            .get(&(self.tag_type_id, self.id))
2888            .unwrap()
2889            .downcast_ref()
2890            .unwrap())
2891    }
2892
2893    pub fn update<R>(
2894        &self,
2895        cx: &mut EventContext,
2896        f: impl FnOnce(&mut T, &mut EventContext) -> R,
2897    ) -> R {
2898        let mut value = cx
2899            .app
2900            .cx
2901            .values
2902            .write()
2903            .remove(&(self.tag_type_id, self.id))
2904            .unwrap();
2905        let result = f(value.downcast_mut().unwrap(), cx);
2906        cx.app
2907            .cx
2908            .values
2909            .write()
2910            .insert((self.tag_type_id, self.id), value);
2911        result
2912    }
2913}
2914
2915impl<T> Drop for ValueHandle<T> {
2916    fn drop(&mut self) {
2917        if let Some(ref_counts) = self.ref_counts.upgrade() {
2918            ref_counts.lock().dec_value(self.tag_type_id, self.id);
2919        }
2920    }
2921}
2922
2923#[derive(Default)]
2924struct RefCounts {
2925    entity_counts: HashMap<usize, usize>,
2926    value_counts: HashMap<(TypeId, usize), usize>,
2927    dropped_models: HashSet<usize>,
2928    dropped_views: HashSet<(usize, usize)>,
2929    dropped_values: HashSet<(TypeId, usize)>,
2930}
2931
2932impl RefCounts {
2933    fn inc_model(&mut self, model_id: usize) {
2934        match self.entity_counts.entry(model_id) {
2935            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
2936            Entry::Vacant(entry) => {
2937                entry.insert(1);
2938                self.dropped_models.remove(&model_id);
2939            }
2940        }
2941    }
2942
2943    fn inc_view(&mut self, window_id: usize, view_id: usize) {
2944        match self.entity_counts.entry(view_id) {
2945            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
2946            Entry::Vacant(entry) => {
2947                entry.insert(1);
2948                self.dropped_views.remove(&(window_id, view_id));
2949            }
2950        }
2951    }
2952
2953    fn inc_value(&mut self, tag_type_id: TypeId, id: usize) {
2954        *self.value_counts.entry((tag_type_id, id)).or_insert(0) += 1;
2955    }
2956
2957    fn dec_model(&mut self, model_id: usize) {
2958        let count = self.entity_counts.get_mut(&model_id).unwrap();
2959        *count -= 1;
2960        if *count == 0 {
2961            self.entity_counts.remove(&model_id);
2962            self.dropped_models.insert(model_id);
2963        }
2964    }
2965
2966    fn dec_view(&mut self, window_id: usize, view_id: usize) {
2967        let count = self.entity_counts.get_mut(&view_id).unwrap();
2968        *count -= 1;
2969        if *count == 0 {
2970            self.entity_counts.remove(&view_id);
2971            self.dropped_views.insert((window_id, view_id));
2972        }
2973    }
2974
2975    fn dec_value(&mut self, tag_type_id: TypeId, id: usize) {
2976        let key = (tag_type_id, id);
2977        let count = self.value_counts.get_mut(&key).unwrap();
2978        *count -= 1;
2979        if *count == 0 {
2980            self.value_counts.remove(&key);
2981            self.dropped_values.insert(key);
2982        }
2983    }
2984
2985    fn is_entity_alive(&self, entity_id: usize) -> bool {
2986        self.entity_counts.contains_key(&entity_id)
2987    }
2988
2989    fn take_dropped(
2990        &mut self,
2991    ) -> (
2992        HashSet<usize>,
2993        HashSet<(usize, usize)>,
2994        HashSet<(TypeId, usize)>,
2995    ) {
2996        let mut dropped_models = HashSet::new();
2997        let mut dropped_views = HashSet::new();
2998        let mut dropped_values = HashSet::new();
2999        std::mem::swap(&mut self.dropped_models, &mut dropped_models);
3000        std::mem::swap(&mut self.dropped_views, &mut dropped_views);
3001        std::mem::swap(&mut self.dropped_values, &mut dropped_values);
3002        (dropped_models, dropped_views, dropped_values)
3003    }
3004}
3005
3006enum Subscription {
3007    FromModel {
3008        model_id: usize,
3009        callback: Box<dyn FnMut(&mut dyn Any, &dyn Any, &mut MutableAppContext, usize)>,
3010    },
3011    FromView {
3012        window_id: usize,
3013        view_id: usize,
3014        callback: Box<dyn FnMut(&mut dyn Any, &dyn Any, &mut MutableAppContext, usize, usize)>,
3015    },
3016}
3017
3018enum ModelObservation {
3019    FromModel {
3020        model_id: usize,
3021        callback: Box<dyn FnMut(&mut dyn Any, usize, &mut MutableAppContext, usize)>,
3022    },
3023    FromView {
3024        window_id: usize,
3025        view_id: usize,
3026        callback: Box<dyn FnMut(&mut dyn Any, usize, &mut MutableAppContext, usize, usize)>,
3027    },
3028}
3029
3030struct ViewObservation {
3031    window_id: usize,
3032    view_id: usize,
3033    callback: Box<dyn FnMut(&mut dyn Any, usize, usize, &mut MutableAppContext, usize, usize)>,
3034}
3035
3036#[cfg(test)]
3037mod tests {
3038    use super::*;
3039    use crate::elements::*;
3040    use smol::future::poll_once;
3041    use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
3042
3043    #[crate::test(self)]
3044    fn test_model_handles(cx: &mut MutableAppContext) {
3045        struct Model {
3046            other: Option<ModelHandle<Model>>,
3047            events: Vec<String>,
3048        }
3049
3050        impl Entity for Model {
3051            type Event = usize;
3052        }
3053
3054        impl Model {
3055            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
3056                if let Some(other) = other.as_ref() {
3057                    cx.observe(other, |me, _, _| {
3058                        me.events.push("notified".into());
3059                    });
3060                    cx.subscribe(other, |me, event, _| {
3061                        me.events.push(format!("observed event {}", event));
3062                    });
3063                }
3064
3065                Self {
3066                    other,
3067                    events: Vec::new(),
3068                }
3069            }
3070        }
3071
3072        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
3073        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
3074        assert_eq!(cx.cx.models.len(), 2);
3075
3076        handle_1.update(cx, |model, cx| {
3077            model.events.push("updated".into());
3078            cx.emit(1);
3079            cx.notify();
3080            cx.emit(2);
3081        });
3082        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3083        assert_eq!(
3084            handle_2.read(cx).events,
3085            vec![
3086                "observed event 1".to_string(),
3087                "notified".to_string(),
3088                "observed event 2".to_string(),
3089            ]
3090        );
3091
3092        handle_2.update(cx, |model, _| {
3093            drop(handle_1);
3094            model.other.take();
3095        });
3096
3097        assert_eq!(cx.cx.models.len(), 1);
3098        assert!(cx.subscriptions.is_empty());
3099        assert!(cx.model_observations.is_empty());
3100    }
3101
3102    #[crate::test(self)]
3103    fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) {
3104        #[derive(Default)]
3105        struct Model {
3106            events: Vec<usize>,
3107        }
3108
3109        impl Entity for Model {
3110            type Event = usize;
3111        }
3112
3113        let handle_1 = cx.add_model(|_| Model::default());
3114        let handle_2 = cx.add_model(|_| Model::default());
3115        let handle_2b = handle_2.clone();
3116
3117        handle_1.update(cx, |_, c| {
3118            c.subscribe(&handle_2, move |model: &mut Model, event, c| {
3119                model.events.push(*event);
3120
3121                c.subscribe(&handle_2b, |model, event, _| {
3122                    model.events.push(*event * 2);
3123                });
3124            });
3125        });
3126
3127        handle_2.update(cx, |_, c| c.emit(7));
3128        assert_eq!(handle_1.read(cx).events, vec![7]);
3129
3130        handle_2.update(cx, |_, c| c.emit(5));
3131        assert_eq!(handle_1.read(cx).events, vec![7, 10, 5]);
3132    }
3133
3134    #[crate::test(self)]
3135    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
3136        #[derive(Default)]
3137        struct Model {
3138            count: usize,
3139            events: Vec<usize>,
3140        }
3141
3142        impl Entity for Model {
3143            type Event = ();
3144        }
3145
3146        let handle_1 = cx.add_model(|_| Model::default());
3147        let handle_2 = cx.add_model(|_| Model::default());
3148        let handle_2b = handle_2.clone();
3149
3150        handle_1.update(cx, |_, c| {
3151            c.observe(&handle_2, move |model, observed, c| {
3152                model.events.push(observed.read(c).count);
3153                c.observe(&handle_2b, |model, observed, c| {
3154                    model.events.push(observed.read(c).count * 2);
3155                });
3156            });
3157        });
3158
3159        handle_2.update(cx, |model, c| {
3160            model.count = 7;
3161            c.notify()
3162        });
3163        assert_eq!(handle_1.read(cx).events, vec![7]);
3164
3165        handle_2.update(cx, |model, c| {
3166            model.count = 5;
3167            c.notify()
3168        });
3169        assert_eq!(handle_1.read(cx).events, vec![7, 10, 5])
3170    }
3171
3172    #[crate::test(self)]
3173    fn test_view_handles(cx: &mut MutableAppContext) {
3174        struct View {
3175            other: Option<ViewHandle<View>>,
3176            events: Vec<String>,
3177        }
3178
3179        impl Entity for View {
3180            type Event = usize;
3181        }
3182
3183        impl super::View for View {
3184            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3185                Empty::new().boxed()
3186            }
3187
3188            fn ui_name() -> &'static str {
3189                "View"
3190            }
3191        }
3192
3193        impl View {
3194            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
3195                if let Some(other) = other.as_ref() {
3196                    cx.subscribe_to_view(other, |me, _, event, _| {
3197                        me.events.push(format!("observed event {}", event));
3198                    });
3199                }
3200                Self {
3201                    other,
3202                    events: Vec::new(),
3203                }
3204            }
3205        }
3206
3207        let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
3208        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
3209        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
3210        assert_eq!(cx.cx.views.len(), 3);
3211
3212        handle_1.update(cx, |view, cx| {
3213            view.events.push("updated".into());
3214            cx.emit(1);
3215            cx.emit(2);
3216        });
3217        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3218        assert_eq!(
3219            handle_2.read(cx).events,
3220            vec![
3221                "observed event 1".to_string(),
3222                "observed event 2".to_string(),
3223            ]
3224        );
3225
3226        handle_2.update(cx, |view, _| {
3227            drop(handle_1);
3228            view.other.take();
3229        });
3230
3231        assert_eq!(cx.cx.views.len(), 2);
3232        assert!(cx.subscriptions.is_empty());
3233        assert!(cx.model_observations.is_empty());
3234    }
3235
3236    #[crate::test(self)]
3237    fn test_add_window(cx: &mut MutableAppContext) {
3238        struct View {
3239            mouse_down_count: Arc<AtomicUsize>,
3240        }
3241
3242        impl Entity for View {
3243            type Event = ();
3244        }
3245
3246        impl super::View for View {
3247            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3248                let mouse_down_count = self.mouse_down_count.clone();
3249                EventHandler::new(Empty::new().boxed())
3250                    .on_mouse_down(move |_| {
3251                        mouse_down_count.fetch_add(1, SeqCst);
3252                        true
3253                    })
3254                    .boxed()
3255            }
3256
3257            fn ui_name() -> &'static str {
3258                "View"
3259            }
3260        }
3261
3262        let mouse_down_count = Arc::new(AtomicUsize::new(0));
3263        let (window_id, _) = cx.add_window(Default::default(), |_| View {
3264            mouse_down_count: mouse_down_count.clone(),
3265        });
3266        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
3267        // Ensure window's root element is in a valid lifecycle state.
3268        presenter.borrow_mut().dispatch_event(
3269            Event::LeftMouseDown {
3270                position: Default::default(),
3271                cmd: false,
3272            },
3273            cx,
3274        );
3275        assert_eq!(mouse_down_count.load(SeqCst), 1);
3276    }
3277
3278    #[crate::test(self)]
3279    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
3280        struct Model {
3281            released: Arc<Mutex<bool>>,
3282        }
3283
3284        struct View {
3285            released: Arc<Mutex<bool>>,
3286        }
3287
3288        impl Entity for Model {
3289            type Event = ();
3290
3291            fn release(&mut self, _: &mut MutableAppContext) {
3292                *self.released.lock() = true;
3293            }
3294        }
3295
3296        impl Entity for View {
3297            type Event = ();
3298
3299            fn release(&mut self, _: &mut MutableAppContext) {
3300                *self.released.lock() = true;
3301            }
3302        }
3303
3304        impl super::View for View {
3305            fn ui_name() -> &'static str {
3306                "View"
3307            }
3308
3309            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3310                Empty::new().boxed()
3311            }
3312        }
3313
3314        let model_released = Arc::new(Mutex::new(false));
3315        let view_released = Arc::new(Mutex::new(false));
3316
3317        let model = cx.add_model(|_| Model {
3318            released: model_released.clone(),
3319        });
3320
3321        let (window_id, _) = cx.add_window(Default::default(), |_| View {
3322            released: view_released.clone(),
3323        });
3324
3325        assert!(!*model_released.lock());
3326        assert!(!*view_released.lock());
3327
3328        cx.update(move || {
3329            drop(model);
3330        });
3331        assert!(*model_released.lock());
3332
3333        drop(cx.remove_window(window_id));
3334        assert!(*view_released.lock());
3335    }
3336
3337    #[crate::test(self)]
3338    fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) {
3339        #[derive(Default)]
3340        struct View {
3341            events: Vec<usize>,
3342        }
3343
3344        impl Entity for View {
3345            type Event = usize;
3346        }
3347
3348        impl super::View for View {
3349            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3350                Empty::new().boxed()
3351            }
3352
3353            fn ui_name() -> &'static str {
3354                "View"
3355            }
3356        }
3357
3358        struct Model;
3359
3360        impl Entity for Model {
3361            type Event = usize;
3362        }
3363
3364        let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
3365        let handle_2 = cx.add_view(window_id, |_| View::default());
3366        let handle_2b = handle_2.clone();
3367        let handle_3 = cx.add_model(|_| Model);
3368
3369        handle_1.update(cx, |_, c| {
3370            c.subscribe_to_view(&handle_2, move |me, _, event, c| {
3371                me.events.push(*event);
3372
3373                c.subscribe_to_view(&handle_2b, |me, _, event, _| {
3374                    me.events.push(*event * 2);
3375                });
3376            });
3377
3378            c.subscribe_to_model(&handle_3, |me, _, event, _| {
3379                me.events.push(*event);
3380            })
3381        });
3382
3383        handle_2.update(cx, |_, c| c.emit(7));
3384        assert_eq!(handle_1.read(cx).events, vec![7]);
3385
3386        handle_2.update(cx, |_, c| c.emit(5));
3387        assert_eq!(handle_1.read(cx).events, vec![7, 10, 5]);
3388
3389        handle_3.update(cx, |_, c| c.emit(9));
3390        assert_eq!(handle_1.read(cx).events, vec![7, 10, 5, 9]);
3391    }
3392
3393    #[crate::test(self)]
3394    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
3395        struct View;
3396
3397        impl Entity for View {
3398            type Event = ();
3399        }
3400
3401        impl super::View for View {
3402            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3403                Empty::new().boxed()
3404            }
3405
3406            fn ui_name() -> &'static str {
3407                "View"
3408            }
3409        }
3410
3411        struct Model;
3412
3413        impl Entity for Model {
3414            type Event = ();
3415        }
3416
3417        let (window_id, _) = cx.add_window(Default::default(), |_| View);
3418        let observing_view = cx.add_view(window_id, |_| View);
3419        let emitting_view = cx.add_view(window_id, |_| View);
3420        let observing_model = cx.add_model(|_| Model);
3421        let observed_model = cx.add_model(|_| Model);
3422
3423        observing_view.update(cx, |_, cx| {
3424            cx.subscribe_to_view(&emitting_view, |_, _, _, _| {});
3425            cx.subscribe_to_model(&observed_model, |_, _, _, _| {});
3426        });
3427        observing_model.update(cx, |_, cx| {
3428            cx.subscribe(&observed_model, |_, _, _| {});
3429        });
3430
3431        cx.update(|| {
3432            drop(observing_view);
3433            drop(observing_model);
3434        });
3435
3436        emitting_view.update(cx, |_, cx| cx.emit(()));
3437        observed_model.update(cx, |_, cx| cx.emit(()));
3438    }
3439
3440    #[crate::test(self)]
3441    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
3442        #[derive(Default)]
3443        struct View {
3444            events: Vec<usize>,
3445        }
3446
3447        impl Entity for View {
3448            type Event = usize;
3449        }
3450
3451        impl super::View for View {
3452            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3453                Empty::new().boxed()
3454            }
3455
3456            fn ui_name() -> &'static str {
3457                "View"
3458            }
3459        }
3460
3461        #[derive(Default)]
3462        struct Model {
3463            count: usize,
3464        }
3465
3466        impl Entity for Model {
3467            type Event = ();
3468        }
3469
3470        let (_, view) = cx.add_window(Default::default(), |_| View::default());
3471        let model = cx.add_model(|_| Model::default());
3472
3473        view.update(cx, |_, c| {
3474            c.observe_model(&model, |me, observed, c| {
3475                me.events.push(observed.read(c).count)
3476            });
3477        });
3478
3479        model.update(cx, |model, c| {
3480            model.count = 11;
3481            c.notify();
3482        });
3483        assert_eq!(view.read(cx).events, vec![11]);
3484    }
3485
3486    #[crate::test(self)]
3487    fn test_dropping_observers(cx: &mut MutableAppContext) {
3488        struct View;
3489
3490        impl Entity for View {
3491            type Event = ();
3492        }
3493
3494        impl super::View for View {
3495            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3496                Empty::new().boxed()
3497            }
3498
3499            fn ui_name() -> &'static str {
3500                "View"
3501            }
3502        }
3503
3504        struct Model;
3505
3506        impl Entity for Model {
3507            type Event = ();
3508        }
3509
3510        let (window_id, _) = cx.add_window(Default::default(), |_| View);
3511        let observing_view = cx.add_view(window_id, |_| View);
3512        let observing_model = cx.add_model(|_| Model);
3513        let observed_model = cx.add_model(|_| Model);
3514
3515        observing_view.update(cx, |_, cx| {
3516            cx.observe_model(&observed_model, |_, _, _| {});
3517        });
3518        observing_model.update(cx, |_, cx| {
3519            cx.observe(&observed_model, |_, _, _| {});
3520        });
3521
3522        cx.update(|| {
3523            drop(observing_view);
3524            drop(observing_model);
3525        });
3526
3527        observed_model.update(cx, |_, cx| cx.notify());
3528    }
3529
3530    #[crate::test(self)]
3531    fn test_focus(cx: &mut MutableAppContext) {
3532        struct View {
3533            name: String,
3534            events: Arc<Mutex<Vec<String>>>,
3535        }
3536
3537        impl Entity for View {
3538            type Event = ();
3539        }
3540
3541        impl super::View for View {
3542            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3543                Empty::new().boxed()
3544            }
3545
3546            fn ui_name() -> &'static str {
3547                "View"
3548            }
3549
3550            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
3551                self.events.lock().push(format!("{} focused", &self.name));
3552            }
3553
3554            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
3555                self.events.lock().push(format!("{} blurred", &self.name));
3556            }
3557        }
3558
3559        let events: Arc<Mutex<Vec<String>>> = Default::default();
3560        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
3561            events: events.clone(),
3562            name: "view 1".to_string(),
3563        });
3564        let view_2 = cx.add_view(window_id, |_| View {
3565            events: events.clone(),
3566            name: "view 2".to_string(),
3567        });
3568
3569        view_1.update(cx, |_, cx| cx.focus(&view_2));
3570        view_1.update(cx, |_, cx| cx.focus(&view_1));
3571        view_1.update(cx, |_, cx| cx.focus(&view_2));
3572        view_1.update(cx, |_, _| drop(view_2));
3573
3574        assert_eq!(
3575            *events.lock(),
3576            [
3577                "view 1 focused".to_string(),
3578                "view 1 blurred".to_string(),
3579                "view 2 focused".to_string(),
3580                "view 2 blurred".to_string(),
3581                "view 1 focused".to_string(),
3582                "view 1 blurred".to_string(),
3583                "view 2 focused".to_string(),
3584                "view 1 focused".to_string(),
3585            ],
3586        );
3587    }
3588
3589    #[crate::test(self)]
3590    fn test_dispatch_action(cx: &mut MutableAppContext) {
3591        struct ViewA {
3592            id: usize,
3593        }
3594
3595        impl Entity for ViewA {
3596            type Event = ();
3597        }
3598
3599        impl View for ViewA {
3600            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3601                Empty::new().boxed()
3602            }
3603
3604            fn ui_name() -> &'static str {
3605                "View"
3606            }
3607        }
3608
3609        struct ViewB {
3610            id: usize,
3611        }
3612
3613        impl Entity for ViewB {
3614            type Event = ();
3615        }
3616
3617        impl View for ViewB {
3618            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3619                Empty::new().boxed()
3620            }
3621
3622            fn ui_name() -> &'static str {
3623                "View"
3624            }
3625        }
3626
3627        action!(Action, &'static str);
3628
3629        let actions = Rc::new(RefCell::new(Vec::new()));
3630
3631        let actions_clone = actions.clone();
3632        cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
3633            actions_clone.borrow_mut().push("global a".to_string());
3634        });
3635
3636        let actions_clone = actions.clone();
3637        cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
3638            actions_clone.borrow_mut().push("global b".to_string());
3639        });
3640
3641        let actions_clone = actions.clone();
3642        cx.add_action(move |view: &mut ViewA, action: &Action, cx| {
3643            assert_eq!(action.0, "bar");
3644            cx.propagate_action();
3645            actions_clone.borrow_mut().push(format!("{} a", view.id));
3646        });
3647
3648        let actions_clone = actions.clone();
3649        cx.add_action(move |view: &mut ViewA, _: &Action, cx| {
3650            if view.id != 1 {
3651                cx.propagate_action();
3652            }
3653            actions_clone.borrow_mut().push(format!("{} b", view.id));
3654        });
3655
3656        let actions_clone = actions.clone();
3657        cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
3658            cx.propagate_action();
3659            actions_clone.borrow_mut().push(format!("{} c", view.id));
3660        });
3661
3662        let actions_clone = actions.clone();
3663        cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
3664            cx.propagate_action();
3665            actions_clone.borrow_mut().push(format!("{} d", view.id));
3666        });
3667
3668        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
3669        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
3670        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
3671        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
3672
3673        cx.dispatch_action(
3674            window_id,
3675            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
3676            &Action("bar"),
3677        );
3678
3679        assert_eq!(
3680            *actions.borrow(),
3681            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "1 b"]
3682        );
3683
3684        // Remove view_1, which doesn't propagate the action
3685        actions.borrow_mut().clear();
3686        cx.dispatch_action(
3687            window_id,
3688            vec![view_2.id(), view_3.id(), view_4.id()],
3689            &Action("bar"),
3690        );
3691
3692        assert_eq!(
3693            *actions.borrow(),
3694            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "global b", "global a"]
3695        );
3696    }
3697
3698    #[crate::test(self)]
3699    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
3700        use std::cell::Cell;
3701
3702        action!(Action, &'static str);
3703
3704        struct View {
3705            id: usize,
3706            keymap_context: keymap::Context,
3707        }
3708
3709        impl Entity for View {
3710            type Event = ();
3711        }
3712
3713        impl super::View for View {
3714            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3715                Empty::new().boxed()
3716            }
3717
3718            fn ui_name() -> &'static str {
3719                "View"
3720            }
3721
3722            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
3723                self.keymap_context.clone()
3724            }
3725        }
3726
3727        impl View {
3728            fn new(id: usize) -> Self {
3729                View {
3730                    id,
3731                    keymap_context: keymap::Context::default(),
3732                }
3733            }
3734        }
3735
3736        let mut view_1 = View::new(1);
3737        let mut view_2 = View::new(2);
3738        let mut view_3 = View::new(3);
3739        view_1.keymap_context.set.insert("a".into());
3740        view_2.keymap_context.set.insert("b".into());
3741        view_3.keymap_context.set.insert("c".into());
3742
3743        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
3744        let view_2 = cx.add_view(window_id, |_| view_2);
3745        let view_3 = cx.add_view(window_id, |_| view_3);
3746
3747        // This keymap's only binding dispatches an action on view 2 because that view will have
3748        // "a" and "b" in its context, but not "c".
3749        cx.add_bindings(vec![keymap::Binding::new(
3750            "a",
3751            Action("a"),
3752            Some("a && b && !c"),
3753        )]);
3754
3755        let handled_action = Rc::new(Cell::new(false));
3756        let handled_action_clone = handled_action.clone();
3757        cx.add_action(move |view: &mut View, action: &Action, _| {
3758            handled_action_clone.set(true);
3759            assert_eq!(view.id, 2);
3760            assert_eq!(action.0, "a");
3761        });
3762
3763        cx.dispatch_keystroke(
3764            window_id,
3765            vec![view_1.id(), view_2.id(), view_3.id()],
3766            &Keystroke::parse("a").unwrap(),
3767        )
3768        .unwrap();
3769
3770        assert!(handled_action.get());
3771    }
3772
3773    #[crate::test(self)]
3774    async fn test_model_condition(mut cx: TestAppContext) {
3775        struct Counter(usize);
3776
3777        impl super::Entity for Counter {
3778            type Event = ();
3779        }
3780
3781        impl Counter {
3782            fn inc(&mut self, cx: &mut ModelContext<Self>) {
3783                self.0 += 1;
3784                cx.notify();
3785            }
3786        }
3787
3788        let model = cx.add_model(|_| Counter(0));
3789
3790        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
3791        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
3792        smol::pin!(condition1, condition2);
3793
3794        model.update(&mut cx, |model, cx| model.inc(cx));
3795        assert_eq!(poll_once(&mut condition1).await, None);
3796        assert_eq!(poll_once(&mut condition2).await, None);
3797
3798        model.update(&mut cx, |model, cx| model.inc(cx));
3799        assert_eq!(poll_once(&mut condition1).await, Some(()));
3800        assert_eq!(poll_once(&mut condition2).await, None);
3801
3802        model.update(&mut cx, |model, cx| model.inc(cx));
3803        assert_eq!(poll_once(&mut condition2).await, Some(()));
3804
3805        model.update(&mut cx, |_, cx| cx.notify());
3806    }
3807
3808    #[crate::test(self)]
3809    #[should_panic]
3810    async fn test_model_condition_timeout(mut cx: TestAppContext) {
3811        struct Model;
3812
3813        impl super::Entity for Model {
3814            type Event = ();
3815        }
3816
3817        let model = cx.add_model(|_| Model);
3818        model.condition(&cx, |_, _| false).await;
3819    }
3820
3821    #[crate::test(self)]
3822    #[should_panic(expected = "model dropped with pending condition")]
3823    async fn test_model_condition_panic_on_drop(mut cx: TestAppContext) {
3824        struct Model;
3825
3826        impl super::Entity for Model {
3827            type Event = ();
3828        }
3829
3830        let model = cx.add_model(|_| Model);
3831        let condition = model.condition(&cx, |_, _| false);
3832        cx.update(|_| drop(model));
3833        condition.await;
3834    }
3835
3836    #[crate::test(self)]
3837    async fn test_view_condition(mut cx: TestAppContext) {
3838        struct Counter(usize);
3839
3840        impl super::Entity for Counter {
3841            type Event = ();
3842        }
3843
3844        impl super::View for Counter {
3845            fn ui_name() -> &'static str {
3846                "test view"
3847            }
3848
3849            fn render(&self, _: &RenderContext<Self>) -> ElementBox {
3850                Empty::new().boxed()
3851            }
3852        }
3853
3854        impl Counter {
3855            fn inc(&mut self, cx: &mut ViewContext<Self>) {
3856                self.0 += 1;
3857                cx.notify();
3858            }
3859        }
3860
3861        let (_, view) = cx.add_window(|_| Counter(0));
3862
3863        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
3864        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
3865        smol::pin!(condition1, condition2);
3866
3867        view.update(&mut cx, |view, cx| view.inc(cx));
3868        assert_eq!(poll_once(&mut condition1).await, None);
3869        assert_eq!(poll_once(&mut condition2).await, None);
3870
3871        view.update(&mut cx, |view, cx| view.inc(cx));
3872        assert_eq!(poll_once(&mut condition1).await, Some(()));
3873        assert_eq!(poll_once(&mut condition2).await, None);
3874
3875        view.update(&mut cx, |view, cx| view.inc(cx));
3876        assert_eq!(poll_once(&mut condition2).await, Some(()));
3877        view.update(&mut cx, |_, cx| cx.notify());
3878    }
3879
3880    #[crate::test(self)]
3881    #[should_panic]
3882    async fn test_view_condition_timeout(mut cx: TestAppContext) {
3883        struct View;
3884
3885        impl super::Entity for View {
3886            type Event = ();
3887        }
3888
3889        impl super::View for View {
3890            fn ui_name() -> &'static str {
3891                "test view"
3892            }
3893
3894            fn render(&self, _: &RenderContext<Self>) -> ElementBox {
3895                Empty::new().boxed()
3896            }
3897        }
3898
3899        let (_, view) = cx.add_window(|_| View);
3900        view.condition(&cx, |_, _| false).await;
3901    }
3902
3903    #[crate::test(self)]
3904    #[should_panic(expected = "view dropped with pending condition")]
3905    async fn test_view_condition_panic_on_drop(mut cx: TestAppContext) {
3906        struct View;
3907
3908        impl super::Entity for View {
3909            type Event = ();
3910        }
3911
3912        impl super::View for View {
3913            fn ui_name() -> &'static str {
3914                "test view"
3915            }
3916
3917            fn render(&self, _: &RenderContext<Self>) -> ElementBox {
3918                Empty::new().boxed()
3919            }
3920        }
3921
3922        let window_id = cx.add_window(|_| View).0;
3923        let view = cx.add_view(window_id, |_| View);
3924
3925        let condition = view.condition(&cx, |_, _| false);
3926        cx.update(|_| drop(view));
3927        condition.await;
3928    }
3929}