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