app.rs

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