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