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