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 =
1435                        presenter.build_scene(window.size(), window.scale_factor(), false, self);
1436                    window.present_scene(scene);
1437                }
1438                self.presenters_and_platform_windows
1439                    .insert(window_id, (presenter, window));
1440            }
1441        }
1442    }
1443
1444    fn resize_window(&mut self, window_id: usize) {
1445        self.pending_effects
1446            .push_back(Effect::ResizeWindow { window_id });
1447    }
1448
1449    pub fn refresh_windows(&mut self) {
1450        self.pending_effects.push_back(Effect::RefreshWindows);
1451    }
1452
1453    fn perform_window_refresh(&mut self) {
1454        let mut presenters = mem::take(&mut self.presenters_and_platform_windows);
1455        for (window_id, (presenter, window)) in &mut presenters {
1456            let invalidation = self
1457                .cx
1458                .windows
1459                .get_mut(&window_id)
1460                .unwrap()
1461                .invalidation
1462                .take();
1463            let mut presenter = presenter.borrow_mut();
1464            presenter.refresh(invalidation, self);
1465            let scene = presenter.build_scene(window.size(), window.scale_factor(), true, self);
1466            window.present_scene(scene);
1467        }
1468        self.presenters_and_platform_windows = presenters;
1469    }
1470
1471    pub fn set_cursor_style(&mut self, style: CursorStyle) -> CursorStyleHandle {
1472        self.platform.set_cursor_style(style);
1473        let id = self.next_cursor_style_handle_id.fetch_add(1, SeqCst);
1474        CursorStyleHandle {
1475            id,
1476            next_cursor_style_handle_id: self.next_cursor_style_handle_id.clone(),
1477            platform: self.platform(),
1478        }
1479    }
1480
1481    fn emit_event(&mut self, entity_id: usize, payload: Box<dyn Any>) {
1482        let callbacks = self.subscriptions.lock().remove(&entity_id);
1483        if let Some(callbacks) = callbacks {
1484            for (id, mut callback) in callbacks {
1485                let alive = callback(payload.as_ref(), self);
1486                if alive {
1487                    self.subscriptions
1488                        .lock()
1489                        .entry(entity_id)
1490                        .or_default()
1491                        .insert(id, callback);
1492                }
1493            }
1494        }
1495    }
1496
1497    fn notify_model_observers(&mut self, observed_id: usize) {
1498        let callbacks = self.observations.lock().remove(&observed_id);
1499        if let Some(callbacks) = callbacks {
1500            if self.cx.models.contains_key(&observed_id) {
1501                for (id, mut callback) in callbacks {
1502                    let alive = callback(self);
1503                    if alive {
1504                        self.observations
1505                            .lock()
1506                            .entry(observed_id)
1507                            .or_default()
1508                            .insert(id, callback);
1509                    }
1510                }
1511            }
1512        }
1513    }
1514
1515    fn notify_view_observers(&mut self, observed_window_id: usize, observed_view_id: usize) {
1516        if let Some(window) = self.cx.windows.get_mut(&observed_window_id) {
1517            window
1518                .invalidation
1519                .get_or_insert_with(Default::default)
1520                .updated
1521                .insert(observed_view_id);
1522        }
1523
1524        let callbacks = self.observations.lock().remove(&observed_view_id);
1525        if let Some(callbacks) = callbacks {
1526            if self
1527                .cx
1528                .views
1529                .contains_key(&(observed_window_id, observed_view_id))
1530            {
1531                for (id, mut callback) in callbacks {
1532                    let alive = callback(self);
1533                    if alive {
1534                        self.observations
1535                            .lock()
1536                            .entry(observed_view_id)
1537                            .or_default()
1538                            .insert(id, callback);
1539                    }
1540                }
1541            }
1542        }
1543    }
1544
1545    fn focus(&mut self, window_id: usize, focused_id: usize) {
1546        if self
1547            .cx
1548            .windows
1549            .get(&window_id)
1550            .map(|w| w.focused_view_id)
1551            .map_or(false, |cur_focused| cur_focused == focused_id)
1552        {
1553            return;
1554        }
1555
1556        self.pending_flushes += 1;
1557
1558        let blurred_id = self.cx.windows.get_mut(&window_id).map(|window| {
1559            let blurred_id = window.focused_view_id;
1560            window.focused_view_id = focused_id;
1561            blurred_id
1562        });
1563
1564        if let Some(blurred_id) = blurred_id {
1565            if let Some(mut blurred_view) = self.cx.views.remove(&(window_id, blurred_id)) {
1566                blurred_view.on_blur(self, window_id, blurred_id);
1567                self.cx.views.insert((window_id, blurred_id), blurred_view);
1568            }
1569        }
1570
1571        if let Some(mut focused_view) = self.cx.views.remove(&(window_id, focused_id)) {
1572            focused_view.on_focus(self, window_id, focused_id);
1573            self.cx.views.insert((window_id, focused_id), focused_view);
1574        }
1575
1576        self.flush_effects();
1577    }
1578
1579    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
1580    where
1581        F: FnOnce(AsyncAppContext) -> Fut,
1582        Fut: 'static + Future<Output = T>,
1583        T: 'static,
1584    {
1585        let cx = self.to_async();
1586        self.foreground.spawn(f(cx))
1587    }
1588
1589    pub fn to_async(&self) -> AsyncAppContext {
1590        AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
1591    }
1592
1593    pub fn write_to_clipboard(&self, item: ClipboardItem) {
1594        self.cx.platform.write_to_clipboard(item);
1595    }
1596
1597    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1598        self.cx.platform.read_from_clipboard()
1599    }
1600}
1601
1602impl ReadModel for MutableAppContext {
1603    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1604        if let Some(model) = self.cx.models.get(&handle.model_id) {
1605            model
1606                .as_any()
1607                .downcast_ref()
1608                .expect("downcast is type safe")
1609        } else {
1610            panic!("circular model reference");
1611        }
1612    }
1613}
1614
1615impl UpdateModel for MutableAppContext {
1616    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
1617    where
1618        T: Entity,
1619        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
1620    {
1621        if let Some(mut model) = self.cx.models.remove(&handle.model_id) {
1622            self.pending_flushes += 1;
1623            let mut cx = ModelContext::new(self, handle.model_id);
1624            let result = update(
1625                model
1626                    .as_any_mut()
1627                    .downcast_mut()
1628                    .expect("downcast is type safe"),
1629                &mut cx,
1630            );
1631            self.cx.models.insert(handle.model_id, model);
1632            self.flush_effects();
1633            result
1634        } else {
1635            panic!("circular model update");
1636        }
1637    }
1638}
1639
1640impl UpgradeModelHandle for MutableAppContext {
1641    fn upgrade_model_handle<T: Entity>(
1642        &self,
1643        handle: WeakModelHandle<T>,
1644    ) -> Option<ModelHandle<T>> {
1645        self.cx.upgrade_model_handle(handle)
1646    }
1647}
1648
1649impl ReadView for MutableAppContext {
1650    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1651        if let Some(view) = self.cx.views.get(&(handle.window_id, handle.view_id)) {
1652            view.as_any().downcast_ref().expect("downcast is type safe")
1653        } else {
1654            panic!("circular view reference");
1655        }
1656    }
1657}
1658
1659impl UpdateView for MutableAppContext {
1660    fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
1661    where
1662        T: View,
1663        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
1664    {
1665        self.pending_flushes += 1;
1666        let mut view = self
1667            .cx
1668            .views
1669            .remove(&(handle.window_id, handle.view_id))
1670            .expect("circular view update");
1671
1672        let mut cx = ViewContext::new(self, handle.window_id, handle.view_id);
1673        let result = update(
1674            view.as_any_mut()
1675                .downcast_mut()
1676                .expect("downcast is type safe"),
1677            &mut cx,
1678        );
1679        self.cx
1680            .views
1681            .insert((handle.window_id, handle.view_id), view);
1682        self.flush_effects();
1683        result
1684    }
1685}
1686
1687impl AsRef<AppContext> for MutableAppContext {
1688    fn as_ref(&self) -> &AppContext {
1689        &self.cx
1690    }
1691}
1692
1693impl Deref for MutableAppContext {
1694    type Target = AppContext;
1695
1696    fn deref(&self) -> &Self::Target {
1697        &self.cx
1698    }
1699}
1700
1701pub struct AppContext {
1702    models: HashMap<usize, Box<dyn AnyModel>>,
1703    views: HashMap<(usize, usize), Box<dyn AnyView>>,
1704    windows: HashMap<usize, Window>,
1705    element_states: HashMap<(TypeId, ElementStateId), Box<dyn Any>>,
1706    background: Arc<executor::Background>,
1707    ref_counts: Arc<Mutex<RefCounts>>,
1708    font_cache: Arc<FontCache>,
1709    platform: Arc<dyn Platform>,
1710}
1711
1712impl AppContext {
1713    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
1714        self.windows
1715            .get(&window_id)
1716            .map(|window| window.root_view.id())
1717    }
1718
1719    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
1720        self.windows
1721            .get(&window_id)
1722            .map(|window| window.focused_view_id)
1723    }
1724
1725    pub fn background(&self) -> &Arc<executor::Background> {
1726        &self.background
1727    }
1728
1729    pub fn font_cache(&self) -> &Arc<FontCache> {
1730        &self.font_cache
1731    }
1732
1733    pub fn platform(&self) -> &Arc<dyn Platform> {
1734        &self.platform
1735    }
1736}
1737
1738impl ReadModel for AppContext {
1739    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1740        if let Some(model) = self.models.get(&handle.model_id) {
1741            model
1742                .as_any()
1743                .downcast_ref()
1744                .expect("downcast should be type safe")
1745        } else {
1746            panic!("circular model reference");
1747        }
1748    }
1749}
1750
1751impl UpgradeModelHandle for AppContext {
1752    fn upgrade_model_handle<T: Entity>(
1753        &self,
1754        handle: WeakModelHandle<T>,
1755    ) -> Option<ModelHandle<T>> {
1756        if self.models.contains_key(&handle.model_id) {
1757            Some(ModelHandle::new(handle.model_id, &self.ref_counts))
1758        } else {
1759            None
1760        }
1761    }
1762}
1763
1764impl ReadView for AppContext {
1765    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1766        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
1767            view.as_any()
1768                .downcast_ref()
1769                .expect("downcast should be type safe")
1770        } else {
1771            panic!("circular view reference");
1772        }
1773    }
1774}
1775
1776struct Window {
1777    root_view: AnyViewHandle,
1778    focused_view_id: usize,
1779    invalidation: Option<WindowInvalidation>,
1780}
1781
1782#[derive(Default, Clone)]
1783pub struct WindowInvalidation {
1784    pub updated: HashSet<usize>,
1785    pub removed: Vec<usize>,
1786}
1787
1788pub enum Effect {
1789    Event {
1790        entity_id: usize,
1791        payload: Box<dyn Any>,
1792    },
1793    ModelNotification {
1794        model_id: usize,
1795    },
1796    ViewNotification {
1797        window_id: usize,
1798        view_id: usize,
1799    },
1800    Focus {
1801        window_id: usize,
1802        view_id: usize,
1803    },
1804    ResizeWindow {
1805        window_id: usize,
1806    },
1807    RefreshWindows,
1808}
1809
1810impl Debug for Effect {
1811    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1812        match self {
1813            Effect::Event { entity_id, .. } => f
1814                .debug_struct("Effect::Event")
1815                .field("entity_id", entity_id)
1816                .finish(),
1817            Effect::ModelNotification { model_id } => f
1818                .debug_struct("Effect::ModelNotification")
1819                .field("model_id", model_id)
1820                .finish(),
1821            Effect::ViewNotification { window_id, view_id } => f
1822                .debug_struct("Effect::ViewNotification")
1823                .field("window_id", window_id)
1824                .field("view_id", view_id)
1825                .finish(),
1826            Effect::Focus { window_id, view_id } => f
1827                .debug_struct("Effect::Focus")
1828                .field("window_id", window_id)
1829                .field("view_id", view_id)
1830                .finish(),
1831            Effect::ResizeWindow { window_id } => f
1832                .debug_struct("Effect::RefreshWindow")
1833                .field("window_id", window_id)
1834                .finish(),
1835            Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
1836        }
1837    }
1838}
1839
1840pub trait AnyModel {
1841    fn as_any(&self) -> &dyn Any;
1842    fn as_any_mut(&mut self) -> &mut dyn Any;
1843    fn release(&mut self, cx: &mut MutableAppContext);
1844}
1845
1846impl<T> AnyModel for T
1847where
1848    T: Entity,
1849{
1850    fn as_any(&self) -> &dyn Any {
1851        self
1852    }
1853
1854    fn as_any_mut(&mut self) -> &mut dyn Any {
1855        self
1856    }
1857
1858    fn release(&mut self, cx: &mut MutableAppContext) {
1859        self.release(cx);
1860    }
1861}
1862
1863pub trait AnyView {
1864    fn as_any(&self) -> &dyn Any;
1865    fn as_any_mut(&mut self) -> &mut dyn Any;
1866    fn release(&mut self, cx: &mut MutableAppContext);
1867    fn ui_name(&self) -> &'static str;
1868    fn render<'a>(
1869        &mut self,
1870        window_id: usize,
1871        view_id: usize,
1872        titlebar_height: f32,
1873        refreshing: bool,
1874        cx: &mut MutableAppContext,
1875    ) -> ElementBox;
1876    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
1877    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
1878    fn keymap_context(&self, cx: &AppContext) -> keymap::Context;
1879}
1880
1881impl<T> AnyView for T
1882where
1883    T: View,
1884{
1885    fn as_any(&self) -> &dyn Any {
1886        self
1887    }
1888
1889    fn as_any_mut(&mut self) -> &mut dyn Any {
1890        self
1891    }
1892
1893    fn release(&mut self, cx: &mut MutableAppContext) {
1894        self.release(cx);
1895    }
1896
1897    fn ui_name(&self) -> &'static str {
1898        T::ui_name()
1899    }
1900
1901    fn render<'a>(
1902        &mut self,
1903        window_id: usize,
1904        view_id: usize,
1905        titlebar_height: f32,
1906        refreshing: bool,
1907        cx: &mut MutableAppContext,
1908    ) -> ElementBox {
1909        View::render(
1910            self,
1911            &mut RenderContext {
1912                window_id,
1913                view_id,
1914                app: cx,
1915                view_type: PhantomData::<T>,
1916                titlebar_height,
1917                refreshing,
1918            },
1919        )
1920    }
1921
1922    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
1923        let mut cx = ViewContext::new(cx, window_id, view_id);
1924        View::on_focus(self, &mut cx);
1925    }
1926
1927    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
1928        let mut cx = ViewContext::new(cx, window_id, view_id);
1929        View::on_blur(self, &mut cx);
1930    }
1931
1932    fn keymap_context(&self, cx: &AppContext) -> keymap::Context {
1933        View::keymap_context(self, cx)
1934    }
1935}
1936
1937pub struct ModelContext<'a, T: ?Sized> {
1938    app: &'a mut MutableAppContext,
1939    model_id: usize,
1940    model_type: PhantomData<T>,
1941    halt_stream: bool,
1942}
1943
1944impl<'a, T: Entity> ModelContext<'a, T> {
1945    fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
1946        Self {
1947            app,
1948            model_id,
1949            model_type: PhantomData,
1950            halt_stream: false,
1951        }
1952    }
1953
1954    pub fn background(&self) -> &Arc<executor::Background> {
1955        &self.app.cx.background
1956    }
1957
1958    pub fn halt_stream(&mut self) {
1959        self.halt_stream = true;
1960    }
1961
1962    pub fn model_id(&self) -> usize {
1963        self.model_id
1964    }
1965
1966    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
1967    where
1968        S: Entity,
1969        F: FnOnce(&mut ModelContext<S>) -> S,
1970    {
1971        self.app.add_model(build_model)
1972    }
1973
1974    pub fn emit(&mut self, payload: T::Event) {
1975        self.app.pending_effects.push_back(Effect::Event {
1976            entity_id: self.model_id,
1977            payload: Box::new(payload),
1978        });
1979    }
1980
1981    pub fn notify(&mut self) {
1982        self.app
1983            .pending_effects
1984            .push_back(Effect::ModelNotification {
1985                model_id: self.model_id,
1986            });
1987    }
1988
1989    pub fn subscribe<S: Entity, F>(
1990        &mut self,
1991        handle: &ModelHandle<S>,
1992        mut callback: F,
1993    ) -> Subscription
1994    where
1995        S::Event: 'static,
1996        F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
1997    {
1998        let subscriber = self.handle().downgrade();
1999        self.app
2000            .subscribe_internal(handle, move |emitter, event, cx| {
2001                if let Some(subscriber) = subscriber.upgrade(cx) {
2002                    subscriber.update(cx, |subscriber, cx| {
2003                        callback(subscriber, emitter, event, cx);
2004                    });
2005                    true
2006                } else {
2007                    false
2008                }
2009            })
2010    }
2011
2012    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
2013    where
2014        S: Entity,
2015        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
2016    {
2017        let observer = self.handle().downgrade();
2018        self.app.observe_internal(handle, move |observed, cx| {
2019            if let Some(observer) = observer.upgrade(cx) {
2020                observer.update(cx, |observer, cx| {
2021                    callback(observer, observed, cx);
2022                });
2023                true
2024            } else {
2025                false
2026            }
2027        })
2028    }
2029
2030    pub fn handle(&self) -> ModelHandle<T> {
2031        ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
2032    }
2033
2034    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2035    where
2036        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
2037        Fut: 'static + Future<Output = S>,
2038        S: 'static,
2039    {
2040        let handle = self.handle();
2041        self.app.spawn(|cx| f(handle, cx))
2042    }
2043
2044    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
2045    where
2046        F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
2047        Fut: 'static + Future<Output = S>,
2048        S: 'static,
2049    {
2050        let handle = self.handle().downgrade();
2051        self.app.spawn(|cx| f(handle, cx))
2052    }
2053}
2054
2055impl<M> AsRef<AppContext> for ModelContext<'_, M> {
2056    fn as_ref(&self) -> &AppContext {
2057        &self.app.cx
2058    }
2059}
2060
2061impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
2062    fn as_mut(&mut self) -> &mut MutableAppContext {
2063        self.app
2064    }
2065}
2066
2067impl<M> ReadModel for ModelContext<'_, M> {
2068    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2069        self.app.read_model(handle)
2070    }
2071}
2072
2073impl<M> UpdateModel for ModelContext<'_, M> {
2074    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
2075    where
2076        T: Entity,
2077        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2078    {
2079        self.app.update_model(handle, update)
2080    }
2081}
2082
2083impl<M> UpgradeModelHandle for ModelContext<'_, M> {
2084    fn upgrade_model_handle<T: Entity>(
2085        &self,
2086        handle: WeakModelHandle<T>,
2087    ) -> Option<ModelHandle<T>> {
2088        self.cx.upgrade_model_handle(handle)
2089    }
2090}
2091
2092impl<M> Deref for ModelContext<'_, M> {
2093    type Target = MutableAppContext;
2094
2095    fn deref(&self) -> &Self::Target {
2096        &self.app
2097    }
2098}
2099
2100impl<M> DerefMut for ModelContext<'_, M> {
2101    fn deref_mut(&mut self) -> &mut Self::Target {
2102        &mut self.app
2103    }
2104}
2105
2106pub struct ViewContext<'a, T: ?Sized> {
2107    app: &'a mut MutableAppContext,
2108    window_id: usize,
2109    view_id: usize,
2110    view_type: PhantomData<T>,
2111    halt_action_dispatch: bool,
2112}
2113
2114impl<'a, T: View> ViewContext<'a, T> {
2115    fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
2116        Self {
2117            app,
2118            window_id,
2119            view_id,
2120            view_type: PhantomData,
2121            halt_action_dispatch: true,
2122        }
2123    }
2124
2125    pub fn handle(&self) -> ViewHandle<T> {
2126        ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
2127    }
2128
2129    pub fn window_id(&self) -> usize {
2130        self.window_id
2131    }
2132
2133    pub fn view_id(&self) -> usize {
2134        self.view_id
2135    }
2136
2137    pub fn foreground(&self) -> &Rc<executor::Foreground> {
2138        self.app.foreground()
2139    }
2140
2141    pub fn background_executor(&self) -> &Arc<executor::Background> {
2142        &self.app.cx.background
2143    }
2144
2145    pub fn platform(&self) -> Arc<dyn Platform> {
2146        self.app.platform()
2147    }
2148
2149    pub fn prompt<F>(&self, level: PromptLevel, msg: &str, answers: &[&str], done_fn: F)
2150    where
2151        F: 'static + FnOnce(usize, &mut MutableAppContext),
2152    {
2153        self.app
2154            .prompt(self.window_id, level, msg, answers, done_fn)
2155    }
2156
2157    pub fn prompt_for_paths<F>(&self, options: PathPromptOptions, done_fn: F)
2158    where
2159        F: 'static + FnOnce(Option<Vec<PathBuf>>, &mut MutableAppContext),
2160    {
2161        self.app.prompt_for_paths(options, done_fn)
2162    }
2163
2164    pub fn prompt_for_new_path<F>(&self, directory: &Path, done_fn: F)
2165    where
2166        F: 'static + FnOnce(Option<PathBuf>, &mut MutableAppContext),
2167    {
2168        self.app.prompt_for_new_path(directory, done_fn)
2169    }
2170
2171    pub fn debug_elements(&self) -> crate::json::Value {
2172        self.app.debug_elements(self.window_id).unwrap()
2173    }
2174
2175    pub fn focus<S>(&mut self, handle: S)
2176    where
2177        S: Into<AnyViewHandle>,
2178    {
2179        let handle = handle.into();
2180        self.app.pending_effects.push_back(Effect::Focus {
2181            window_id: handle.window_id,
2182            view_id: handle.view_id,
2183        });
2184    }
2185
2186    pub fn focus_self(&mut self) {
2187        self.app.pending_effects.push_back(Effect::Focus {
2188            window_id: self.window_id,
2189            view_id: self.view_id,
2190        });
2191    }
2192
2193    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2194    where
2195        S: Entity,
2196        F: FnOnce(&mut ModelContext<S>) -> S,
2197    {
2198        self.app.add_model(build_model)
2199    }
2200
2201    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
2202    where
2203        S: View,
2204        F: FnOnce(&mut ViewContext<S>) -> S,
2205    {
2206        self.app.add_view(self.window_id, build_view)
2207    }
2208
2209    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
2210    where
2211        S: View,
2212        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
2213    {
2214        self.app.add_option_view(self.window_id, build_view)
2215    }
2216
2217    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
2218    where
2219        E: Entity,
2220        E::Event: 'static,
2221        H: Handle<E>,
2222        F: 'static + FnMut(&mut T, H, &E::Event, &mut ViewContext<T>),
2223    {
2224        let subscriber = self.handle().downgrade();
2225        self.app
2226            .subscribe_internal(handle, move |emitter, event, cx| {
2227                if let Some(subscriber) = subscriber.upgrade(cx) {
2228                    subscriber.update(cx, |subscriber, cx| {
2229                        callback(subscriber, emitter, event, cx);
2230                    });
2231                    true
2232                } else {
2233                    false
2234                }
2235            })
2236    }
2237
2238    pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2239    where
2240        E: Entity,
2241        H: Handle<E>,
2242        F: 'static + FnMut(&mut T, H, &mut ViewContext<T>),
2243    {
2244        let observer = self.handle().downgrade();
2245        self.app.observe_internal(handle, move |observed, cx| {
2246            if let Some(observer) = observer.upgrade(cx) {
2247                observer.update(cx, |observer, cx| {
2248                    callback(observer, observed, cx);
2249                });
2250                true
2251            } else {
2252                false
2253            }
2254        })
2255    }
2256
2257    pub fn emit(&mut self, payload: T::Event) {
2258        self.app.pending_effects.push_back(Effect::Event {
2259            entity_id: self.view_id,
2260            payload: Box::new(payload),
2261        });
2262    }
2263
2264    pub fn notify(&mut self) {
2265        self.app.notify_view(self.window_id, self.view_id);
2266    }
2267
2268    pub fn propagate_action(&mut self) {
2269        self.halt_action_dispatch = false;
2270    }
2271
2272    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2273    where
2274        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
2275        Fut: 'static + Future<Output = S>,
2276        S: 'static,
2277    {
2278        let handle = self.handle();
2279        self.app.spawn(|cx| f(handle, cx))
2280    }
2281}
2282
2283pub struct RenderContext<'a, T: View> {
2284    pub app: &'a mut MutableAppContext,
2285    pub titlebar_height: f32,
2286    pub refreshing: bool,
2287    window_id: usize,
2288    view_id: usize,
2289    view_type: PhantomData<T>,
2290}
2291
2292impl<'a, T: View> RenderContext<'a, T> {
2293    pub fn handle(&self) -> WeakViewHandle<T> {
2294        WeakViewHandle::new(self.window_id, self.view_id)
2295    }
2296}
2297
2298impl AsRef<AppContext> for &AppContext {
2299    fn as_ref(&self) -> &AppContext {
2300        self
2301    }
2302}
2303
2304impl<V: View> Deref for RenderContext<'_, V> {
2305    type Target = MutableAppContext;
2306
2307    fn deref(&self) -> &Self::Target {
2308        self.app
2309    }
2310}
2311
2312impl<V: View> DerefMut for RenderContext<'_, V> {
2313    fn deref_mut(&mut self) -> &mut Self::Target {
2314        self.app
2315    }
2316}
2317
2318impl<V: View> ReadModel for RenderContext<'_, V> {
2319    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2320        self.app.read_model(handle)
2321    }
2322}
2323
2324impl<M> AsRef<AppContext> for ViewContext<'_, M> {
2325    fn as_ref(&self) -> &AppContext {
2326        &self.app.cx
2327    }
2328}
2329
2330impl<M> Deref for ViewContext<'_, M> {
2331    type Target = MutableAppContext;
2332
2333    fn deref(&self) -> &Self::Target {
2334        &self.app
2335    }
2336}
2337
2338impl<M> DerefMut for ViewContext<'_, M> {
2339    fn deref_mut(&mut self) -> &mut Self::Target {
2340        &mut self.app
2341    }
2342}
2343
2344impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
2345    fn as_mut(&mut self) -> &mut MutableAppContext {
2346        self.app
2347    }
2348}
2349
2350impl<V> ReadModel for ViewContext<'_, V> {
2351    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2352        self.app.read_model(handle)
2353    }
2354}
2355
2356impl<V> UpgradeModelHandle for ViewContext<'_, V> {
2357    fn upgrade_model_handle<T: Entity>(
2358        &self,
2359        handle: WeakModelHandle<T>,
2360    ) -> Option<ModelHandle<T>> {
2361        self.cx.upgrade_model_handle(handle)
2362    }
2363}
2364
2365impl<V: View> UpdateModel for ViewContext<'_, V> {
2366    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
2367    where
2368        T: Entity,
2369        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2370    {
2371        self.app.update_model(handle, update)
2372    }
2373}
2374
2375impl<V: View> ReadView for ViewContext<'_, V> {
2376    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2377        self.app.read_view(handle)
2378    }
2379}
2380
2381impl<V: View> UpdateView for ViewContext<'_, V> {
2382    fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
2383    where
2384        T: View,
2385        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2386    {
2387        self.app.update_view(handle, update)
2388    }
2389}
2390
2391pub trait Handle<T> {
2392    type Weak: 'static;
2393    fn id(&self) -> usize;
2394    fn location(&self) -> EntityLocation;
2395    fn downgrade(&self) -> Self::Weak;
2396    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2397    where
2398        Self: Sized;
2399}
2400
2401#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
2402pub enum EntityLocation {
2403    Model(usize),
2404    View(usize, usize),
2405}
2406
2407pub struct ModelHandle<T> {
2408    model_id: usize,
2409    model_type: PhantomData<T>,
2410    ref_counts: Arc<Mutex<RefCounts>>,
2411}
2412
2413impl<T: Entity> ModelHandle<T> {
2414    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2415        ref_counts.lock().inc_model(model_id);
2416        Self {
2417            model_id,
2418            model_type: PhantomData,
2419            ref_counts: ref_counts.clone(),
2420        }
2421    }
2422
2423    pub fn downgrade(&self) -> WeakModelHandle<T> {
2424        WeakModelHandle::new(self.model_id)
2425    }
2426
2427    pub fn id(&self) -> usize {
2428        self.model_id
2429    }
2430
2431    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
2432        cx.read_model(self)
2433    }
2434
2435    pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
2436    where
2437        C: ReadModelWith,
2438        F: FnOnce(&T, &AppContext) -> S,
2439    {
2440        cx.read_model_with(self, read)
2441    }
2442
2443    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2444    where
2445        C: UpdateModel,
2446        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2447    {
2448        cx.update_model(self, update)
2449    }
2450
2451    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
2452        let (mut tx, mut rx) = mpsc::channel(1);
2453        let mut cx = cx.cx.borrow_mut();
2454        let subscription = cx.observe(self, move |_, _| {
2455            tx.blocking_send(()).ok();
2456        });
2457
2458        let duration = if std::env::var("CI").is_ok() {
2459            Duration::from_secs(5)
2460        } else {
2461            Duration::from_secs(1)
2462        };
2463
2464        async move {
2465            let notification = timeout(duration, rx.recv())
2466                .await
2467                .expect("next notification timed out");
2468            drop(subscription);
2469            notification.expect("model dropped while test was waiting for its next notification")
2470        }
2471    }
2472
2473    pub fn next_event(&self, cx: &TestAppContext) -> impl Future<Output = T::Event>
2474    where
2475        T::Event: Clone,
2476    {
2477        let (mut tx, mut rx) = mpsc::channel(1);
2478        let mut cx = cx.cx.borrow_mut();
2479        let subscription = cx.subscribe(self, move |_, event, _| {
2480            tx.blocking_send(event.clone()).ok();
2481        });
2482
2483        let duration = if std::env::var("CI").is_ok() {
2484            Duration::from_secs(5)
2485        } else {
2486            Duration::from_secs(1)
2487        };
2488
2489        async move {
2490            let event = timeout(duration, rx.recv())
2491                .await
2492                .expect("next event timed out");
2493            drop(subscription);
2494            event.expect("model dropped while test was waiting for its next event")
2495        }
2496    }
2497
2498    pub fn condition(
2499        &self,
2500        cx: &TestAppContext,
2501        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2502    ) -> impl Future<Output = ()> {
2503        let (tx, mut rx) = mpsc::channel(1024);
2504
2505        let mut cx = cx.cx.borrow_mut();
2506        let subscriptions = (
2507            cx.observe(self, {
2508                let mut tx = tx.clone();
2509                move |_, _| {
2510                    tx.blocking_send(()).ok();
2511                }
2512            }),
2513            cx.subscribe(self, {
2514                let mut tx = tx.clone();
2515                move |_, _, _| {
2516                    tx.blocking_send(()).ok();
2517                }
2518            }),
2519        );
2520
2521        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2522        let handle = self.downgrade();
2523        let duration = if std::env::var("CI").is_ok() {
2524            Duration::from_secs(5)
2525        } else {
2526            Duration::from_secs(1)
2527        };
2528
2529        async move {
2530            timeout(duration, async move {
2531                loop {
2532                    {
2533                        let cx = cx.borrow();
2534                        let cx = cx.as_ref();
2535                        if predicate(
2536                            handle
2537                                .upgrade(cx)
2538                                .expect("model dropped with pending condition")
2539                                .read(cx),
2540                            cx,
2541                        ) {
2542                            break;
2543                        }
2544                    }
2545
2546                    rx.recv()
2547                        .await
2548                        .expect("model dropped with pending condition");
2549                }
2550            })
2551            .await
2552            .expect("condition timed out");
2553            drop(subscriptions);
2554        }
2555    }
2556}
2557
2558impl<T> Clone for ModelHandle<T> {
2559    fn clone(&self) -> Self {
2560        self.ref_counts.lock().inc_model(self.model_id);
2561        Self {
2562            model_id: self.model_id,
2563            model_type: PhantomData,
2564            ref_counts: self.ref_counts.clone(),
2565        }
2566    }
2567}
2568
2569impl<T> PartialEq for ModelHandle<T> {
2570    fn eq(&self, other: &Self) -> bool {
2571        self.model_id == other.model_id
2572    }
2573}
2574
2575impl<T> Eq for ModelHandle<T> {}
2576
2577impl<T> Hash for ModelHandle<T> {
2578    fn hash<H: Hasher>(&self, state: &mut H) {
2579        self.model_id.hash(state);
2580    }
2581}
2582
2583impl<T> std::borrow::Borrow<usize> for ModelHandle<T> {
2584    fn borrow(&self) -> &usize {
2585        &self.model_id
2586    }
2587}
2588
2589impl<T> Debug for ModelHandle<T> {
2590    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2591        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
2592            .field(&self.model_id)
2593            .finish()
2594    }
2595}
2596
2597unsafe impl<T> Send for ModelHandle<T> {}
2598unsafe impl<T> Sync for ModelHandle<T> {}
2599
2600impl<T> Drop for ModelHandle<T> {
2601    fn drop(&mut self) {
2602        self.ref_counts.lock().dec_model(self.model_id);
2603    }
2604}
2605
2606impl<T: Entity> Handle<T> for ModelHandle<T> {
2607    type Weak = WeakModelHandle<T>;
2608
2609    fn id(&self) -> usize {
2610        self.model_id
2611    }
2612
2613    fn location(&self) -> EntityLocation {
2614        EntityLocation::Model(self.model_id)
2615    }
2616
2617    fn downgrade(&self) -> Self::Weak {
2618        self.downgrade()
2619    }
2620
2621    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2622    where
2623        Self: Sized,
2624    {
2625        weak.upgrade(cx)
2626    }
2627}
2628
2629pub struct WeakModelHandle<T> {
2630    model_id: usize,
2631    model_type: PhantomData<T>,
2632}
2633
2634unsafe impl<T> Send for WeakModelHandle<T> {}
2635unsafe impl<T> Sync for WeakModelHandle<T> {}
2636
2637impl<T: Entity> WeakModelHandle<T> {
2638    fn new(model_id: usize) -> Self {
2639        Self {
2640            model_id,
2641            model_type: PhantomData,
2642        }
2643    }
2644
2645    pub fn upgrade(self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
2646        cx.upgrade_model_handle(self)
2647    }
2648}
2649
2650impl<T> Hash for WeakModelHandle<T> {
2651    fn hash<H: Hasher>(&self, state: &mut H) {
2652        self.model_id.hash(state)
2653    }
2654}
2655
2656impl<T> PartialEq for WeakModelHandle<T> {
2657    fn eq(&self, other: &Self) -> bool {
2658        self.model_id == other.model_id
2659    }
2660}
2661
2662impl<T> Eq for WeakModelHandle<T> {}
2663
2664impl<T> Clone for WeakModelHandle<T> {
2665    fn clone(&self) -> Self {
2666        Self {
2667            model_id: self.model_id,
2668            model_type: PhantomData,
2669        }
2670    }
2671}
2672
2673impl<T> Copy for WeakModelHandle<T> {}
2674
2675pub struct ViewHandle<T> {
2676    window_id: usize,
2677    view_id: usize,
2678    view_type: PhantomData<T>,
2679    ref_counts: Arc<Mutex<RefCounts>>,
2680}
2681
2682impl<T: View> ViewHandle<T> {
2683    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2684        ref_counts.lock().inc_view(window_id, view_id);
2685        Self {
2686            window_id,
2687            view_id,
2688            view_type: PhantomData,
2689            ref_counts: ref_counts.clone(),
2690        }
2691    }
2692
2693    pub fn downgrade(&self) -> WeakViewHandle<T> {
2694        WeakViewHandle::new(self.window_id, self.view_id)
2695    }
2696
2697    pub fn window_id(&self) -> usize {
2698        self.window_id
2699    }
2700
2701    pub fn id(&self) -> usize {
2702        self.view_id
2703    }
2704
2705    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
2706        cx.read_view(self)
2707    }
2708
2709    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
2710    where
2711        C: ReadViewWith,
2712        F: FnOnce(&T, &AppContext) -> S,
2713    {
2714        cx.read_view_with(self, read)
2715    }
2716
2717    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2718    where
2719        C: UpdateView,
2720        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2721    {
2722        cx.update_view(self, update)
2723    }
2724
2725    pub fn is_focused(&self, cx: &AppContext) -> bool {
2726        cx.focused_view_id(self.window_id)
2727            .map_or(false, |focused_id| focused_id == self.view_id)
2728    }
2729
2730    pub fn condition(
2731        &self,
2732        cx: &TestAppContext,
2733        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2734    ) -> impl Future<Output = ()> {
2735        let (tx, mut rx) = mpsc::channel(1024);
2736
2737        let mut cx = cx.cx.borrow_mut();
2738        let subscriptions = self.update(&mut *cx, |_, cx| {
2739            (
2740                cx.observe(self, {
2741                    let mut tx = tx.clone();
2742                    move |_, _, _| {
2743                        tx.blocking_send(()).ok();
2744                    }
2745                }),
2746                cx.subscribe(self, {
2747                    let mut tx = tx.clone();
2748                    move |_, _, _, _| {
2749                        tx.blocking_send(()).ok();
2750                    }
2751                }),
2752            )
2753        });
2754
2755        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2756        let handle = self.downgrade();
2757        let duration = if std::env::var("CI").is_ok() {
2758            Duration::from_secs(2)
2759        } else {
2760            Duration::from_millis(500)
2761        };
2762
2763        async move {
2764            timeout(duration, async move {
2765                loop {
2766                    {
2767                        let cx = cx.borrow();
2768                        let cx = cx.as_ref();
2769                        if predicate(
2770                            handle
2771                                .upgrade(cx)
2772                                .expect("view dropped with pending condition")
2773                                .read(cx),
2774                            cx,
2775                        ) {
2776                            break;
2777                        }
2778                    }
2779
2780                    rx.recv()
2781                        .await
2782                        .expect("view dropped with pending condition");
2783                }
2784            })
2785            .await
2786            .expect("condition timed out");
2787            drop(subscriptions);
2788        }
2789    }
2790}
2791
2792impl<T> Clone for ViewHandle<T> {
2793    fn clone(&self) -> Self {
2794        self.ref_counts
2795            .lock()
2796            .inc_view(self.window_id, self.view_id);
2797        Self {
2798            window_id: self.window_id,
2799            view_id: self.view_id,
2800            view_type: PhantomData,
2801            ref_counts: self.ref_counts.clone(),
2802        }
2803    }
2804}
2805
2806impl<T> PartialEq for ViewHandle<T> {
2807    fn eq(&self, other: &Self) -> bool {
2808        self.window_id == other.window_id && self.view_id == other.view_id
2809    }
2810}
2811
2812impl<T> Eq for ViewHandle<T> {}
2813
2814impl<T> Debug for ViewHandle<T> {
2815    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2816        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
2817            .field("window_id", &self.window_id)
2818            .field("view_id", &self.view_id)
2819            .finish()
2820    }
2821}
2822
2823impl<T> Drop for ViewHandle<T> {
2824    fn drop(&mut self) {
2825        self.ref_counts
2826            .lock()
2827            .dec_view(self.window_id, self.view_id);
2828    }
2829}
2830
2831impl<T: View> Handle<T> for ViewHandle<T> {
2832    type Weak = WeakViewHandle<T>;
2833
2834    fn id(&self) -> usize {
2835        self.view_id
2836    }
2837
2838    fn location(&self) -> EntityLocation {
2839        EntityLocation::View(self.window_id, self.view_id)
2840    }
2841
2842    fn downgrade(&self) -> Self::Weak {
2843        self.downgrade()
2844    }
2845
2846    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2847    where
2848        Self: Sized,
2849    {
2850        weak.upgrade(cx)
2851    }
2852}
2853
2854pub struct AnyViewHandle {
2855    window_id: usize,
2856    view_id: usize,
2857    view_type: TypeId,
2858    ref_counts: Arc<Mutex<RefCounts>>,
2859}
2860
2861impl AnyViewHandle {
2862    pub fn id(&self) -> usize {
2863        self.view_id
2864    }
2865
2866    pub fn is<T: 'static>(&self) -> bool {
2867        TypeId::of::<T>() == self.view_type
2868    }
2869
2870    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
2871        if self.is::<T>() {
2872            let result = Some(ViewHandle {
2873                window_id: self.window_id,
2874                view_id: self.view_id,
2875                ref_counts: self.ref_counts.clone(),
2876                view_type: PhantomData,
2877            });
2878            unsafe {
2879                Arc::decrement_strong_count(&self.ref_counts);
2880            }
2881            std::mem::forget(self);
2882            result
2883        } else {
2884            None
2885        }
2886    }
2887}
2888
2889impl Clone for AnyViewHandle {
2890    fn clone(&self) -> Self {
2891        self.ref_counts
2892            .lock()
2893            .inc_view(self.window_id, self.view_id);
2894        Self {
2895            window_id: self.window_id,
2896            view_id: self.view_id,
2897            view_type: self.view_type,
2898            ref_counts: self.ref_counts.clone(),
2899        }
2900    }
2901}
2902
2903impl From<&AnyViewHandle> for AnyViewHandle {
2904    fn from(handle: &AnyViewHandle) -> Self {
2905        handle.clone()
2906    }
2907}
2908
2909impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
2910    fn from(handle: &ViewHandle<T>) -> Self {
2911        handle
2912            .ref_counts
2913            .lock()
2914            .inc_view(handle.window_id, handle.view_id);
2915        AnyViewHandle {
2916            window_id: handle.window_id,
2917            view_id: handle.view_id,
2918            view_type: TypeId::of::<T>(),
2919            ref_counts: handle.ref_counts.clone(),
2920        }
2921    }
2922}
2923
2924impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
2925    fn from(handle: ViewHandle<T>) -> Self {
2926        let any_handle = AnyViewHandle {
2927            window_id: handle.window_id,
2928            view_id: handle.view_id,
2929            view_type: TypeId::of::<T>(),
2930            ref_counts: handle.ref_counts.clone(),
2931        };
2932        unsafe {
2933            Arc::decrement_strong_count(&handle.ref_counts);
2934        }
2935        std::mem::forget(handle);
2936        any_handle
2937    }
2938}
2939
2940impl Drop for AnyViewHandle {
2941    fn drop(&mut self) {
2942        self.ref_counts
2943            .lock()
2944            .dec_view(self.window_id, self.view_id);
2945    }
2946}
2947
2948pub struct AnyModelHandle {
2949    model_id: usize,
2950    ref_counts: Arc<Mutex<RefCounts>>,
2951}
2952
2953impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
2954    fn from(handle: ModelHandle<T>) -> Self {
2955        handle.ref_counts.lock().inc_model(handle.model_id);
2956        Self {
2957            model_id: handle.model_id,
2958            ref_counts: handle.ref_counts.clone(),
2959        }
2960    }
2961}
2962
2963impl Drop for AnyModelHandle {
2964    fn drop(&mut self) {
2965        self.ref_counts.lock().dec_model(self.model_id);
2966    }
2967}
2968pub struct WeakViewHandle<T> {
2969    window_id: usize,
2970    view_id: usize,
2971    view_type: PhantomData<T>,
2972}
2973
2974impl<T: View> WeakViewHandle<T> {
2975    fn new(window_id: usize, view_id: usize) -> Self {
2976        Self {
2977            window_id,
2978            view_id,
2979            view_type: PhantomData,
2980        }
2981    }
2982
2983    pub fn id(&self) -> usize {
2984        self.view_id
2985    }
2986
2987    pub fn upgrade(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
2988        if cx.ref_counts.lock().is_entity_alive(self.view_id) {
2989            Some(ViewHandle::new(
2990                self.window_id,
2991                self.view_id,
2992                &cx.ref_counts,
2993            ))
2994        } else {
2995            None
2996        }
2997    }
2998}
2999
3000impl<T> Clone for WeakViewHandle<T> {
3001    fn clone(&self) -> Self {
3002        Self {
3003            window_id: self.window_id,
3004            view_id: self.view_id,
3005            view_type: PhantomData,
3006        }
3007    }
3008}
3009
3010#[derive(Clone, Copy, PartialEq, Eq, Hash)]
3011pub struct ElementStateId(usize, usize);
3012
3013impl From<usize> for ElementStateId {
3014    fn from(id: usize) -> Self {
3015        Self(id, 0)
3016    }
3017}
3018
3019impl From<(usize, usize)> for ElementStateId {
3020    fn from(id: (usize, usize)) -> Self {
3021        Self(id.0, id.1)
3022    }
3023}
3024
3025pub struct ElementStateHandle<T> {
3026    value_type: PhantomData<T>,
3027    tag_type_id: TypeId,
3028    id: ElementStateId,
3029    ref_counts: Weak<Mutex<RefCounts>>,
3030}
3031
3032impl<T: 'static> ElementStateHandle<T> {
3033    fn new(tag_type_id: TypeId, id: ElementStateId, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3034        ref_counts.lock().inc_element_state(tag_type_id, id);
3035        Self {
3036            value_type: PhantomData,
3037            tag_type_id,
3038            id,
3039            ref_counts: Arc::downgrade(ref_counts),
3040        }
3041    }
3042
3043    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3044        cx.element_states
3045            .get(&(self.tag_type_id, self.id))
3046            .unwrap()
3047            .downcast_ref()
3048            .unwrap()
3049    }
3050
3051    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
3052    where
3053        C: DerefMut<Target = MutableAppContext>,
3054    {
3055        let mut element_state = cx
3056            .deref_mut()
3057            .cx
3058            .element_states
3059            .remove(&(self.tag_type_id, self.id))
3060            .unwrap();
3061        let result = f(element_state.downcast_mut().unwrap(), cx);
3062        cx.deref_mut()
3063            .cx
3064            .element_states
3065            .insert((self.tag_type_id, self.id), element_state);
3066        result
3067    }
3068}
3069
3070impl<T> Drop for ElementStateHandle<T> {
3071    fn drop(&mut self) {
3072        if let Some(ref_counts) = self.ref_counts.upgrade() {
3073            ref_counts
3074                .lock()
3075                .dec_element_state(self.tag_type_id, self.id);
3076        }
3077    }
3078}
3079
3080pub struct CursorStyleHandle {
3081    id: usize,
3082    next_cursor_style_handle_id: Arc<AtomicUsize>,
3083    platform: Arc<dyn Platform>,
3084}
3085
3086impl Drop for CursorStyleHandle {
3087    fn drop(&mut self) {
3088        if self.id + 1 == self.next_cursor_style_handle_id.load(SeqCst) {
3089            self.platform.set_cursor_style(CursorStyle::Arrow);
3090        }
3091    }
3092}
3093
3094#[must_use]
3095pub enum Subscription {
3096    Subscription {
3097        id: usize,
3098        entity_id: usize,
3099        subscriptions: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>>,
3100    },
3101    Observation {
3102        id: usize,
3103        entity_id: usize,
3104        observations: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ObservationCallback>>>>>,
3105    },
3106}
3107
3108impl Subscription {
3109    pub fn detach(&mut self) {
3110        match self {
3111            Subscription::Subscription { subscriptions, .. } => {
3112                subscriptions.take();
3113            }
3114            Subscription::Observation { observations, .. } => {
3115                observations.take();
3116            }
3117        }
3118    }
3119}
3120
3121impl Drop for Subscription {
3122    fn drop(&mut self) {
3123        match self {
3124            Subscription::Observation {
3125                id,
3126                entity_id,
3127                observations,
3128            } => {
3129                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3130                    if let Some(observations) = observations.lock().get_mut(entity_id) {
3131                        observations.remove(id);
3132                    }
3133                }
3134            }
3135            Subscription::Subscription {
3136                id,
3137                entity_id,
3138                subscriptions,
3139            } => {
3140                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
3141                    if let Some(subscriptions) = subscriptions.lock().get_mut(entity_id) {
3142                        subscriptions.remove(id);
3143                    }
3144                }
3145            }
3146        }
3147    }
3148}
3149
3150#[derive(Default)]
3151struct RefCounts {
3152    entity_counts: HashMap<usize, usize>,
3153    element_state_counts: HashMap<(TypeId, ElementStateId), usize>,
3154    dropped_models: HashSet<usize>,
3155    dropped_views: HashSet<(usize, usize)>,
3156    dropped_element_states: HashSet<(TypeId, ElementStateId)>,
3157}
3158
3159impl RefCounts {
3160    fn inc_model(&mut self, model_id: usize) {
3161        match self.entity_counts.entry(model_id) {
3162            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3163            Entry::Vacant(entry) => {
3164                entry.insert(1);
3165                self.dropped_models.remove(&model_id);
3166            }
3167        }
3168    }
3169
3170    fn inc_view(&mut self, window_id: usize, view_id: usize) {
3171        match self.entity_counts.entry(view_id) {
3172            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3173            Entry::Vacant(entry) => {
3174                entry.insert(1);
3175                self.dropped_views.remove(&(window_id, view_id));
3176            }
3177        }
3178    }
3179
3180    fn inc_element_state(&mut self, tag_type_id: TypeId, id: ElementStateId) {
3181        match self.element_state_counts.entry((tag_type_id, id)) {
3182            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3183            Entry::Vacant(entry) => {
3184                entry.insert(1);
3185                self.dropped_element_states.remove(&(tag_type_id, id));
3186            }
3187        }
3188    }
3189
3190    fn dec_model(&mut self, model_id: usize) {
3191        let count = self.entity_counts.get_mut(&model_id).unwrap();
3192        *count -= 1;
3193        if *count == 0 {
3194            self.entity_counts.remove(&model_id);
3195            self.dropped_models.insert(model_id);
3196        }
3197    }
3198
3199    fn dec_view(&mut self, window_id: usize, view_id: usize) {
3200        let count = self.entity_counts.get_mut(&view_id).unwrap();
3201        *count -= 1;
3202        if *count == 0 {
3203            self.entity_counts.remove(&view_id);
3204            self.dropped_views.insert((window_id, view_id));
3205        }
3206    }
3207
3208    fn dec_element_state(&mut self, tag_type_id: TypeId, id: ElementStateId) {
3209        let key = (tag_type_id, id);
3210        let count = self.element_state_counts.get_mut(&key).unwrap();
3211        *count -= 1;
3212        if *count == 0 {
3213            self.element_state_counts.remove(&key);
3214            self.dropped_element_states.insert(key);
3215        }
3216    }
3217
3218    fn is_entity_alive(&self, entity_id: usize) -> bool {
3219        self.entity_counts.contains_key(&entity_id)
3220    }
3221
3222    fn take_dropped(
3223        &mut self,
3224    ) -> (
3225        HashSet<usize>,
3226        HashSet<(usize, usize)>,
3227        HashSet<(TypeId, ElementStateId)>,
3228    ) {
3229        let mut dropped_models = HashSet::new();
3230        let mut dropped_views = HashSet::new();
3231        let mut dropped_element_states = HashSet::new();
3232        std::mem::swap(&mut self.dropped_models, &mut dropped_models);
3233        std::mem::swap(&mut self.dropped_views, &mut dropped_views);
3234        std::mem::swap(
3235            &mut self.dropped_element_states,
3236            &mut dropped_element_states,
3237        );
3238        (dropped_models, dropped_views, dropped_element_states)
3239    }
3240}
3241
3242#[cfg(test)]
3243mod tests {
3244    use super::*;
3245    use crate::elements::*;
3246    use smol::future::poll_once;
3247    use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
3248
3249    #[crate::test(self)]
3250    fn test_model_handles(cx: &mut MutableAppContext) {
3251        struct Model {
3252            other: Option<ModelHandle<Model>>,
3253            events: Vec<String>,
3254        }
3255
3256        impl Entity for Model {
3257            type Event = usize;
3258        }
3259
3260        impl Model {
3261            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
3262                if let Some(other) = other.as_ref() {
3263                    cx.observe(other, |me, _, _| {
3264                        me.events.push("notified".into());
3265                    })
3266                    .detach();
3267                    cx.subscribe(other, |me, _, event, _| {
3268                        me.events.push(format!("observed event {}", event));
3269                    })
3270                    .detach();
3271                }
3272
3273                Self {
3274                    other,
3275                    events: Vec::new(),
3276                }
3277            }
3278        }
3279
3280        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
3281        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
3282        assert_eq!(cx.cx.models.len(), 2);
3283
3284        handle_1.update(cx, |model, cx| {
3285            model.events.push("updated".into());
3286            cx.emit(1);
3287            cx.notify();
3288            cx.emit(2);
3289        });
3290        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3291        assert_eq!(
3292            handle_2.read(cx).events,
3293            vec![
3294                "observed event 1".to_string(),
3295                "notified".to_string(),
3296                "observed event 2".to_string(),
3297            ]
3298        );
3299
3300        handle_2.update(cx, |model, _| {
3301            drop(handle_1);
3302            model.other.take();
3303        });
3304
3305        assert_eq!(cx.cx.models.len(), 1);
3306        assert!(cx.subscriptions.lock().is_empty());
3307        assert!(cx.observations.lock().is_empty());
3308    }
3309
3310    #[crate::test(self)]
3311    fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) {
3312        #[derive(Default)]
3313        struct Model {
3314            events: Vec<usize>,
3315        }
3316
3317        impl Entity for Model {
3318            type Event = usize;
3319        }
3320
3321        let handle_1 = cx.add_model(|_| Model::default());
3322        let handle_2 = cx.add_model(|_| Model::default());
3323        let handle_2b = handle_2.clone();
3324
3325        handle_1.update(cx, |_, c| {
3326            c.subscribe(&handle_2, move |model: &mut Model, _, event, c| {
3327                model.events.push(*event);
3328
3329                c.subscribe(&handle_2b, |model, _, event, _| {
3330                    model.events.push(*event * 2);
3331                })
3332                .detach();
3333            })
3334            .detach();
3335        });
3336
3337        handle_2.update(cx, |_, c| c.emit(7));
3338        assert_eq!(handle_1.read(cx).events, vec![7]);
3339
3340        handle_2.update(cx, |_, c| c.emit(5));
3341        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
3342    }
3343
3344    #[crate::test(self)]
3345    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
3346        #[derive(Default)]
3347        struct Model {
3348            count: usize,
3349            events: Vec<usize>,
3350        }
3351
3352        impl Entity for Model {
3353            type Event = ();
3354        }
3355
3356        let handle_1 = cx.add_model(|_| Model::default());
3357        let handle_2 = cx.add_model(|_| Model::default());
3358        let handle_2b = handle_2.clone();
3359
3360        handle_1.update(cx, |_, c| {
3361            c.observe(&handle_2, move |model, observed, c| {
3362                model.events.push(observed.read(c).count);
3363                c.observe(&handle_2b, |model, observed, c| {
3364                    model.events.push(observed.read(c).count * 2);
3365                })
3366                .detach();
3367            })
3368            .detach();
3369        });
3370
3371        handle_2.update(cx, |model, c| {
3372            model.count = 7;
3373            c.notify()
3374        });
3375        assert_eq!(handle_1.read(cx).events, vec![7]);
3376
3377        handle_2.update(cx, |model, c| {
3378            model.count = 5;
3379            c.notify()
3380        });
3381        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
3382    }
3383
3384    #[crate::test(self)]
3385    fn test_view_handles(cx: &mut MutableAppContext) {
3386        struct View {
3387            other: Option<ViewHandle<View>>,
3388            events: Vec<String>,
3389        }
3390
3391        impl Entity for View {
3392            type Event = usize;
3393        }
3394
3395        impl super::View for View {
3396            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3397                Empty::new().boxed()
3398            }
3399
3400            fn ui_name() -> &'static str {
3401                "View"
3402            }
3403        }
3404
3405        impl View {
3406            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
3407                if let Some(other) = other.as_ref() {
3408                    cx.subscribe(other, |me, _, event, _| {
3409                        me.events.push(format!("observed event {}", event));
3410                    })
3411                    .detach();
3412                }
3413                Self {
3414                    other,
3415                    events: Vec::new(),
3416                }
3417            }
3418        }
3419
3420        let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
3421        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
3422        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
3423        assert_eq!(cx.cx.views.len(), 3);
3424
3425        handle_1.update(cx, |view, cx| {
3426            view.events.push("updated".into());
3427            cx.emit(1);
3428            cx.emit(2);
3429        });
3430        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3431        assert_eq!(
3432            handle_2.read(cx).events,
3433            vec![
3434                "observed event 1".to_string(),
3435                "observed event 2".to_string(),
3436            ]
3437        );
3438
3439        handle_2.update(cx, |view, _| {
3440            drop(handle_1);
3441            view.other.take();
3442        });
3443
3444        assert_eq!(cx.cx.views.len(), 2);
3445        assert!(cx.subscriptions.lock().is_empty());
3446        assert!(cx.observations.lock().is_empty());
3447    }
3448
3449    #[crate::test(self)]
3450    fn test_add_window(cx: &mut MutableAppContext) {
3451        struct View {
3452            mouse_down_count: Arc<AtomicUsize>,
3453        }
3454
3455        impl Entity for View {
3456            type Event = ();
3457        }
3458
3459        impl super::View for View {
3460            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3461                let mouse_down_count = self.mouse_down_count.clone();
3462                EventHandler::new(Empty::new().boxed())
3463                    .on_mouse_down(move |_| {
3464                        mouse_down_count.fetch_add(1, SeqCst);
3465                        true
3466                    })
3467                    .boxed()
3468            }
3469
3470            fn ui_name() -> &'static str {
3471                "View"
3472            }
3473        }
3474
3475        let mouse_down_count = Arc::new(AtomicUsize::new(0));
3476        let (window_id, _) = cx.add_window(Default::default(), |_| View {
3477            mouse_down_count: mouse_down_count.clone(),
3478        });
3479        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
3480        // Ensure window's root element is in a valid lifecycle state.
3481        presenter.borrow_mut().dispatch_event(
3482            Event::LeftMouseDown {
3483                position: Default::default(),
3484                cmd: false,
3485            },
3486            cx,
3487        );
3488        assert_eq!(mouse_down_count.load(SeqCst), 1);
3489    }
3490
3491    #[crate::test(self)]
3492    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
3493        struct Model {
3494            released: Arc<Mutex<bool>>,
3495        }
3496
3497        struct View {
3498            released: Arc<Mutex<bool>>,
3499        }
3500
3501        impl Entity for Model {
3502            type Event = ();
3503
3504            fn release(&mut self, _: &mut MutableAppContext) {
3505                *self.released.lock() = true;
3506            }
3507        }
3508
3509        impl Entity for View {
3510            type Event = ();
3511
3512            fn release(&mut self, _: &mut MutableAppContext) {
3513                *self.released.lock() = true;
3514            }
3515        }
3516
3517        impl super::View for View {
3518            fn ui_name() -> &'static str {
3519                "View"
3520            }
3521
3522            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3523                Empty::new().boxed()
3524            }
3525        }
3526
3527        let model_released = Arc::new(Mutex::new(false));
3528        let view_released = Arc::new(Mutex::new(false));
3529
3530        let model = cx.add_model(|_| Model {
3531            released: model_released.clone(),
3532        });
3533
3534        let (window_id, _) = cx.add_window(Default::default(), |_| View {
3535            released: view_released.clone(),
3536        });
3537
3538        assert!(!*model_released.lock());
3539        assert!(!*view_released.lock());
3540
3541        cx.update(move || {
3542            drop(model);
3543        });
3544        assert!(*model_released.lock());
3545
3546        drop(cx.remove_window(window_id));
3547        assert!(*view_released.lock());
3548    }
3549
3550    #[crate::test(self)]
3551    fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) {
3552        #[derive(Default)]
3553        struct View {
3554            events: Vec<usize>,
3555        }
3556
3557        impl Entity for View {
3558            type Event = usize;
3559        }
3560
3561        impl super::View for View {
3562            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3563                Empty::new().boxed()
3564            }
3565
3566            fn ui_name() -> &'static str {
3567                "View"
3568            }
3569        }
3570
3571        struct Model;
3572
3573        impl Entity for Model {
3574            type Event = usize;
3575        }
3576
3577        let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
3578        let handle_2 = cx.add_view(window_id, |_| View::default());
3579        let handle_2b = handle_2.clone();
3580        let handle_3 = cx.add_model(|_| Model);
3581
3582        handle_1.update(cx, |_, c| {
3583            c.subscribe(&handle_2, move |me, _, event, c| {
3584                me.events.push(*event);
3585
3586                c.subscribe(&handle_2b, |me, _, event, _| {
3587                    me.events.push(*event * 2);
3588                })
3589                .detach();
3590            })
3591            .detach();
3592
3593            c.subscribe(&handle_3, |me, _, event, _| {
3594                me.events.push(*event);
3595            })
3596            .detach();
3597        });
3598
3599        handle_2.update(cx, |_, c| c.emit(7));
3600        assert_eq!(handle_1.read(cx).events, vec![7]);
3601
3602        handle_2.update(cx, |_, c| c.emit(5));
3603        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
3604
3605        handle_3.update(cx, |_, c| c.emit(9));
3606        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
3607    }
3608
3609    #[crate::test(self)]
3610    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
3611        struct View;
3612
3613        impl Entity for View {
3614            type Event = ();
3615        }
3616
3617        impl super::View for View {
3618            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3619                Empty::new().boxed()
3620            }
3621
3622            fn ui_name() -> &'static str {
3623                "View"
3624            }
3625        }
3626
3627        struct Model;
3628
3629        impl Entity for Model {
3630            type Event = ();
3631        }
3632
3633        let (window_id, _) = cx.add_window(Default::default(), |_| View);
3634        let observing_view = cx.add_view(window_id, |_| View);
3635        let emitting_view = cx.add_view(window_id, |_| View);
3636        let observing_model = cx.add_model(|_| Model);
3637        let observed_model = cx.add_model(|_| Model);
3638
3639        observing_view.update(cx, |_, cx| {
3640            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
3641            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
3642        });
3643        observing_model.update(cx, |_, cx| {
3644            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
3645        });
3646
3647        cx.update(|| {
3648            drop(observing_view);
3649            drop(observing_model);
3650        });
3651
3652        emitting_view.update(cx, |_, cx| cx.emit(()));
3653        observed_model.update(cx, |_, cx| cx.emit(()));
3654    }
3655
3656    #[crate::test(self)]
3657    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
3658        #[derive(Default)]
3659        struct View {
3660            events: Vec<usize>,
3661        }
3662
3663        impl Entity for View {
3664            type Event = usize;
3665        }
3666
3667        impl super::View for View {
3668            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3669                Empty::new().boxed()
3670            }
3671
3672            fn ui_name() -> &'static str {
3673                "View"
3674            }
3675        }
3676
3677        #[derive(Default)]
3678        struct Model {
3679            count: usize,
3680        }
3681
3682        impl Entity for Model {
3683            type Event = ();
3684        }
3685
3686        let (_, view) = cx.add_window(Default::default(), |_| View::default());
3687        let model = cx.add_model(|_| Model::default());
3688
3689        view.update(cx, |_, c| {
3690            c.observe(&model, |me, observed, c| {
3691                me.events.push(observed.read(c).count)
3692            })
3693            .detach();
3694        });
3695
3696        model.update(cx, |model, c| {
3697            model.count = 11;
3698            c.notify();
3699        });
3700        assert_eq!(view.read(cx).events, vec![11]);
3701    }
3702
3703    #[crate::test(self)]
3704    fn test_dropping_observers(cx: &mut MutableAppContext) {
3705        struct View;
3706
3707        impl Entity for View {
3708            type Event = ();
3709        }
3710
3711        impl super::View for View {
3712            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3713                Empty::new().boxed()
3714            }
3715
3716            fn ui_name() -> &'static str {
3717                "View"
3718            }
3719        }
3720
3721        struct Model;
3722
3723        impl Entity for Model {
3724            type Event = ();
3725        }
3726
3727        let (window_id, _) = cx.add_window(Default::default(), |_| View);
3728        let observing_view = cx.add_view(window_id, |_| View);
3729        let observing_model = cx.add_model(|_| Model);
3730        let observed_model = cx.add_model(|_| Model);
3731
3732        observing_view.update(cx, |_, cx| {
3733            cx.observe(&observed_model, |_, _, _| {}).detach();
3734        });
3735        observing_model.update(cx, |_, cx| {
3736            cx.observe(&observed_model, |_, _, _| {}).detach();
3737        });
3738
3739        cx.update(|| {
3740            drop(observing_view);
3741            drop(observing_model);
3742        });
3743
3744        observed_model.update(cx, |_, cx| cx.notify());
3745    }
3746
3747    #[crate::test(self)]
3748    fn test_focus(cx: &mut MutableAppContext) {
3749        struct View {
3750            name: String,
3751            events: Arc<Mutex<Vec<String>>>,
3752        }
3753
3754        impl Entity for View {
3755            type Event = ();
3756        }
3757
3758        impl super::View for View {
3759            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3760                Empty::new().boxed()
3761            }
3762
3763            fn ui_name() -> &'static str {
3764                "View"
3765            }
3766
3767            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
3768                self.events.lock().push(format!("{} focused", &self.name));
3769            }
3770
3771            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
3772                self.events.lock().push(format!("{} blurred", &self.name));
3773            }
3774        }
3775
3776        let events: Arc<Mutex<Vec<String>>> = Default::default();
3777        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
3778            events: events.clone(),
3779            name: "view 1".to_string(),
3780        });
3781        let view_2 = cx.add_view(window_id, |_| View {
3782            events: events.clone(),
3783            name: "view 2".to_string(),
3784        });
3785
3786        view_1.update(cx, |_, cx| cx.focus(&view_2));
3787        view_1.update(cx, |_, cx| cx.focus(&view_1));
3788        view_1.update(cx, |_, cx| cx.focus(&view_2));
3789        view_1.update(cx, |_, _| drop(view_2));
3790
3791        assert_eq!(
3792            *events.lock(),
3793            [
3794                "view 1 focused".to_string(),
3795                "view 1 blurred".to_string(),
3796                "view 2 focused".to_string(),
3797                "view 2 blurred".to_string(),
3798                "view 1 focused".to_string(),
3799                "view 1 blurred".to_string(),
3800                "view 2 focused".to_string(),
3801                "view 1 focused".to_string(),
3802            ],
3803        );
3804    }
3805
3806    #[crate::test(self)]
3807    fn test_dispatch_action(cx: &mut MutableAppContext) {
3808        struct ViewA {
3809            id: usize,
3810        }
3811
3812        impl Entity for ViewA {
3813            type Event = ();
3814        }
3815
3816        impl View for ViewA {
3817            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3818                Empty::new().boxed()
3819            }
3820
3821            fn ui_name() -> &'static str {
3822                "View"
3823            }
3824        }
3825
3826        struct ViewB {
3827            id: usize,
3828        }
3829
3830        impl Entity for ViewB {
3831            type Event = ();
3832        }
3833
3834        impl View for ViewB {
3835            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3836                Empty::new().boxed()
3837            }
3838
3839            fn ui_name() -> &'static str {
3840                "View"
3841            }
3842        }
3843
3844        action!(Action, &'static str);
3845
3846        let actions = Rc::new(RefCell::new(Vec::new()));
3847
3848        let actions_clone = actions.clone();
3849        cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
3850            actions_clone.borrow_mut().push("global a".to_string());
3851        });
3852
3853        let actions_clone = actions.clone();
3854        cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
3855            actions_clone.borrow_mut().push("global b".to_string());
3856        });
3857
3858        let actions_clone = actions.clone();
3859        cx.add_action(move |view: &mut ViewA, action: &Action, cx| {
3860            assert_eq!(action.0, "bar");
3861            cx.propagate_action();
3862            actions_clone.borrow_mut().push(format!("{} a", view.id));
3863        });
3864
3865        let actions_clone = actions.clone();
3866        cx.add_action(move |view: &mut ViewA, _: &Action, cx| {
3867            if view.id != 1 {
3868                cx.propagate_action();
3869            }
3870            actions_clone.borrow_mut().push(format!("{} b", view.id));
3871        });
3872
3873        let actions_clone = actions.clone();
3874        cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
3875            cx.propagate_action();
3876            actions_clone.borrow_mut().push(format!("{} c", view.id));
3877        });
3878
3879        let actions_clone = actions.clone();
3880        cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
3881            cx.propagate_action();
3882            actions_clone.borrow_mut().push(format!("{} d", view.id));
3883        });
3884
3885        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
3886        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
3887        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
3888        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
3889
3890        cx.dispatch_action(
3891            window_id,
3892            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
3893            &Action("bar"),
3894        );
3895
3896        assert_eq!(
3897            *actions.borrow(),
3898            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "1 b"]
3899        );
3900
3901        // Remove view_1, which doesn't propagate the action
3902        actions.borrow_mut().clear();
3903        cx.dispatch_action(
3904            window_id,
3905            vec![view_2.id(), view_3.id(), view_4.id()],
3906            &Action("bar"),
3907        );
3908
3909        assert_eq!(
3910            *actions.borrow(),
3911            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "global b", "global a"]
3912        );
3913    }
3914
3915    #[crate::test(self)]
3916    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
3917        use std::cell::Cell;
3918
3919        action!(Action, &'static str);
3920
3921        struct View {
3922            id: usize,
3923            keymap_context: keymap::Context,
3924        }
3925
3926        impl Entity for View {
3927            type Event = ();
3928        }
3929
3930        impl super::View for View {
3931            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3932                Empty::new().boxed()
3933            }
3934
3935            fn ui_name() -> &'static str {
3936                "View"
3937            }
3938
3939            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
3940                self.keymap_context.clone()
3941            }
3942        }
3943
3944        impl View {
3945            fn new(id: usize) -> Self {
3946                View {
3947                    id,
3948                    keymap_context: keymap::Context::default(),
3949                }
3950            }
3951        }
3952
3953        let mut view_1 = View::new(1);
3954        let mut view_2 = View::new(2);
3955        let mut view_3 = View::new(3);
3956        view_1.keymap_context.set.insert("a".into());
3957        view_2.keymap_context.set.insert("b".into());
3958        view_3.keymap_context.set.insert("c".into());
3959
3960        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
3961        let view_2 = cx.add_view(window_id, |_| view_2);
3962        let view_3 = cx.add_view(window_id, |_| view_3);
3963
3964        // This keymap's only binding dispatches an action on view 2 because that view will have
3965        // "a" and "b" in its context, but not "c".
3966        cx.add_bindings(vec![keymap::Binding::new(
3967            "a",
3968            Action("a"),
3969            Some("a && b && !c"),
3970        )]);
3971
3972        let handled_action = Rc::new(Cell::new(false));
3973        let handled_action_clone = handled_action.clone();
3974        cx.add_action(move |view: &mut View, action: &Action, _| {
3975            handled_action_clone.set(true);
3976            assert_eq!(view.id, 2);
3977            assert_eq!(action.0, "a");
3978        });
3979
3980        cx.dispatch_keystroke(
3981            window_id,
3982            vec![view_1.id(), view_2.id(), view_3.id()],
3983            &Keystroke::parse("a").unwrap(),
3984        )
3985        .unwrap();
3986
3987        assert!(handled_action.get());
3988    }
3989
3990    #[crate::test(self)]
3991    async fn test_model_condition(mut cx: TestAppContext) {
3992        struct Counter(usize);
3993
3994        impl super::Entity for Counter {
3995            type Event = ();
3996        }
3997
3998        impl Counter {
3999            fn inc(&mut self, cx: &mut ModelContext<Self>) {
4000                self.0 += 1;
4001                cx.notify();
4002            }
4003        }
4004
4005        let model = cx.add_model(|_| Counter(0));
4006
4007        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
4008        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
4009        smol::pin!(condition1, condition2);
4010
4011        model.update(&mut cx, |model, cx| model.inc(cx));
4012        assert_eq!(poll_once(&mut condition1).await, None);
4013        assert_eq!(poll_once(&mut condition2).await, None);
4014
4015        model.update(&mut cx, |model, cx| model.inc(cx));
4016        assert_eq!(poll_once(&mut condition1).await, Some(()));
4017        assert_eq!(poll_once(&mut condition2).await, None);
4018
4019        model.update(&mut cx, |model, cx| model.inc(cx));
4020        assert_eq!(poll_once(&mut condition2).await, Some(()));
4021
4022        model.update(&mut cx, |_, cx| cx.notify());
4023    }
4024
4025    #[crate::test(self)]
4026    #[should_panic]
4027    async fn test_model_condition_timeout(mut cx: TestAppContext) {
4028        struct Model;
4029
4030        impl super::Entity for Model {
4031            type Event = ();
4032        }
4033
4034        let model = cx.add_model(|_| Model);
4035        model.condition(&cx, |_, _| false).await;
4036    }
4037
4038    #[crate::test(self)]
4039    #[should_panic(expected = "model dropped with pending condition")]
4040    async fn test_model_condition_panic_on_drop(mut cx: TestAppContext) {
4041        struct Model;
4042
4043        impl super::Entity for Model {
4044            type Event = ();
4045        }
4046
4047        let model = cx.add_model(|_| Model);
4048        let condition = model.condition(&cx, |_, _| false);
4049        cx.update(|_| drop(model));
4050        condition.await;
4051    }
4052
4053    #[crate::test(self)]
4054    async fn test_view_condition(mut cx: TestAppContext) {
4055        struct Counter(usize);
4056
4057        impl super::Entity for Counter {
4058            type Event = ();
4059        }
4060
4061        impl super::View for Counter {
4062            fn ui_name() -> &'static str {
4063                "test view"
4064            }
4065
4066            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4067                Empty::new().boxed()
4068            }
4069        }
4070
4071        impl Counter {
4072            fn inc(&mut self, cx: &mut ViewContext<Self>) {
4073                self.0 += 1;
4074                cx.notify();
4075            }
4076        }
4077
4078        let (_, view) = cx.add_window(|_| Counter(0));
4079
4080        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
4081        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
4082        smol::pin!(condition1, condition2);
4083
4084        view.update(&mut cx, |view, cx| view.inc(cx));
4085        assert_eq!(poll_once(&mut condition1).await, None);
4086        assert_eq!(poll_once(&mut condition2).await, None);
4087
4088        view.update(&mut cx, |view, cx| view.inc(cx));
4089        assert_eq!(poll_once(&mut condition1).await, Some(()));
4090        assert_eq!(poll_once(&mut condition2).await, None);
4091
4092        view.update(&mut cx, |view, cx| view.inc(cx));
4093        assert_eq!(poll_once(&mut condition2).await, Some(()));
4094        view.update(&mut cx, |_, cx| cx.notify());
4095    }
4096
4097    #[crate::test(self)]
4098    #[should_panic]
4099    async fn test_view_condition_timeout(mut cx: TestAppContext) {
4100        struct View;
4101
4102        impl super::Entity for View {
4103            type Event = ();
4104        }
4105
4106        impl super::View for View {
4107            fn ui_name() -> &'static str {
4108                "test view"
4109            }
4110
4111            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4112                Empty::new().boxed()
4113            }
4114        }
4115
4116        let (_, view) = cx.add_window(|_| View);
4117        view.condition(&cx, |_, _| false).await;
4118    }
4119
4120    #[crate::test(self)]
4121    #[should_panic(expected = "view dropped with pending condition")]
4122    async fn test_view_condition_panic_on_drop(mut cx: TestAppContext) {
4123        struct View;
4124
4125        impl super::Entity for View {
4126            type Event = ();
4127        }
4128
4129        impl super::View for View {
4130            fn ui_name() -> &'static str {
4131                "test view"
4132            }
4133
4134            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4135                Empty::new().boxed()
4136            }
4137        }
4138
4139        let window_id = cx.add_window(|_| View).0;
4140        let view = cx.add_view(window_id, |_| View);
4141
4142        let condition = view.condition(&cx, |_, _| false);
4143        cx.update(|_| drop(view));
4144        condition.await;
4145    }
4146}