app.rs

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