app.rs

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