app.rs

   1pub mod action;
   2mod callback_collection;
   3mod menu;
   4pub(crate) mod ref_counts;
   5#[cfg(any(test, feature = "test-support"))]
   6pub mod test_app_context;
   7mod window_input_handler;
   8
   9use std::{
  10    any::{type_name, Any, TypeId},
  11    cell::RefCell,
  12    fmt::{self, Debug},
  13    hash::{Hash, Hasher},
  14    marker::PhantomData,
  15    mem,
  16    ops::{Deref, DerefMut, Range},
  17    path::{Path, PathBuf},
  18    pin::Pin,
  19    rc::{self, Rc},
  20    sync::{Arc, Weak},
  21    time::Duration,
  22};
  23
  24use anyhow::{anyhow, Context, Result};
  25use parking_lot::Mutex;
  26use pathfinder_geometry::vector::Vector2F;
  27use postage::oneshot;
  28use smallvec::SmallVec;
  29use smol::prelude::*;
  30use uuid::Uuid;
  31
  32pub use action::*;
  33use callback_collection::CallbackCollection;
  34use collections::{hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque};
  35pub use menu::*;
  36use platform::Event;
  37#[cfg(any(test, feature = "test-support"))]
  38use ref_counts::LeakDetector;
  39#[cfg(any(test, feature = "test-support"))]
  40pub use test_app_context::{ContextHandle, TestAppContext};
  41use window_input_handler::WindowInputHandler;
  42
  43use crate::{
  44    elements::ElementBox,
  45    executor::{self, Task},
  46    keymap_matcher::{self, Binding, KeymapContext, KeymapMatcher, Keystroke, MatchResult},
  47    platform::{self, KeyDownEvent, Platform, PromptLevel, WindowOptions},
  48    presenter::Presenter,
  49    util::post_inc,
  50    Appearance, AssetCache, AssetSource, ClipboardItem, FontCache, KeyUpEvent,
  51    ModifiersChangedEvent, MouseButton, MouseRegionId, PathPromptOptions, TextLayoutCache,
  52    WindowBounds,
  53};
  54
  55use self::ref_counts::RefCounts;
  56
  57pub trait Entity: 'static {
  58    type Event;
  59
  60    fn release(&mut self, _: &mut MutableAppContext) {}
  61    fn app_will_quit(
  62        &mut self,
  63        _: &mut MutableAppContext,
  64    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
  65        None
  66    }
  67}
  68
  69pub trait View: Entity + Sized {
  70    fn ui_name() -> &'static str;
  71    fn render(&mut self, cx: &mut RenderContext<'_, Self>) -> ElementBox;
  72    fn focus_in(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {}
  73    fn focus_out(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {}
  74    fn key_down(&mut self, _: &KeyDownEvent, _: &mut ViewContext<Self>) -> bool {
  75        false
  76    }
  77    fn key_up(&mut self, _: &KeyUpEvent, _: &mut ViewContext<Self>) -> bool {
  78        false
  79    }
  80    fn modifiers_changed(&mut self, _: &ModifiersChangedEvent, _: &mut ViewContext<Self>) -> bool {
  81        false
  82    }
  83
  84    fn keymap_context(&self, _: &AppContext) -> keymap_matcher::KeymapContext {
  85        Self::default_keymap_context()
  86    }
  87    fn default_keymap_context() -> keymap_matcher::KeymapContext {
  88        let mut cx = keymap_matcher::KeymapContext::default();
  89        cx.add_identifier(Self::ui_name());
  90        cx
  91    }
  92    fn debug_json(&self, _: &AppContext) -> serde_json::Value {
  93        serde_json::Value::Null
  94    }
  95
  96    fn text_for_range(&self, _: Range<usize>, _: &AppContext) -> Option<String> {
  97        None
  98    }
  99    fn selected_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
 100        None
 101    }
 102    fn marked_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
 103        None
 104    }
 105    fn unmark_text(&mut self, _: &mut ViewContext<Self>) {}
 106    fn replace_text_in_range(
 107        &mut self,
 108        _: Option<Range<usize>>,
 109        _: &str,
 110        _: &mut ViewContext<Self>,
 111    ) {
 112    }
 113    fn replace_and_mark_text_in_range(
 114        &mut self,
 115        _: Option<Range<usize>>,
 116        _: &str,
 117        _: Option<Range<usize>>,
 118        _: &mut ViewContext<Self>,
 119    ) {
 120    }
 121}
 122
 123pub trait ReadModel {
 124    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T;
 125}
 126
 127pub trait ReadModelWith {
 128    fn read_model_with<E: Entity, T>(
 129        &self,
 130        handle: &ModelHandle<E>,
 131        read: &mut dyn FnMut(&E, &AppContext) -> T,
 132    ) -> T;
 133}
 134
 135pub trait UpdateModel {
 136    fn update_model<T: Entity, O>(
 137        &mut self,
 138        handle: &ModelHandle<T>,
 139        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
 140    ) -> O;
 141}
 142
 143pub trait UpgradeModelHandle {
 144    fn upgrade_model_handle<T: Entity>(
 145        &self,
 146        handle: &WeakModelHandle<T>,
 147    ) -> Option<ModelHandle<T>>;
 148
 149    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool;
 150
 151    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle>;
 152}
 153
 154pub trait UpgradeViewHandle {
 155    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>>;
 156
 157    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle>;
 158}
 159
 160pub trait ReadView {
 161    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T;
 162}
 163
 164pub trait ReadViewWith {
 165    fn read_view_with<V, T>(
 166        &self,
 167        handle: &ViewHandle<V>,
 168        read: &mut dyn FnMut(&V, &AppContext) -> T,
 169    ) -> T
 170    where
 171        V: View;
 172}
 173
 174pub trait UpdateView {
 175    fn update_view<T, S>(
 176        &mut self,
 177        handle: &ViewHandle<T>,
 178        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 179    ) -> S
 180    where
 181        T: View;
 182}
 183
 184#[derive(Clone)]
 185pub struct App(Rc<RefCell<MutableAppContext>>);
 186
 187#[derive(Clone)]
 188pub struct AsyncAppContext(Rc<RefCell<MutableAppContext>>);
 189
 190impl App {
 191    pub fn new(asset_source: impl AssetSource) -> Result<Self> {
 192        let platform = platform::current::platform();
 193        let foreground = Rc::new(executor::Foreground::platform(platform.dispatcher())?);
 194        let foreground_platform = platform::current::foreground_platform(foreground.clone());
 195        let app = Self(Rc::new(RefCell::new(MutableAppContext::new(
 196            foreground,
 197            Arc::new(executor::Background::new()),
 198            platform.clone(),
 199            foreground_platform.clone(),
 200            Arc::new(FontCache::new(platform.fonts())),
 201            Default::default(),
 202            asset_source,
 203        ))));
 204
 205        foreground_platform.on_quit(Box::new({
 206            let cx = app.0.clone();
 207            move || {
 208                cx.borrow_mut().quit();
 209            }
 210        }));
 211        setup_menu_handlers(foreground_platform.as_ref(), &app);
 212
 213        app.0.borrow_mut().weak_self = Some(Rc::downgrade(&app.0));
 214        Ok(app)
 215    }
 216
 217    pub fn background(&self) -> Arc<executor::Background> {
 218        self.0.borrow().background().clone()
 219    }
 220
 221    pub fn on_become_active<F>(self, mut callback: F) -> Self
 222    where
 223        F: 'static + FnMut(&mut MutableAppContext),
 224    {
 225        let cx = self.0.clone();
 226        self.0
 227            .borrow_mut()
 228            .foreground_platform
 229            .on_become_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 230        self
 231    }
 232
 233    pub fn on_resign_active<F>(self, mut callback: F) -> Self
 234    where
 235        F: 'static + FnMut(&mut MutableAppContext),
 236    {
 237        let cx = self.0.clone();
 238        self.0
 239            .borrow_mut()
 240            .foreground_platform
 241            .on_resign_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 242        self
 243    }
 244
 245    pub fn on_quit<F>(&mut self, mut callback: F) -> &mut Self
 246    where
 247        F: 'static + FnMut(&mut MutableAppContext),
 248    {
 249        let cx = self.0.clone();
 250        self.0
 251            .borrow_mut()
 252            .foreground_platform
 253            .on_quit(Box::new(move || callback(&mut *cx.borrow_mut())));
 254        self
 255    }
 256
 257    pub fn on_event<F>(&mut self, mut callback: F) -> &mut Self
 258    where
 259        F: 'static + FnMut(Event, &mut MutableAppContext) -> bool,
 260    {
 261        let cx = self.0.clone();
 262        self.0
 263            .borrow_mut()
 264            .foreground_platform
 265            .on_event(Box::new(move |event| {
 266                callback(event, &mut *cx.borrow_mut())
 267            }));
 268        self
 269    }
 270
 271    pub fn on_open_urls<F>(&mut self, mut callback: F) -> &mut Self
 272    where
 273        F: 'static + FnMut(Vec<String>, &mut MutableAppContext),
 274    {
 275        let cx = self.0.clone();
 276        self.0
 277            .borrow_mut()
 278            .foreground_platform
 279            .on_open_urls(Box::new(move |paths| {
 280                callback(paths, &mut *cx.borrow_mut())
 281            }));
 282        self
 283    }
 284
 285    pub fn run<F>(self, on_finish_launching: F)
 286    where
 287        F: 'static + FnOnce(&mut MutableAppContext),
 288    {
 289        let platform = self.0.borrow().foreground_platform.clone();
 290        platform.run(Box::new(move || {
 291            let mut cx = self.0.borrow_mut();
 292            let cx = &mut *cx;
 293            crate::views::init(cx);
 294            on_finish_launching(cx);
 295        }))
 296    }
 297
 298    pub fn platform(&self) -> Arc<dyn Platform> {
 299        self.0.borrow().platform()
 300    }
 301
 302    pub fn font_cache(&self) -> Arc<FontCache> {
 303        self.0.borrow().cx.font_cache.clone()
 304    }
 305
 306    fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 307        let mut state = self.0.borrow_mut();
 308        let result = state.update(callback);
 309        state.pending_notifications.clear();
 310        result
 311    }
 312}
 313
 314impl AsyncAppContext {
 315    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
 316    where
 317        F: FnOnce(AsyncAppContext) -> Fut,
 318        Fut: 'static + Future<Output = T>,
 319        T: 'static,
 320    {
 321        self.0.borrow().foreground.spawn(f(self.clone()))
 322    }
 323
 324    pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
 325        callback(self.0.borrow().as_ref())
 326    }
 327
 328    pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 329        self.0.borrow_mut().update(callback)
 330    }
 331
 332    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 333    where
 334        T: Entity,
 335        F: FnOnce(&mut ModelContext<T>) -> T,
 336    {
 337        self.update(|cx| cx.add_model(build_model))
 338    }
 339
 340    pub fn add_window<T, F>(
 341        &mut self,
 342        window_options: WindowOptions,
 343        build_root_view: F,
 344    ) -> (usize, ViewHandle<T>)
 345    where
 346        T: View,
 347        F: FnOnce(&mut ViewContext<T>) -> T,
 348    {
 349        self.update(|cx| cx.add_window(window_options, build_root_view))
 350    }
 351
 352    pub fn remove_window(&mut self, window_id: usize) {
 353        self.update(|cx| cx.remove_window(window_id))
 354    }
 355
 356    pub fn activate_window(&mut self, window_id: usize) {
 357        self.update(|cx| cx.activate_window(window_id))
 358    }
 359
 360    pub fn prompt(
 361        &mut self,
 362        window_id: usize,
 363        level: PromptLevel,
 364        msg: &str,
 365        answers: &[&str],
 366    ) -> oneshot::Receiver<usize> {
 367        self.update(|cx| cx.prompt(window_id, level, msg, answers))
 368    }
 369
 370    pub fn platform(&self) -> Arc<dyn Platform> {
 371        self.0.borrow().platform()
 372    }
 373
 374    pub fn foreground(&self) -> Rc<executor::Foreground> {
 375        self.0.borrow().foreground.clone()
 376    }
 377
 378    pub fn background(&self) -> Arc<executor::Background> {
 379        self.0.borrow().cx.background.clone()
 380    }
 381}
 382
 383impl UpdateModel for AsyncAppContext {
 384    fn update_model<E: Entity, O>(
 385        &mut self,
 386        handle: &ModelHandle<E>,
 387        update: &mut dyn FnMut(&mut E, &mut ModelContext<E>) -> O,
 388    ) -> O {
 389        self.0.borrow_mut().update_model(handle, update)
 390    }
 391}
 392
 393impl UpgradeModelHandle for AsyncAppContext {
 394    fn upgrade_model_handle<T: Entity>(
 395        &self,
 396        handle: &WeakModelHandle<T>,
 397    ) -> Option<ModelHandle<T>> {
 398        self.0.borrow().upgrade_model_handle(handle)
 399    }
 400
 401    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
 402        self.0.borrow().model_handle_is_upgradable(handle)
 403    }
 404
 405    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
 406        self.0.borrow().upgrade_any_model_handle(handle)
 407    }
 408}
 409
 410impl UpgradeViewHandle for AsyncAppContext {
 411    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
 412        self.0.borrow_mut().upgrade_view_handle(handle)
 413    }
 414
 415    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
 416        self.0.borrow_mut().upgrade_any_view_handle(handle)
 417    }
 418}
 419
 420impl ReadModelWith for AsyncAppContext {
 421    fn read_model_with<E: Entity, T>(
 422        &self,
 423        handle: &ModelHandle<E>,
 424        read: &mut dyn FnMut(&E, &AppContext) -> T,
 425    ) -> T {
 426        let cx = self.0.borrow();
 427        let cx = cx.as_ref();
 428        read(handle.read(cx), cx)
 429    }
 430}
 431
 432impl UpdateView for AsyncAppContext {
 433    fn update_view<T, S>(
 434        &mut self,
 435        handle: &ViewHandle<T>,
 436        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 437    ) -> S
 438    where
 439        T: View,
 440    {
 441        self.0.borrow_mut().update_view(handle, update)
 442    }
 443}
 444
 445impl ReadViewWith for AsyncAppContext {
 446    fn read_view_with<V, T>(
 447        &self,
 448        handle: &ViewHandle<V>,
 449        read: &mut dyn FnMut(&V, &AppContext) -> T,
 450    ) -> T
 451    where
 452        V: View,
 453    {
 454        let cx = self.0.borrow();
 455        let cx = cx.as_ref();
 456        read(handle.read(cx), cx)
 457    }
 458}
 459
 460type ActionCallback =
 461    dyn FnMut(&mut dyn AnyView, &dyn Action, &mut MutableAppContext, usize, usize);
 462type GlobalActionCallback = dyn FnMut(&dyn Action, &mut MutableAppContext);
 463
 464type SubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut MutableAppContext) -> bool>;
 465type GlobalSubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut MutableAppContext)>;
 466type ObservationCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>;
 467type GlobalObservationCallback = Box<dyn FnMut(&mut MutableAppContext)>;
 468type FocusObservationCallback = Box<dyn FnMut(bool, &mut MutableAppContext) -> bool>;
 469type ReleaseObservationCallback = Box<dyn FnMut(&dyn Any, &mut MutableAppContext)>;
 470type ActionObservationCallback = Box<dyn FnMut(TypeId, &mut MutableAppContext)>;
 471type WindowActivationCallback = Box<dyn FnMut(bool, &mut MutableAppContext) -> bool>;
 472type WindowFullscreenCallback = Box<dyn FnMut(bool, &mut MutableAppContext) -> bool>;
 473type WindowBoundsCallback = Box<dyn FnMut(WindowBounds, Uuid, &mut MutableAppContext) -> bool>;
 474type KeystrokeCallback = Box<
 475    dyn FnMut(&Keystroke, &MatchResult, Option<&Box<dyn Action>>, &mut MutableAppContext) -> bool,
 476>;
 477type ActiveLabeledTasksCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>;
 478type DeserializeActionCallback = fn(json: &str) -> anyhow::Result<Box<dyn Action>>;
 479type WindowShouldCloseSubscriptionCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>;
 480
 481pub struct MutableAppContext {
 482    weak_self: Option<rc::Weak<RefCell<Self>>>,
 483    foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 484    assets: Arc<AssetCache>,
 485    cx: AppContext,
 486    action_deserializers: HashMap<&'static str, (TypeId, DeserializeActionCallback)>,
 487    capture_actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 488    // Entity Types -> { Action Types -> Action Handlers }
 489    actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 490    // Action Types -> Action Handlers
 491    global_actions: HashMap<TypeId, Box<GlobalActionCallback>>,
 492    keystroke_matcher: KeymapMatcher,
 493    next_entity_id: usize,
 494    next_window_id: usize,
 495    next_subscription_id: usize,
 496    frame_count: usize,
 497
 498    subscriptions: CallbackCollection<usize, SubscriptionCallback>,
 499    global_subscriptions: CallbackCollection<TypeId, GlobalSubscriptionCallback>,
 500    observations: CallbackCollection<usize, ObservationCallback>,
 501    global_observations: CallbackCollection<TypeId, GlobalObservationCallback>,
 502    focus_observations: CallbackCollection<usize, FocusObservationCallback>,
 503    release_observations: CallbackCollection<usize, ReleaseObservationCallback>,
 504    action_dispatch_observations: CallbackCollection<(), ActionObservationCallback>,
 505    window_activation_observations: CallbackCollection<usize, WindowActivationCallback>,
 506    window_fullscreen_observations: CallbackCollection<usize, WindowFullscreenCallback>,
 507    window_bounds_observations: CallbackCollection<usize, WindowBoundsCallback>,
 508    keystroke_observations: CallbackCollection<usize, KeystrokeCallback>,
 509    active_labeled_task_observations: CallbackCollection<(), ActiveLabeledTasksCallback>,
 510
 511    #[allow(clippy::type_complexity)]
 512    presenters_and_platform_windows:
 513        HashMap<usize, (Rc<RefCell<Presenter>>, Box<dyn platform::Window>)>,
 514    foreground: Rc<executor::Foreground>,
 515    pending_effects: VecDeque<Effect>,
 516    pending_notifications: HashSet<usize>,
 517    pending_global_notifications: HashSet<TypeId>,
 518    pending_flushes: usize,
 519    flushing_effects: bool,
 520    halt_action_dispatch: bool,
 521    next_labeled_task_id: usize,
 522    active_labeled_tasks: BTreeMap<usize, &'static str>,
 523}
 524
 525impl MutableAppContext {
 526    fn new(
 527        foreground: Rc<executor::Foreground>,
 528        background: Arc<executor::Background>,
 529        platform: Arc<dyn platform::Platform>,
 530        foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 531        font_cache: Arc<FontCache>,
 532        ref_counts: RefCounts,
 533        asset_source: impl AssetSource,
 534    ) -> Self {
 535        Self {
 536            weak_self: None,
 537            foreground_platform,
 538            assets: Arc::new(AssetCache::new(asset_source)),
 539            cx: AppContext {
 540                models: Default::default(),
 541                views: Default::default(),
 542                parents: Default::default(),
 543                windows: Default::default(),
 544                globals: Default::default(),
 545                element_states: Default::default(),
 546                ref_counts: Arc::new(Mutex::new(ref_counts)),
 547                background,
 548                font_cache,
 549                platform,
 550            },
 551            action_deserializers: Default::default(),
 552            capture_actions: Default::default(),
 553            actions: Default::default(),
 554            global_actions: Default::default(),
 555            keystroke_matcher: KeymapMatcher::default(),
 556            next_entity_id: 0,
 557            next_window_id: 0,
 558            next_subscription_id: 0,
 559            frame_count: 0,
 560            subscriptions: Default::default(),
 561            global_subscriptions: Default::default(),
 562            observations: Default::default(),
 563            focus_observations: Default::default(),
 564            release_observations: Default::default(),
 565            global_observations: Default::default(),
 566            window_activation_observations: Default::default(),
 567            window_fullscreen_observations: Default::default(),
 568            window_bounds_observations: Default::default(),
 569            keystroke_observations: Default::default(),
 570            action_dispatch_observations: Default::default(),
 571            active_labeled_task_observations: Default::default(),
 572            presenters_and_platform_windows: Default::default(),
 573            foreground,
 574            pending_effects: VecDeque::new(),
 575            pending_notifications: Default::default(),
 576            pending_global_notifications: Default::default(),
 577            pending_flushes: 0,
 578            flushing_effects: false,
 579            halt_action_dispatch: false,
 580            next_labeled_task_id: 0,
 581            active_labeled_tasks: Default::default(),
 582        }
 583    }
 584
 585    pub fn upgrade(&self) -> App {
 586        App(self.weak_self.as_ref().unwrap().upgrade().unwrap())
 587    }
 588
 589    pub fn quit(&mut self) {
 590        let mut futures = Vec::new();
 591
 592        self.update(|cx| {
 593            for model_id in cx.models.keys().copied().collect::<Vec<_>>() {
 594                let mut model = cx.cx.models.remove(&model_id).unwrap();
 595                futures.extend(model.app_will_quit(cx));
 596                cx.cx.models.insert(model_id, model);
 597            }
 598
 599            for view_id in cx.views.keys().copied().collect::<Vec<_>>() {
 600                let mut view = cx.cx.views.remove(&view_id).unwrap();
 601                futures.extend(view.app_will_quit(cx));
 602                cx.cx.views.insert(view_id, view);
 603            }
 604        });
 605
 606        self.remove_all_windows();
 607
 608        let futures = futures::future::join_all(futures);
 609        if self
 610            .background
 611            .block_with_timeout(Duration::from_millis(100), futures)
 612            .is_err()
 613        {
 614            log::error!("timed out waiting on app_will_quit");
 615        }
 616    }
 617
 618    pub fn remove_all_windows(&mut self) {
 619        for (window_id, _) in self.cx.windows.drain() {
 620            self.presenters_and_platform_windows.remove(&window_id);
 621        }
 622        self.flush_effects();
 623    }
 624
 625    pub fn platform(&self) -> Arc<dyn platform::Platform> {
 626        self.cx.platform.clone()
 627    }
 628
 629    pub fn font_cache(&self) -> &Arc<FontCache> {
 630        &self.cx.font_cache
 631    }
 632
 633    pub fn foreground(&self) -> &Rc<executor::Foreground> {
 634        &self.foreground
 635    }
 636
 637    pub fn background(&self) -> &Arc<executor::Background> {
 638        &self.cx.background
 639    }
 640
 641    pub fn debug_elements(&self, window_id: usize) -> Option<crate::json::Value> {
 642        self.presenters_and_platform_windows
 643            .get(&window_id)
 644            .and_then(|(presenter, _)| presenter.borrow().debug_elements(self))
 645    }
 646
 647    pub fn deserialize_action(
 648        &self,
 649        name: &str,
 650        argument: Option<&str>,
 651    ) -> Result<Box<dyn Action>> {
 652        let callback = self
 653            .action_deserializers
 654            .get(name)
 655            .ok_or_else(|| anyhow!("unknown action {}", name))?
 656            .1;
 657        callback(argument.unwrap_or("{}"))
 658            .with_context(|| format!("invalid data for action {}", name))
 659    }
 660
 661    pub fn add_action<A, V, F, R>(&mut self, handler: F)
 662    where
 663        A: Action,
 664        V: View,
 665        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> R,
 666    {
 667        self.add_action_internal(handler, false)
 668    }
 669
 670    pub fn capture_action<A, V, F>(&mut self, handler: F)
 671    where
 672        A: Action,
 673        V: View,
 674        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
 675    {
 676        self.add_action_internal(handler, true)
 677    }
 678
 679    fn add_action_internal<A, V, F, R>(&mut self, mut handler: F, capture: bool)
 680    where
 681        A: Action,
 682        V: View,
 683        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> R,
 684    {
 685        let handler = Box::new(
 686            move |view: &mut dyn AnyView,
 687                  action: &dyn Action,
 688                  cx: &mut MutableAppContext,
 689                  window_id: usize,
 690                  view_id: usize| {
 691                let action = action.as_any().downcast_ref().unwrap();
 692                let mut cx = ViewContext::new(cx, window_id, view_id);
 693                handler(
 694                    view.as_any_mut()
 695                        .downcast_mut()
 696                        .expect("downcast is type safe"),
 697                    action,
 698                    &mut cx,
 699                );
 700            },
 701        );
 702
 703        self.action_deserializers
 704            .entry(A::qualified_name())
 705            .or_insert((TypeId::of::<A>(), A::from_json_str));
 706
 707        let actions = if capture {
 708            &mut self.capture_actions
 709        } else {
 710            &mut self.actions
 711        };
 712
 713        actions
 714            .entry(TypeId::of::<V>())
 715            .or_default()
 716            .entry(TypeId::of::<A>())
 717            .or_default()
 718            .push(handler);
 719    }
 720
 721    pub fn add_async_action<A, V, F>(&mut self, mut handler: F)
 722    where
 723        A: Action,
 724        V: View,
 725        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> Option<Task<Result<()>>>,
 726    {
 727        self.add_action(move |view, action, cx| {
 728            if let Some(task) = handler(view, action, cx) {
 729                task.detach_and_log_err(cx);
 730            }
 731        })
 732    }
 733
 734    pub fn add_global_action<A, F>(&mut self, mut handler: F)
 735    where
 736        A: Action,
 737        F: 'static + FnMut(&A, &mut MutableAppContext),
 738    {
 739        let handler = Box::new(move |action: &dyn Action, cx: &mut MutableAppContext| {
 740            let action = action.as_any().downcast_ref().unwrap();
 741            handler(action, cx);
 742        });
 743
 744        self.action_deserializers
 745            .entry(A::qualified_name())
 746            .or_insert((TypeId::of::<A>(), A::from_json_str));
 747
 748        if self
 749            .global_actions
 750            .insert(TypeId::of::<A>(), handler)
 751            .is_some()
 752        {
 753            panic!(
 754                "registered multiple global handlers for {}",
 755                type_name::<A>()
 756            );
 757        }
 758    }
 759
 760    pub fn is_topmost_window_for_position(&self, window_id: usize, position: Vector2F) -> bool {
 761        self.presenters_and_platform_windows
 762            .get(&window_id)
 763            .map_or(false, |(_, window)| {
 764                window.is_topmost_for_position(position)
 765            })
 766    }
 767
 768    pub fn has_window(&self, window_id: usize) -> bool {
 769        self.window_ids()
 770            .find(|window| window == &window_id)
 771            .is_some()
 772    }
 773
 774    pub fn window_ids(&self) -> impl Iterator<Item = usize> + '_ {
 775        self.cx.windows.keys().copied()
 776    }
 777
 778    pub fn activate_window(&self, window_id: usize) {
 779        if let Some((_, window)) = self.presenters_and_platform_windows.get(&window_id) {
 780            window.activate()
 781        }
 782    }
 783
 784    pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
 785        self.cx
 786            .windows
 787            .get(&window_id)
 788            .and_then(|window| window.root_view.clone().downcast::<T>())
 789    }
 790
 791    pub fn window_is_active(&self, window_id: usize) -> bool {
 792        self.cx
 793            .windows
 794            .get(&window_id)
 795            .map_or(false, |window| window.is_active)
 796    }
 797
 798    pub fn window_is_fullscreen(&self, window_id: usize) -> bool {
 799        self.cx
 800            .windows
 801            .get(&window_id)
 802            .map_or(false, |window| window.is_fullscreen)
 803    }
 804
 805    pub fn window_bounds(&self, window_id: usize) -> Option<WindowBounds> {
 806        let (_, window) = self.presenters_and_platform_windows.get(&window_id)?;
 807        Some(window.bounds())
 808    }
 809
 810    pub fn window_display_uuid(&self, window_id: usize) -> Option<Uuid> {
 811        let (_, window) = self.presenters_and_platform_windows.get(&window_id)?;
 812        window.screen().display_uuid()
 813    }
 814
 815    pub fn active_labeled_tasks<'a>(
 816        &'a self,
 817    ) -> impl DoubleEndedIterator<Item = &'static str> + 'a {
 818        self.active_labeled_tasks.values().cloned()
 819    }
 820
 821    pub fn render_view(&mut self, params: RenderParams) -> Result<ElementBox> {
 822        let window_id = params.window_id;
 823        let view_id = params.view_id;
 824        let mut view = self
 825            .cx
 826            .views
 827            .remove(&(window_id, view_id))
 828            .ok_or_else(|| anyhow!("view not found"))?;
 829        let element = view.render(params, self);
 830        self.cx.views.insert((window_id, view_id), view);
 831        Ok(element)
 832    }
 833
 834    pub fn render_views(
 835        &mut self,
 836        window_id: usize,
 837        titlebar_height: f32,
 838        appearance: Appearance,
 839    ) -> HashMap<usize, ElementBox> {
 840        self.start_frame();
 841        #[allow(clippy::needless_collect)]
 842        let view_ids = self
 843            .views
 844            .keys()
 845            .filter_map(|(win_id, view_id)| {
 846                if *win_id == window_id {
 847                    Some(*view_id)
 848                } else {
 849                    None
 850                }
 851            })
 852            .collect::<Vec<_>>();
 853
 854        view_ids
 855            .into_iter()
 856            .map(|view_id| {
 857                (
 858                    view_id,
 859                    self.render_view(RenderParams {
 860                        window_id,
 861                        view_id,
 862                        titlebar_height,
 863                        hovered_region_ids: Default::default(),
 864                        clicked_region_ids: None,
 865                        refreshing: false,
 866                        appearance,
 867                    })
 868                    .unwrap(),
 869                )
 870            })
 871            .collect()
 872    }
 873
 874    pub(crate) fn start_frame(&mut self) {
 875        self.frame_count += 1;
 876    }
 877
 878    pub fn update<T, F: FnOnce(&mut Self) -> T>(&mut self, callback: F) -> T {
 879        self.pending_flushes += 1;
 880        let result = callback(self);
 881        self.flush_effects();
 882        result
 883    }
 884
 885    fn show_character_palette(&self, window_id: usize) {
 886        let (_, window) = &self.presenters_and_platform_windows[&window_id];
 887        window.show_character_palette();
 888    }
 889
 890    pub fn minimize_window(&self, window_id: usize) {
 891        let (_, window) = &self.presenters_and_platform_windows[&window_id];
 892        window.minimize();
 893    }
 894
 895    pub fn zoom_window(&self, window_id: usize) {
 896        let (_, window) = &self.presenters_and_platform_windows[&window_id];
 897        window.zoom();
 898    }
 899
 900    pub fn toggle_window_full_screen(&self, window_id: usize) {
 901        let (_, window) = &self.presenters_and_platform_windows[&window_id];
 902        window.toggle_full_screen();
 903    }
 904
 905    pub fn prompt(
 906        &self,
 907        window_id: usize,
 908        level: PromptLevel,
 909        msg: &str,
 910        answers: &[&str],
 911    ) -> oneshot::Receiver<usize> {
 912        let (_, window) = &self.presenters_and_platform_windows[&window_id];
 913        window.prompt(level, msg, answers)
 914    }
 915
 916    pub fn prompt_for_paths(
 917        &self,
 918        options: PathPromptOptions,
 919    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 920        self.foreground_platform.prompt_for_paths(options)
 921    }
 922
 923    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
 924        self.foreground_platform.prompt_for_new_path(directory)
 925    }
 926
 927    pub fn reveal_path(&self, path: &Path) {
 928        self.foreground_platform.reveal_path(path)
 929    }
 930
 931    pub fn emit_global<E: Any>(&mut self, payload: E) {
 932        self.pending_effects.push_back(Effect::GlobalEvent {
 933            payload: Box::new(payload),
 934        });
 935    }
 936
 937    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 938    where
 939        E: Entity,
 940        E::Event: 'static,
 941        H: Handle<E>,
 942        F: 'static + FnMut(H, &E::Event, &mut Self),
 943    {
 944        self.subscribe_internal(handle, move |handle, event, cx| {
 945            callback(handle, event, cx);
 946            true
 947        })
 948    }
 949
 950    pub fn subscribe_global<E, F>(&mut self, mut callback: F) -> Subscription
 951    where
 952        E: Any,
 953        F: 'static + FnMut(&E, &mut Self),
 954    {
 955        let subscription_id = post_inc(&mut self.next_subscription_id);
 956        let type_id = TypeId::of::<E>();
 957        self.pending_effects.push_back(Effect::GlobalSubscription {
 958            type_id,
 959            subscription_id,
 960            callback: Box::new(move |payload, cx| {
 961                let payload = payload.downcast_ref().expect("downcast is type safe");
 962                callback(payload, cx)
 963            }),
 964        });
 965        Subscription::GlobalSubscription(
 966            self.global_subscriptions
 967                .subscribe(type_id, subscription_id),
 968        )
 969    }
 970
 971    pub fn observe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 972    where
 973        E: Entity,
 974        E::Event: 'static,
 975        H: Handle<E>,
 976        F: 'static + FnMut(H, &mut Self),
 977    {
 978        self.observe_internal(handle, move |handle, cx| {
 979            callback(handle, cx);
 980            true
 981        })
 982    }
 983
 984    pub fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 985    where
 986        E: Entity,
 987        E::Event: 'static,
 988        H: Handle<E>,
 989        F: 'static + FnMut(H, &E::Event, &mut Self) -> bool,
 990    {
 991        let subscription_id = post_inc(&mut self.next_subscription_id);
 992        let emitter = handle.downgrade();
 993        self.pending_effects.push_back(Effect::Subscription {
 994            entity_id: handle.id(),
 995            subscription_id,
 996            callback: Box::new(move |payload, cx| {
 997                if let Some(emitter) = H::upgrade_from(&emitter, cx.as_ref()) {
 998                    let payload = payload.downcast_ref().expect("downcast is type safe");
 999                    callback(emitter, payload, cx)
1000                } else {
1001                    false
1002                }
1003            }),
1004        });
1005        Subscription::Subscription(self.subscriptions.subscribe(handle.id(), subscription_id))
1006    }
1007
1008    fn observe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1009    where
1010        E: Entity,
1011        E::Event: 'static,
1012        H: Handle<E>,
1013        F: 'static + FnMut(H, &mut Self) -> bool,
1014    {
1015        let subscription_id = post_inc(&mut self.next_subscription_id);
1016        let observed = handle.downgrade();
1017        let entity_id = handle.id();
1018        self.pending_effects.push_back(Effect::Observation {
1019            entity_id,
1020            subscription_id,
1021            callback: Box::new(move |cx| {
1022                if let Some(observed) = H::upgrade_from(&observed, cx) {
1023                    callback(observed, cx)
1024                } else {
1025                    false
1026                }
1027            }),
1028        });
1029        Subscription::Observation(self.observations.subscribe(entity_id, subscription_id))
1030    }
1031
1032    fn observe_focus<F, V>(&mut self, handle: &ViewHandle<V>, mut callback: F) -> Subscription
1033    where
1034        F: 'static + FnMut(ViewHandle<V>, bool, &mut MutableAppContext) -> bool,
1035        V: View,
1036    {
1037        let subscription_id = post_inc(&mut self.next_subscription_id);
1038        let observed = handle.downgrade();
1039        let view_id = handle.id();
1040
1041        self.pending_effects.push_back(Effect::FocusObservation {
1042            view_id,
1043            subscription_id,
1044            callback: Box::new(move |focused, cx| {
1045                if let Some(observed) = observed.upgrade(cx) {
1046                    callback(observed, focused, cx)
1047                } else {
1048                    false
1049                }
1050            }),
1051        });
1052        Subscription::FocusObservation(self.focus_observations.subscribe(view_id, subscription_id))
1053    }
1054
1055    pub fn observe_global<G, F>(&mut self, mut observe: F) -> Subscription
1056    where
1057        G: Any,
1058        F: 'static + FnMut(&mut MutableAppContext),
1059    {
1060        let type_id = TypeId::of::<G>();
1061        let id = post_inc(&mut self.next_subscription_id);
1062
1063        self.global_observations.add_callback(
1064            type_id,
1065            id,
1066            Box::new(move |cx: &mut MutableAppContext| observe(cx)),
1067        );
1068        Subscription::GlobalObservation(self.global_observations.subscribe(type_id, id))
1069    }
1070
1071    pub fn observe_default_global<G, F>(&mut self, observe: F) -> Subscription
1072    where
1073        G: Any + Default,
1074        F: 'static + FnMut(&mut MutableAppContext),
1075    {
1076        if !self.has_global::<G>() {
1077            self.set_global(G::default());
1078        }
1079        self.observe_global::<G, F>(observe)
1080    }
1081
1082    pub fn observe_release<E, H, F>(&mut self, handle: &H, callback: F) -> Subscription
1083    where
1084        E: Entity,
1085        E::Event: 'static,
1086        H: Handle<E>,
1087        F: 'static + FnOnce(&E, &mut Self),
1088    {
1089        let id = post_inc(&mut self.next_subscription_id);
1090        let mut callback = Some(callback);
1091        self.release_observations.add_callback(
1092            handle.id(),
1093            id,
1094            Box::new(move |released, cx| {
1095                let released = released.downcast_ref().unwrap();
1096                if let Some(callback) = callback.take() {
1097                    callback(released, cx)
1098                }
1099            }),
1100        );
1101        Subscription::ReleaseObservation(self.release_observations.subscribe(handle.id(), id))
1102    }
1103
1104    pub fn observe_actions<F>(&mut self, callback: F) -> Subscription
1105    where
1106        F: 'static + FnMut(TypeId, &mut MutableAppContext),
1107    {
1108        let subscription_id = post_inc(&mut self.next_subscription_id);
1109        self.action_dispatch_observations
1110            .add_callback((), subscription_id, Box::new(callback));
1111        Subscription::ActionObservation(
1112            self.action_dispatch_observations
1113                .subscribe((), subscription_id),
1114        )
1115    }
1116
1117    fn observe_window_activation<F>(&mut self, window_id: usize, callback: F) -> Subscription
1118    where
1119        F: 'static + FnMut(bool, &mut MutableAppContext) -> bool,
1120    {
1121        let subscription_id = post_inc(&mut self.next_subscription_id);
1122        self.pending_effects
1123            .push_back(Effect::WindowActivationObservation {
1124                window_id,
1125                subscription_id,
1126                callback: Box::new(callback),
1127            });
1128        Subscription::WindowActivationObservation(
1129            self.window_activation_observations
1130                .subscribe(window_id, subscription_id),
1131        )
1132    }
1133
1134    fn observe_fullscreen<F>(&mut self, window_id: usize, callback: F) -> Subscription
1135    where
1136        F: 'static + FnMut(bool, &mut MutableAppContext) -> bool,
1137    {
1138        let subscription_id = post_inc(&mut self.next_subscription_id);
1139        self.pending_effects
1140            .push_back(Effect::WindowFullscreenObservation {
1141                window_id,
1142                subscription_id,
1143                callback: Box::new(callback),
1144            });
1145        Subscription::WindowActivationObservation(
1146            self.window_activation_observations
1147                .subscribe(window_id, subscription_id),
1148        )
1149    }
1150
1151    fn observe_window_bounds<F>(&mut self, window_id: usize, callback: F) -> Subscription
1152    where
1153        F: 'static + FnMut(WindowBounds, Uuid, &mut MutableAppContext) -> bool,
1154    {
1155        let subscription_id = post_inc(&mut self.next_subscription_id);
1156        self.pending_effects
1157            .push_back(Effect::WindowBoundsObservation {
1158                window_id,
1159                subscription_id,
1160                callback: Box::new(callback),
1161            });
1162        Subscription::WindowBoundsObservation(
1163            self.window_bounds_observations
1164                .subscribe(window_id, subscription_id),
1165        )
1166    }
1167
1168    pub fn observe_keystrokes<F>(&mut self, window_id: usize, callback: F) -> Subscription
1169    where
1170        F: 'static
1171            + FnMut(
1172                &Keystroke,
1173                &MatchResult,
1174                Option<&Box<dyn Action>>,
1175                &mut MutableAppContext,
1176            ) -> bool,
1177    {
1178        let subscription_id = post_inc(&mut self.next_subscription_id);
1179        self.keystroke_observations
1180            .add_callback(window_id, subscription_id, Box::new(callback));
1181        Subscription::KeystrokeObservation(
1182            self.keystroke_observations
1183                .subscribe(window_id, subscription_id),
1184        )
1185    }
1186
1187    pub fn observe_active_labeled_tasks<F>(&mut self, callback: F) -> Subscription
1188    where
1189        F: 'static + FnMut(&mut MutableAppContext) -> bool,
1190    {
1191        let subscription_id = post_inc(&mut self.next_subscription_id);
1192        self.active_labeled_task_observations
1193            .add_callback((), subscription_id, Box::new(callback));
1194        Subscription::ActiveLabeledTasksObservation(
1195            self.active_labeled_task_observations
1196                .subscribe((), subscription_id),
1197        )
1198    }
1199
1200    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut MutableAppContext)) {
1201        self.pending_effects.push_back(Effect::Deferred {
1202            callback: Box::new(callback),
1203            after_window_update: false,
1204        })
1205    }
1206
1207    pub fn after_window_update(&mut self, callback: impl 'static + FnOnce(&mut MutableAppContext)) {
1208        self.pending_effects.push_back(Effect::Deferred {
1209            callback: Box::new(callback),
1210            after_window_update: true,
1211        })
1212    }
1213
1214    pub(crate) fn notify_model(&mut self, model_id: usize) {
1215        if self.pending_notifications.insert(model_id) {
1216            self.pending_effects
1217                .push_back(Effect::ModelNotification { model_id });
1218        }
1219    }
1220
1221    pub(crate) fn notify_view(&mut self, window_id: usize, view_id: usize) {
1222        if self.pending_notifications.insert(view_id) {
1223            self.pending_effects
1224                .push_back(Effect::ViewNotification { window_id, view_id });
1225        }
1226    }
1227
1228    pub(crate) fn notify_global(&mut self, type_id: TypeId) {
1229        if self.pending_global_notifications.insert(type_id) {
1230            self.pending_effects
1231                .push_back(Effect::GlobalNotification { type_id });
1232        }
1233    }
1234
1235    pub(crate) fn name_for_view(&self, window_id: usize, view_id: usize) -> Option<&str> {
1236        self.views
1237            .get(&(window_id, view_id))
1238            .map(|view| view.ui_name())
1239    }
1240
1241    pub fn all_action_names<'a>(&'a self) -> impl Iterator<Item = &'static str> + 'a {
1242        self.action_deserializers.keys().copied()
1243    }
1244
1245    /// Return keystrokes that would dispatch the given action on the given view.
1246    pub(crate) fn keystrokes_for_action(
1247        &mut self,
1248        window_id: usize,
1249        view_id: usize,
1250        action: &dyn Action,
1251    ) -> Option<SmallVec<[Keystroke; 2]>> {
1252        let mut contexts = Vec::new();
1253        let mut handler_depth = None;
1254        for (i, view_id) in self.ancestors(window_id, view_id).enumerate() {
1255            if let Some(view) = self.views.get(&(window_id, view_id)) {
1256                if let Some(actions) = self.actions.get(&view.as_any().type_id()) {
1257                    if actions.contains_key(&action.as_any().type_id()) {
1258                        handler_depth = Some(i);
1259                    }
1260                }
1261                contexts.push(view.keymap_context(self));
1262            }
1263        }
1264
1265        if self.global_actions.contains_key(&action.as_any().type_id()) {
1266            handler_depth = Some(contexts.len())
1267        }
1268
1269        self.keystroke_matcher
1270            .bindings_for_action_type(action.as_any().type_id())
1271            .find_map(|b| {
1272                handler_depth
1273                    .map(|highest_handler| {
1274                        if (0..=highest_handler).any(|depth| b.match_context(&contexts[depth..])) {
1275                            Some(b.keystrokes().into())
1276                        } else {
1277                            None
1278                        }
1279                    })
1280                    .flatten()
1281            })
1282    }
1283
1284    pub fn available_actions(
1285        &self,
1286        window_id: usize,
1287        view_id: usize,
1288    ) -> impl Iterator<Item = (&'static str, Box<dyn Action>, SmallVec<[&Binding; 1]>)> {
1289        let mut contexts = Vec::new();
1290        let mut handler_depths_by_action_type = HashMap::<TypeId, usize>::default();
1291        for (depth, view_id) in self.ancestors(window_id, view_id).enumerate() {
1292            if let Some(view) = self.views.get(&(window_id, view_id)) {
1293                contexts.push(view.keymap_context(self));
1294                let view_type = view.as_any().type_id();
1295                if let Some(actions) = self.actions.get(&view_type) {
1296                    handler_depths_by_action_type.extend(
1297                        actions
1298                            .keys()
1299                            .copied()
1300                            .map(|action_type| (action_type, depth)),
1301                    );
1302                }
1303            }
1304        }
1305
1306        handler_depths_by_action_type.extend(
1307            self.global_actions
1308                .keys()
1309                .copied()
1310                .map(|action_type| (action_type, contexts.len())),
1311        );
1312
1313        self.action_deserializers
1314            .iter()
1315            .filter_map(move |(name, (type_id, deserialize))| {
1316                if let Some(action_depth) = handler_depths_by_action_type.get(type_id).copied() {
1317                    Some((
1318                        *name,
1319                        deserialize("{}").ok()?,
1320                        self.keystroke_matcher
1321                            .bindings_for_action_type(*type_id)
1322                            .filter(|b| {
1323                                (0..=action_depth).any(|depth| b.match_context(&contexts[depth..]))
1324                            })
1325                            .collect(),
1326                    ))
1327                } else {
1328                    None
1329                }
1330            })
1331    }
1332
1333    pub fn is_action_available(&self, action: &dyn Action) -> bool {
1334        let action_type = action.as_any().type_id();
1335        if let Some(window_id) = self.cx.platform.main_window_id() {
1336            if let Some(focused_view_id) = self.focused_view_id(window_id) {
1337                for view_id in self.ancestors(window_id, focused_view_id) {
1338                    if let Some(view) = self.views.get(&(window_id, view_id)) {
1339                        let view_type = view.as_any().type_id();
1340                        if let Some(actions) = self.actions.get(&view_type) {
1341                            if actions.contains_key(&action_type) {
1342                                return true;
1343                            }
1344                        }
1345                    }
1346                }
1347            }
1348        }
1349        self.global_actions.contains_key(&action_type)
1350    }
1351
1352    // Traverses the parent tree. Walks down the tree toward the passed
1353    // view calling visit with true. Then walks back up the tree calling visit with false.
1354    // If `visit` returns false this function will immediately return.
1355    // Returns a bool indicating if the traversal was completed early.
1356    fn visit_dispatch_path(
1357        &mut self,
1358        window_id: usize,
1359        view_id: usize,
1360        mut visit: impl FnMut(usize, bool, &mut MutableAppContext) -> bool,
1361    ) -> bool {
1362        // List of view ids from the leaf to the root of the window
1363        let path = self.ancestors(window_id, view_id).collect::<Vec<_>>();
1364
1365        // Walk down from the root to the leaf calling visit with capture_phase = true
1366        for view_id in path.iter().rev() {
1367            if !visit(*view_id, true, self) {
1368                return false;
1369            }
1370        }
1371
1372        // Walk up from the leaf to the root calling visit with capture_phase = false
1373        for view_id in path.iter() {
1374            if !visit(*view_id, false, self) {
1375                return false;
1376            }
1377        }
1378
1379        true
1380    }
1381
1382    fn actions_mut(
1383        &mut self,
1384        capture_phase: bool,
1385    ) -> &mut HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>> {
1386        if capture_phase {
1387            &mut self.capture_actions
1388        } else {
1389            &mut self.actions
1390        }
1391    }
1392
1393    pub fn dispatch_global_action<A: Action>(&mut self, action: A) {
1394        self.dispatch_global_action_any(&action);
1395    }
1396
1397    fn dispatch_global_action_any(&mut self, action: &dyn Action) -> bool {
1398        self.update(|this| {
1399            if let Some((name, mut handler)) = this.global_actions.remove_entry(&action.id()) {
1400                handler(action, this);
1401                this.global_actions.insert(name, handler);
1402                true
1403            } else {
1404                false
1405            }
1406        })
1407    }
1408
1409    pub fn add_bindings<T: IntoIterator<Item = Binding>>(&mut self, bindings: T) {
1410        self.keystroke_matcher.add_bindings(bindings);
1411    }
1412
1413    pub fn clear_bindings(&mut self) {
1414        self.keystroke_matcher.clear_bindings();
1415    }
1416
1417    pub fn dispatch_key_down(&mut self, window_id: usize, event: &KeyDownEvent) -> bool {
1418        if let Some(focused_view_id) = self.focused_view_id(window_id) {
1419            for view_id in self
1420                .ancestors(window_id, focused_view_id)
1421                .collect::<Vec<_>>()
1422            {
1423                if let Some(mut view) = self.cx.views.remove(&(window_id, view_id)) {
1424                    let handled = view.key_down(event, self, window_id, view_id);
1425                    self.cx.views.insert((window_id, view_id), view);
1426                    if handled {
1427                        return true;
1428                    }
1429                } else {
1430                    log::error!("view {} does not exist", view_id)
1431                }
1432            }
1433        }
1434
1435        false
1436    }
1437
1438    pub fn dispatch_key_up(&mut self, window_id: usize, event: &KeyUpEvent) -> bool {
1439        if let Some(focused_view_id) = self.focused_view_id(window_id) {
1440            for view_id in self
1441                .ancestors(window_id, focused_view_id)
1442                .collect::<Vec<_>>()
1443            {
1444                if let Some(mut view) = self.cx.views.remove(&(window_id, view_id)) {
1445                    let handled = view.key_up(event, self, window_id, view_id);
1446                    self.cx.views.insert((window_id, view_id), view);
1447                    if handled {
1448                        return true;
1449                    }
1450                } else {
1451                    log::error!("view {} does not exist", view_id)
1452                }
1453            }
1454        }
1455
1456        false
1457    }
1458
1459    pub fn dispatch_modifiers_changed(
1460        &mut self,
1461        window_id: usize,
1462        event: &ModifiersChangedEvent,
1463    ) -> bool {
1464        if let Some(focused_view_id) = self.focused_view_id(window_id) {
1465            for view_id in self
1466                .ancestors(window_id, focused_view_id)
1467                .collect::<Vec<_>>()
1468            {
1469                if let Some(mut view) = self.cx.views.remove(&(window_id, view_id)) {
1470                    let handled = view.modifiers_changed(event, self, window_id, view_id);
1471                    self.cx.views.insert((window_id, view_id), view);
1472                    if handled {
1473                        return true;
1474                    }
1475                } else {
1476                    log::error!("view {} does not exist", view_id)
1477                }
1478            }
1479        }
1480
1481        false
1482    }
1483
1484    pub fn dispatch_keystroke(&mut self, window_id: usize, keystroke: &Keystroke) -> bool {
1485        if let Some(focused_view_id) = self.focused_view_id(window_id) {
1486            let dispatch_path = self
1487                .ancestors(window_id, focused_view_id)
1488                .filter_map(|view_id| {
1489                    self.cx
1490                        .views
1491                        .get(&(window_id, view_id))
1492                        .map(|view| (view_id, view.keymap_context(self.as_ref())))
1493                })
1494                .collect();
1495
1496            let match_result = self
1497                .keystroke_matcher
1498                .push_keystroke(keystroke.clone(), dispatch_path);
1499            let mut handled_by = None;
1500
1501            let keystroke_handled = match &match_result {
1502                MatchResult::None => false,
1503                MatchResult::Pending => true,
1504                MatchResult::Matches(matches) => {
1505                    for (view_id, action) in matches {
1506                        if self.handle_dispatch_action_from_effect(
1507                            window_id,
1508                            Some(*view_id),
1509                            action.as_ref(),
1510                        ) {
1511                            self.keystroke_matcher.clear_pending();
1512                            handled_by = Some(action.boxed_clone());
1513                            break;
1514                        }
1515                    }
1516                    handled_by.is_some()
1517                }
1518            };
1519
1520            self.keystroke(
1521                window_id,
1522                keystroke.clone(),
1523                handled_by,
1524                match_result.clone(),
1525            );
1526            keystroke_handled
1527        } else {
1528            self.keystroke(window_id, keystroke.clone(), None, MatchResult::None);
1529            false
1530        }
1531    }
1532
1533    pub fn default_global<T: 'static + Default>(&mut self) -> &T {
1534        let type_id = TypeId::of::<T>();
1535        self.update(|this| {
1536            if let Entry::Vacant(entry) = this.cx.globals.entry(type_id) {
1537                entry.insert(Box::new(T::default()));
1538                this.notify_global(type_id);
1539            }
1540        });
1541        self.globals.get(&type_id).unwrap().downcast_ref().unwrap()
1542    }
1543
1544    pub fn set_global<T: 'static>(&mut self, state: T) {
1545        self.update(|this| {
1546            let type_id = TypeId::of::<T>();
1547            this.cx.globals.insert(type_id, Box::new(state));
1548            this.notify_global(type_id);
1549        });
1550    }
1551
1552    pub fn update_default_global<T, F, U>(&mut self, update: F) -> U
1553    where
1554        T: 'static + Default,
1555        F: FnOnce(&mut T, &mut MutableAppContext) -> U,
1556    {
1557        self.update(|this| {
1558            let type_id = TypeId::of::<T>();
1559            let mut state = this
1560                .cx
1561                .globals
1562                .remove(&type_id)
1563                .unwrap_or_else(|| Box::new(T::default()));
1564            let result = update(state.downcast_mut().unwrap(), this);
1565            this.cx.globals.insert(type_id, state);
1566            this.notify_global(type_id);
1567            result
1568        })
1569    }
1570
1571    pub fn update_global<T, F, U>(&mut self, update: F) -> U
1572    where
1573        T: 'static,
1574        F: FnOnce(&mut T, &mut MutableAppContext) -> U,
1575    {
1576        self.update(|this| {
1577            let type_id = TypeId::of::<T>();
1578            if let Some(mut state) = this.cx.globals.remove(&type_id) {
1579                let result = update(state.downcast_mut().unwrap(), this);
1580                this.cx.globals.insert(type_id, state);
1581                this.notify_global(type_id);
1582                result
1583            } else {
1584                panic!("No global added for {}", std::any::type_name::<T>());
1585            }
1586        })
1587    }
1588
1589    pub fn clear_globals(&mut self) {
1590        self.cx.globals.clear();
1591    }
1592
1593    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
1594    where
1595        T: Entity,
1596        F: FnOnce(&mut ModelContext<T>) -> T,
1597    {
1598        self.update(|this| {
1599            let model_id = post_inc(&mut this.next_entity_id);
1600            let handle = ModelHandle::new(model_id, &this.cx.ref_counts);
1601            let mut cx = ModelContext::new(this, model_id);
1602            let model = build_model(&mut cx);
1603            this.cx.models.insert(model_id, Box::new(model));
1604            handle
1605        })
1606    }
1607
1608    pub fn add_window<T, F>(
1609        &mut self,
1610        window_options: WindowOptions,
1611        build_root_view: F,
1612    ) -> (usize, ViewHandle<T>)
1613    where
1614        T: View,
1615        F: FnOnce(&mut ViewContext<T>) -> T,
1616    {
1617        self.update(|this| {
1618            let window_id = post_inc(&mut this.next_window_id);
1619            let root_view = this
1620                .build_and_insert_view(window_id, ParentId::Root, |cx| Some(build_root_view(cx)))
1621                .unwrap();
1622            this.cx.windows.insert(
1623                window_id,
1624                Window {
1625                    root_view: root_view.clone().into(),
1626                    focused_view_id: Some(root_view.id()),
1627                    is_active: false,
1628                    invalidation: None,
1629                    is_fullscreen: false,
1630                },
1631            );
1632            root_view.update(this, |view, cx| view.focus_in(cx.handle().into(), cx));
1633
1634            let window =
1635                this.cx
1636                    .platform
1637                    .open_window(window_id, window_options, this.foreground.clone());
1638            this.register_platform_window(window_id, window);
1639
1640            (window_id, root_view)
1641        })
1642    }
1643
1644    pub fn add_status_bar_item<T, F>(&mut self, build_root_view: F) -> (usize, ViewHandle<T>)
1645    where
1646        T: View,
1647        F: FnOnce(&mut ViewContext<T>) -> T,
1648    {
1649        self.update(|this| {
1650            let window_id = post_inc(&mut this.next_window_id);
1651            let root_view = this
1652                .build_and_insert_view(window_id, ParentId::Root, |cx| Some(build_root_view(cx)))
1653                .unwrap();
1654            this.cx.windows.insert(
1655                window_id,
1656                Window {
1657                    root_view: root_view.clone().into(),
1658                    focused_view_id: Some(root_view.id()),
1659                    is_active: false,
1660                    invalidation: None,
1661                    is_fullscreen: false,
1662                },
1663            );
1664            root_view.update(this, |view, cx| view.focus_in(cx.handle().into(), cx));
1665
1666            let status_item = this.cx.platform.add_status_item();
1667            this.register_platform_window(window_id, status_item);
1668
1669            (window_id, root_view)
1670        })
1671    }
1672
1673    pub fn remove_status_bar_item(&mut self, id: usize) {
1674        self.remove_window(id);
1675    }
1676
1677    fn register_platform_window(
1678        &mut self,
1679        window_id: usize,
1680        mut window: Box<dyn platform::Window>,
1681    ) {
1682        let presenter = Rc::new(RefCell::new(self.build_presenter(
1683            window_id,
1684            window.titlebar_height(),
1685            window.appearance(),
1686        )));
1687
1688        {
1689            let mut app = self.upgrade();
1690            let presenter = Rc::downgrade(&presenter);
1691
1692            window.on_event(Box::new(move |event| {
1693                app.update(|cx| {
1694                    if let Some(presenter) = presenter.upgrade() {
1695                        if let Event::KeyDown(KeyDownEvent { keystroke, .. }) = &event {
1696                            if cx.dispatch_keystroke(window_id, keystroke) {
1697                                return true;
1698                            }
1699                        }
1700
1701                        presenter.borrow_mut().dispatch_event(event, false, cx)
1702                    } else {
1703                        false
1704                    }
1705                })
1706            }));
1707        }
1708
1709        {
1710            let mut app = self.upgrade();
1711            window.on_active_status_change(Box::new(move |is_active| {
1712                app.update(|cx| cx.window_changed_active_status(window_id, is_active))
1713            }));
1714        }
1715
1716        {
1717            let mut app = self.upgrade();
1718            window.on_resize(Box::new(move || {
1719                app.update(|cx| cx.window_was_resized(window_id))
1720            }));
1721        }
1722
1723        {
1724            let mut app = self.upgrade();
1725            window.on_moved(Box::new(move || {
1726                app.update(|cx| cx.window_was_moved(window_id))
1727            }));
1728        }
1729
1730        {
1731            let mut app = self.upgrade();
1732            window.on_fullscreen(Box::new(move |is_fullscreen| {
1733                app.update(|cx| cx.window_was_fullscreen_changed(window_id, is_fullscreen))
1734            }));
1735        }
1736
1737        {
1738            let mut app = self.upgrade();
1739            window.on_close(Box::new(move || {
1740                app.update(|cx| cx.remove_window(window_id));
1741            }));
1742        }
1743
1744        {
1745            let mut app = self.upgrade();
1746            window.on_appearance_changed(Box::new(move || app.update(|cx| cx.refresh_windows())));
1747        }
1748
1749        window.set_input_handler(Box::new(WindowInputHandler {
1750            app: self.upgrade().0,
1751            window_id,
1752        }));
1753
1754        let scene = presenter.borrow_mut().build_scene(
1755            window.content_size(),
1756            window.scale_factor(),
1757            false,
1758            self,
1759        );
1760        window.present_scene(scene);
1761        self.presenters_and_platform_windows
1762            .insert(window_id, (presenter.clone(), window));
1763    }
1764
1765    pub fn replace_root_view<T, F>(&mut self, window_id: usize, build_root_view: F) -> ViewHandle<T>
1766    where
1767        T: View,
1768        F: FnOnce(&mut ViewContext<T>) -> T,
1769    {
1770        self.update(|this| {
1771            let root_view = this
1772                .build_and_insert_view(window_id, ParentId::Root, |cx| Some(build_root_view(cx)))
1773                .unwrap();
1774            let window = this.cx.windows.get_mut(&window_id).unwrap();
1775            window.root_view = root_view.clone().into();
1776            window.focused_view_id = Some(root_view.id());
1777            root_view
1778        })
1779    }
1780
1781    pub fn remove_window(&mut self, window_id: usize) {
1782        self.cx.windows.remove(&window_id);
1783        self.presenters_and_platform_windows.remove(&window_id);
1784        self.flush_effects();
1785    }
1786
1787    pub fn build_presenter(
1788        &mut self,
1789        window_id: usize,
1790        titlebar_height: f32,
1791        appearance: Appearance,
1792    ) -> Presenter {
1793        Presenter::new(
1794            window_id,
1795            titlebar_height,
1796            appearance,
1797            self.cx.font_cache.clone(),
1798            TextLayoutCache::new(self.cx.platform.fonts()),
1799            self.assets.clone(),
1800            self,
1801        )
1802    }
1803
1804    pub fn add_view<T, F>(
1805        &mut self,
1806        parent_handle: impl Into<AnyViewHandle>,
1807        build_view: F,
1808    ) -> ViewHandle<T>
1809    where
1810        T: View,
1811        F: FnOnce(&mut ViewContext<T>) -> T,
1812    {
1813        let parent_handle = parent_handle.into();
1814        self.build_and_insert_view(
1815            parent_handle.window_id,
1816            ParentId::View(parent_handle.view_id),
1817            |cx| Some(build_view(cx)),
1818        )
1819        .unwrap()
1820    }
1821
1822    pub fn add_option_view<T, F>(
1823        &mut self,
1824        parent_handle: impl Into<AnyViewHandle>,
1825        build_view: F,
1826    ) -> Option<ViewHandle<T>>
1827    where
1828        T: View,
1829        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1830    {
1831        let parent_handle = parent_handle.into();
1832        self.build_and_insert_view(
1833            parent_handle.window_id,
1834            ParentId::View(parent_handle.view_id),
1835            build_view,
1836        )
1837    }
1838
1839    pub(crate) fn build_and_insert_view<T, F>(
1840        &mut self,
1841        window_id: usize,
1842        parent_id: ParentId,
1843        build_view: F,
1844    ) -> Option<ViewHandle<T>>
1845    where
1846        T: View,
1847        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1848    {
1849        self.update(|this| {
1850            let view_id = post_inc(&mut this.next_entity_id);
1851            // Make sure we can tell child views about their parent
1852            this.cx.parents.insert((window_id, view_id), parent_id);
1853            let mut cx = ViewContext::new(this, window_id, view_id);
1854            let handle = if let Some(view) = build_view(&mut cx) {
1855                this.cx.views.insert((window_id, view_id), Box::new(view));
1856                if let Some(window) = this.cx.windows.get_mut(&window_id) {
1857                    window
1858                        .invalidation
1859                        .get_or_insert_with(Default::default)
1860                        .updated
1861                        .insert(view_id);
1862                }
1863                Some(ViewHandle::new(window_id, view_id, &this.cx.ref_counts))
1864            } else {
1865                this.cx.parents.remove(&(window_id, view_id));
1866                None
1867            };
1868            handle
1869        })
1870    }
1871
1872    fn remove_dropped_entities(&mut self) {
1873        loop {
1874            let (dropped_models, dropped_views, dropped_element_states) =
1875                self.cx.ref_counts.lock().take_dropped();
1876            if dropped_models.is_empty()
1877                && dropped_views.is_empty()
1878                && dropped_element_states.is_empty()
1879            {
1880                break;
1881            }
1882
1883            for model_id in dropped_models {
1884                self.subscriptions.remove(model_id);
1885                self.observations.remove(model_id);
1886                let mut model = self.cx.models.remove(&model_id).unwrap();
1887                model.release(self);
1888                self.pending_effects
1889                    .push_back(Effect::ModelRelease { model_id, model });
1890            }
1891
1892            for (window_id, view_id) in dropped_views {
1893                self.subscriptions.remove(view_id);
1894                self.observations.remove(view_id);
1895                let mut view = self.cx.views.remove(&(window_id, view_id)).unwrap();
1896                view.release(self);
1897                let change_focus_to = self.cx.windows.get_mut(&window_id).and_then(|window| {
1898                    window
1899                        .invalidation
1900                        .get_or_insert_with(Default::default)
1901                        .removed
1902                        .push(view_id);
1903                    if window.focused_view_id == Some(view_id) {
1904                        Some(window.root_view.id())
1905                    } else {
1906                        None
1907                    }
1908                });
1909                self.cx.parents.remove(&(window_id, view_id));
1910
1911                if let Some(view_id) = change_focus_to {
1912                    self.handle_focus_effect(window_id, Some(view_id));
1913                }
1914
1915                self.pending_effects
1916                    .push_back(Effect::ViewRelease { view_id, view });
1917            }
1918
1919            for key in dropped_element_states {
1920                self.cx.element_states.remove(&key);
1921            }
1922        }
1923    }
1924
1925    fn flush_effects(&mut self) {
1926        self.pending_flushes = self.pending_flushes.saturating_sub(1);
1927        let mut after_window_update_callbacks = Vec::new();
1928
1929        if !self.flushing_effects && self.pending_flushes == 0 {
1930            self.flushing_effects = true;
1931
1932            let mut refreshing = false;
1933            loop {
1934                if let Some(effect) = self.pending_effects.pop_front() {
1935                    match effect {
1936                        Effect::Subscription {
1937                            entity_id,
1938                            subscription_id,
1939                            callback,
1940                        } => self
1941                            .subscriptions
1942                            .add_callback(entity_id, subscription_id, callback),
1943
1944                        Effect::Event { entity_id, payload } => {
1945                            let mut subscriptions = self.subscriptions.clone();
1946                            subscriptions.emit(entity_id, self, |callback, this| {
1947                                callback(payload.as_ref(), this)
1948                            })
1949                        }
1950
1951                        Effect::GlobalSubscription {
1952                            type_id,
1953                            subscription_id,
1954                            callback,
1955                        } => self.global_subscriptions.add_callback(
1956                            type_id,
1957                            subscription_id,
1958                            callback,
1959                        ),
1960
1961                        Effect::GlobalEvent { payload } => self.emit_global_event(payload),
1962
1963                        Effect::Observation {
1964                            entity_id,
1965                            subscription_id,
1966                            callback,
1967                        } => self
1968                            .observations
1969                            .add_callback(entity_id, subscription_id, callback),
1970
1971                        Effect::ModelNotification { model_id } => {
1972                            let mut observations = self.observations.clone();
1973                            observations.emit(model_id, self, |callback, this| callback(this));
1974                        }
1975
1976                        Effect::ViewNotification { window_id, view_id } => {
1977                            self.handle_view_notification_effect(window_id, view_id)
1978                        }
1979
1980                        Effect::GlobalNotification { type_id } => {
1981                            let mut subscriptions = self.global_observations.clone();
1982                            subscriptions.emit(type_id, self, |callback, this| {
1983                                callback(this);
1984                                true
1985                            });
1986                        }
1987
1988                        Effect::Deferred {
1989                            callback,
1990                            after_window_update,
1991                        } => {
1992                            if after_window_update {
1993                                after_window_update_callbacks.push(callback);
1994                            } else {
1995                                callback(self)
1996                            }
1997                        }
1998
1999                        Effect::ModelRelease { model_id, model } => {
2000                            self.handle_entity_release_effect(model_id, model.as_any())
2001                        }
2002
2003                        Effect::ViewRelease { view_id, view } => {
2004                            self.handle_entity_release_effect(view_id, view.as_any())
2005                        }
2006
2007                        Effect::Focus { window_id, view_id } => {
2008                            self.handle_focus_effect(window_id, view_id);
2009                        }
2010
2011                        Effect::FocusObservation {
2012                            view_id,
2013                            subscription_id,
2014                            callback,
2015                        } => {
2016                            self.focus_observations.add_callback(
2017                                view_id,
2018                                subscription_id,
2019                                callback,
2020                            );
2021                        }
2022
2023                        Effect::ResizeWindow { window_id } => {
2024                            if let Some(window) = self.cx.windows.get_mut(&window_id) {
2025                                window
2026                                    .invalidation
2027                                    .get_or_insert(WindowInvalidation::default());
2028                            }
2029                            self.handle_window_moved(window_id);
2030                        }
2031
2032                        Effect::MoveWindow { window_id } => {
2033                            self.handle_window_moved(window_id);
2034                        }
2035
2036                        Effect::WindowActivationObservation {
2037                            window_id,
2038                            subscription_id,
2039                            callback,
2040                        } => self.window_activation_observations.add_callback(
2041                            window_id,
2042                            subscription_id,
2043                            callback,
2044                        ),
2045
2046                        Effect::ActivateWindow {
2047                            window_id,
2048                            is_active,
2049                        } => self.handle_window_activation_effect(window_id, is_active),
2050
2051                        Effect::WindowFullscreenObservation {
2052                            window_id,
2053                            subscription_id,
2054                            callback,
2055                        } => self.window_fullscreen_observations.add_callback(
2056                            window_id,
2057                            subscription_id,
2058                            callback,
2059                        ),
2060
2061                        Effect::FullscreenWindow {
2062                            window_id,
2063                            is_fullscreen,
2064                        } => self.handle_fullscreen_effect(window_id, is_fullscreen),
2065
2066                        Effect::WindowBoundsObservation {
2067                            window_id,
2068                            subscription_id,
2069                            callback,
2070                        } => self.window_bounds_observations.add_callback(
2071                            window_id,
2072                            subscription_id,
2073                            callback,
2074                        ),
2075
2076                        Effect::RefreshWindows => {
2077                            refreshing = true;
2078                        }
2079                        Effect::DispatchActionFrom {
2080                            window_id,
2081                            view_id,
2082                            action,
2083                        } => {
2084                            self.handle_dispatch_action_from_effect(
2085                                window_id,
2086                                Some(view_id),
2087                                action.as_ref(),
2088                            );
2089                        }
2090                        Effect::ActionDispatchNotification { action_id } => {
2091                            self.handle_action_dispatch_notification_effect(action_id)
2092                        }
2093                        Effect::WindowShouldCloseSubscription {
2094                            window_id,
2095                            callback,
2096                        } => {
2097                            self.handle_window_should_close_subscription_effect(window_id, callback)
2098                        }
2099                        Effect::Keystroke {
2100                            window_id,
2101                            keystroke,
2102                            handled_by,
2103                            result,
2104                        } => self.handle_keystroke_effect(window_id, keystroke, handled_by, result),
2105                        Effect::ActiveLabeledTasksChanged => {
2106                            self.handle_active_labeled_tasks_changed_effect()
2107                        }
2108                        Effect::ActiveLabeledTasksObservation {
2109                            subscription_id,
2110                            callback,
2111                        } => self.active_labeled_task_observations.add_callback(
2112                            (),
2113                            subscription_id,
2114                            callback,
2115                        ),
2116                    }
2117                    self.pending_notifications.clear();
2118                    self.remove_dropped_entities();
2119                } else {
2120                    self.remove_dropped_entities();
2121
2122                    if refreshing {
2123                        self.perform_window_refresh();
2124                    } else {
2125                        self.update_windows();
2126                    }
2127
2128                    if self.pending_effects.is_empty() {
2129                        for callback in after_window_update_callbacks.drain(..) {
2130                            callback(self);
2131                        }
2132
2133                        if self.pending_effects.is_empty() {
2134                            self.flushing_effects = false;
2135                            self.pending_notifications.clear();
2136                            self.pending_global_notifications.clear();
2137                            break;
2138                        }
2139                    }
2140
2141                    refreshing = false;
2142                }
2143            }
2144        }
2145    }
2146
2147    fn update_windows(&mut self) {
2148        let mut invalidations: HashMap<_, _> = Default::default();
2149        for (window_id, window) in &mut self.cx.windows {
2150            if let Some(invalidation) = window.invalidation.take() {
2151                invalidations.insert(*window_id, invalidation);
2152            }
2153        }
2154
2155        for (window_id, mut invalidation) in invalidations {
2156            if let Some((presenter, mut window)) =
2157                self.presenters_and_platform_windows.remove(&window_id)
2158            {
2159                {
2160                    let mut presenter = presenter.borrow_mut();
2161                    presenter.invalidate(&mut invalidation, window.appearance(), self);
2162                    let scene = presenter.build_scene(
2163                        window.content_size(),
2164                        window.scale_factor(),
2165                        false,
2166                        self,
2167                    );
2168                    window.present_scene(scene);
2169                }
2170                self.presenters_and_platform_windows
2171                    .insert(window_id, (presenter, window));
2172            }
2173        }
2174    }
2175
2176    fn window_was_resized(&mut self, window_id: usize) {
2177        self.pending_effects
2178            .push_back(Effect::ResizeWindow { window_id });
2179    }
2180
2181    fn window_was_moved(&mut self, window_id: usize) {
2182        self.pending_effects
2183            .push_back(Effect::MoveWindow { window_id });
2184    }
2185
2186    fn window_was_fullscreen_changed(&mut self, window_id: usize, is_fullscreen: bool) {
2187        self.pending_effects.push_back(Effect::FullscreenWindow {
2188            window_id,
2189            is_fullscreen,
2190        });
2191    }
2192
2193    fn window_changed_active_status(&mut self, window_id: usize, is_active: bool) {
2194        self.pending_effects.push_back(Effect::ActivateWindow {
2195            window_id,
2196            is_active,
2197        });
2198    }
2199
2200    fn keystroke(
2201        &mut self,
2202        window_id: usize,
2203        keystroke: Keystroke,
2204        handled_by: Option<Box<dyn Action>>,
2205        result: MatchResult,
2206    ) {
2207        self.pending_effects.push_back(Effect::Keystroke {
2208            window_id,
2209            keystroke,
2210            handled_by,
2211            result,
2212        });
2213    }
2214
2215    pub fn refresh_windows(&mut self) {
2216        self.pending_effects.push_back(Effect::RefreshWindows);
2217    }
2218
2219    pub fn dispatch_action_at(&mut self, window_id: usize, view_id: usize, action: impl Action) {
2220        self.dispatch_any_action_at(window_id, view_id, Box::new(action));
2221    }
2222
2223    pub fn dispatch_any_action_at(
2224        &mut self,
2225        window_id: usize,
2226        view_id: usize,
2227        action: Box<dyn Action>,
2228    ) {
2229        self.pending_effects.push_back(Effect::DispatchActionFrom {
2230            window_id,
2231            view_id,
2232            action,
2233        });
2234    }
2235
2236    fn perform_window_refresh(&mut self) {
2237        let mut presenters = mem::take(&mut self.presenters_and_platform_windows);
2238        for (window_id, (presenter, window)) in &mut presenters {
2239            let mut invalidation = self
2240                .cx
2241                .windows
2242                .get_mut(window_id)
2243                .unwrap()
2244                .invalidation
2245                .take();
2246            let mut presenter = presenter.borrow_mut();
2247            presenter.refresh(
2248                invalidation.as_mut().unwrap_or(&mut Default::default()),
2249                window.appearance(),
2250                self,
2251            );
2252            let scene =
2253                presenter.build_scene(window.content_size(), window.scale_factor(), true, self);
2254            window.present_scene(scene);
2255        }
2256        self.presenters_and_platform_windows = presenters;
2257    }
2258
2259    fn emit_global_event(&mut self, payload: Box<dyn Any>) {
2260        let type_id = (&*payload).type_id();
2261
2262        let mut subscriptions = self.global_subscriptions.clone();
2263        subscriptions.emit(type_id, self, |callback, this| {
2264            callback(payload.as_ref(), this);
2265            true //Always alive
2266        });
2267    }
2268
2269    fn handle_view_notification_effect(
2270        &mut self,
2271        observed_window_id: usize,
2272        observed_view_id: usize,
2273    ) {
2274        if self
2275            .cx
2276            .views
2277            .contains_key(&(observed_window_id, observed_view_id))
2278        {
2279            if let Some(window) = self.cx.windows.get_mut(&observed_window_id) {
2280                window
2281                    .invalidation
2282                    .get_or_insert_with(Default::default)
2283                    .updated
2284                    .insert(observed_view_id);
2285            }
2286
2287            let mut observations = self.observations.clone();
2288            observations.emit(observed_view_id, self, |callback, this| callback(this));
2289        }
2290    }
2291
2292    fn handle_entity_release_effect(&mut self, entity_id: usize, entity: &dyn Any) {
2293        self.release_observations
2294            .clone()
2295            .emit(entity_id, self, |callback, this| {
2296                callback(entity, this);
2297                // Release observations happen one time. So clear the callback by returning false
2298                false
2299            })
2300    }
2301
2302    fn handle_fullscreen_effect(&mut self, window_id: usize, is_fullscreen: bool) {
2303        //Short circuit evaluation if we're already g2g
2304        if self
2305            .cx
2306            .windows
2307            .get(&window_id)
2308            .map(|w| w.is_fullscreen == is_fullscreen)
2309            .unwrap_or(false)
2310        {
2311            return;
2312        }
2313
2314        self.update(|this| {
2315            let window = this.cx.windows.get_mut(&window_id)?;
2316            window.is_fullscreen = is_fullscreen;
2317
2318            let mut fullscreen_observations = this.window_fullscreen_observations.clone();
2319            fullscreen_observations.emit(window_id, this, |callback, this| {
2320                callback(is_fullscreen, this)
2321            });
2322
2323            if let Some((uuid, bounds)) = this
2324                .window_display_uuid(window_id)
2325                .zip(this.window_bounds(window_id))
2326            {
2327                let mut bounds_observations = this.window_bounds_observations.clone();
2328                bounds_observations.emit(window_id, this, |callback, this| {
2329                    callback(bounds, uuid, this)
2330                });
2331            }
2332
2333            Some(())
2334        });
2335    }
2336
2337    fn handle_keystroke_effect(
2338        &mut self,
2339        window_id: usize,
2340        keystroke: Keystroke,
2341        handled_by: Option<Box<dyn Action>>,
2342        result: MatchResult,
2343    ) {
2344        self.update(|this| {
2345            let mut observations = this.keystroke_observations.clone();
2346            observations.emit(window_id, this, {
2347                move |callback, this| callback(&keystroke, &result, handled_by.as_ref(), this)
2348            });
2349        });
2350    }
2351
2352    fn handle_window_activation_effect(&mut self, window_id: usize, active: bool) {
2353        //Short circuit evaluation if we're already g2g
2354        if self
2355            .cx
2356            .windows
2357            .get(&window_id)
2358            .map(|w| w.is_active == active)
2359            .unwrap_or(false)
2360        {
2361            return;
2362        }
2363
2364        self.update(|this| {
2365            let window = this.cx.windows.get_mut(&window_id)?;
2366            window.is_active = active;
2367
2368            //Handle focus
2369            let focused_id = window.focused_view_id?;
2370            for view_id in this.ancestors(window_id, focused_id).collect::<Vec<_>>() {
2371                if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
2372                    if active {
2373                        view.focus_in(this, window_id, view_id, focused_id);
2374                    } else {
2375                        view.focus_out(this, window_id, view_id, focused_id);
2376                    }
2377                    this.cx.views.insert((window_id, view_id), view);
2378                }
2379            }
2380
2381            let mut observations = this.window_activation_observations.clone();
2382            observations.emit(window_id, this, |callback, this| callback(active, this));
2383
2384            Some(())
2385        });
2386    }
2387
2388    fn handle_focus_effect(&mut self, window_id: usize, focused_id: Option<usize>) {
2389        if self
2390            .cx
2391            .windows
2392            .get(&window_id)
2393            .map(|w| w.focused_view_id)
2394            .map_or(false, |cur_focused| cur_focused == focused_id)
2395        {
2396            return;
2397        }
2398
2399        self.update(|this| {
2400            let blurred_id = this.cx.windows.get_mut(&window_id).and_then(|window| {
2401                let blurred_id = window.focused_view_id;
2402                window.focused_view_id = focused_id;
2403                blurred_id
2404            });
2405
2406            let blurred_parents = blurred_id
2407                .map(|blurred_id| this.ancestors(window_id, blurred_id).collect::<Vec<_>>())
2408                .unwrap_or_default();
2409            let focused_parents = focused_id
2410                .map(|focused_id| this.ancestors(window_id, focused_id).collect::<Vec<_>>())
2411                .unwrap_or_default();
2412
2413            if let Some(blurred_id) = blurred_id {
2414                for view_id in blurred_parents.iter().copied() {
2415                    if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
2416                        view.focus_out(this, window_id, view_id, blurred_id);
2417                        this.cx.views.insert((window_id, view_id), view);
2418                    }
2419                }
2420
2421                let mut subscriptions = this.focus_observations.clone();
2422                subscriptions.emit(blurred_id, this, |callback, this| callback(false, this));
2423            }
2424
2425            if let Some(focused_id) = focused_id {
2426                for view_id in focused_parents {
2427                    if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
2428                        view.focus_in(this, window_id, view_id, focused_id);
2429                        this.cx.views.insert((window_id, view_id), view);
2430                    }
2431                }
2432
2433                let mut subscriptions = this.focus_observations.clone();
2434                subscriptions.emit(focused_id, this, |callback, this| callback(true, this));
2435            }
2436        })
2437    }
2438
2439    fn handle_dispatch_action_from_effect(
2440        &mut self,
2441        window_id: usize,
2442        view_id: Option<usize>,
2443        action: &dyn Action,
2444    ) -> bool {
2445        self.update(|this| {
2446            if let Some(view_id) = view_id {
2447                this.halt_action_dispatch = false;
2448                this.visit_dispatch_path(window_id, view_id, |view_id, capture_phase, this| {
2449                    if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
2450                        let type_id = view.as_any().type_id();
2451
2452                        if let Some((name, mut handlers)) = this
2453                            .actions_mut(capture_phase)
2454                            .get_mut(&type_id)
2455                            .and_then(|h| h.remove_entry(&action.id()))
2456                        {
2457                            for handler in handlers.iter_mut().rev() {
2458                                this.halt_action_dispatch = true;
2459                                handler(view.as_mut(), action, this, window_id, view_id);
2460                                if this.halt_action_dispatch {
2461                                    break;
2462                                }
2463                            }
2464                            this.actions_mut(capture_phase)
2465                                .get_mut(&type_id)
2466                                .unwrap()
2467                                .insert(name, handlers);
2468                        }
2469
2470                        this.cx.views.insert((window_id, view_id), view);
2471                    }
2472
2473                    !this.halt_action_dispatch
2474                });
2475            }
2476
2477            if !this.halt_action_dispatch {
2478                this.halt_action_dispatch = this.dispatch_global_action_any(action);
2479            }
2480
2481            this.pending_effects
2482                .push_back(Effect::ActionDispatchNotification {
2483                    action_id: action.id(),
2484                });
2485            this.halt_action_dispatch
2486        })
2487    }
2488
2489    fn handle_action_dispatch_notification_effect(&mut self, action_id: TypeId) {
2490        self.action_dispatch_observations
2491            .clone()
2492            .emit((), self, |callback, this| {
2493                callback(action_id, this);
2494                true
2495            });
2496    }
2497
2498    fn handle_window_should_close_subscription_effect(
2499        &mut self,
2500        window_id: usize,
2501        mut callback: WindowShouldCloseSubscriptionCallback,
2502    ) {
2503        let mut app = self.upgrade();
2504        if let Some((_, window)) = self.presenters_and_platform_windows.get_mut(&window_id) {
2505            window.on_should_close(Box::new(move || app.update(|cx| callback(cx))))
2506        }
2507    }
2508
2509    fn handle_window_moved(&mut self, window_id: usize) {
2510        if let Some((display, bounds)) = self
2511            .window_display_uuid(window_id)
2512            .zip(self.window_bounds(window_id))
2513        {
2514            self.window_bounds_observations
2515                .clone()
2516                .emit(window_id, self, move |callback, this| {
2517                    callback(bounds, display, this);
2518                    true
2519                });
2520        }
2521    }
2522
2523    fn handle_active_labeled_tasks_changed_effect(&mut self) {
2524        self.active_labeled_task_observations
2525            .clone()
2526            .emit((), self, move |callback, this| {
2527                callback(this);
2528                true
2529            });
2530    }
2531
2532    pub fn focus(&mut self, window_id: usize, view_id: Option<usize>) {
2533        self.pending_effects
2534            .push_back(Effect::Focus { window_id, view_id });
2535    }
2536
2537    fn spawn_internal<F, Fut, T>(&mut self, task_name: Option<&'static str>, f: F) -> Task<T>
2538    where
2539        F: FnOnce(AsyncAppContext) -> Fut,
2540        Fut: 'static + Future<Output = T>,
2541        T: 'static,
2542    {
2543        let label_id = task_name.map(|task_name| {
2544            let id = post_inc(&mut self.next_labeled_task_id);
2545            self.active_labeled_tasks.insert(id, task_name);
2546            self.pending_effects
2547                .push_back(Effect::ActiveLabeledTasksChanged);
2548            id
2549        });
2550
2551        let future = f(self.to_async());
2552        let cx = self.to_async();
2553        self.foreground.spawn(async move {
2554            let result = future.await;
2555            let mut cx = cx.0.borrow_mut();
2556
2557            if let Some(completed_label_id) = label_id {
2558                cx.active_labeled_tasks.remove(&completed_label_id);
2559                cx.pending_effects
2560                    .push_back(Effect::ActiveLabeledTasksChanged);
2561            }
2562            cx.flush_effects();
2563            result
2564        })
2565    }
2566
2567    pub fn spawn_labeled<F, Fut, T>(&mut self, task_name: &'static str, f: F) -> Task<T>
2568    where
2569        F: FnOnce(AsyncAppContext) -> Fut,
2570        Fut: 'static + Future<Output = T>,
2571        T: 'static,
2572    {
2573        self.spawn_internal(Some(task_name), f)
2574    }
2575
2576    pub fn spawn<F, Fut, T>(&mut self, f: F) -> Task<T>
2577    where
2578        F: FnOnce(AsyncAppContext) -> Fut,
2579        Fut: 'static + Future<Output = T>,
2580        T: 'static,
2581    {
2582        self.spawn_internal(None, f)
2583    }
2584
2585    pub fn to_async(&self) -> AsyncAppContext {
2586        AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
2587    }
2588
2589    pub fn write_to_clipboard(&self, item: ClipboardItem) {
2590        self.cx.platform.write_to_clipboard(item);
2591    }
2592
2593    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
2594        self.cx.platform.read_from_clipboard()
2595    }
2596
2597    #[cfg(any(test, feature = "test-support"))]
2598    pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
2599        self.cx.ref_counts.lock().leak_detector.clone()
2600    }
2601}
2602
2603impl ReadModel for MutableAppContext {
2604    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2605        if let Some(model) = self.cx.models.get(&handle.model_id) {
2606            model
2607                .as_any()
2608                .downcast_ref()
2609                .expect("downcast is type safe")
2610        } else {
2611            panic!("circular model reference");
2612        }
2613    }
2614}
2615
2616impl UpdateModel for MutableAppContext {
2617    fn update_model<T: Entity, V>(
2618        &mut self,
2619        handle: &ModelHandle<T>,
2620        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
2621    ) -> V {
2622        if let Some(mut model) = self.cx.models.remove(&handle.model_id) {
2623            self.update(|this| {
2624                let mut cx = ModelContext::new(this, handle.model_id);
2625                let result = update(
2626                    model
2627                        .as_any_mut()
2628                        .downcast_mut()
2629                        .expect("downcast is type safe"),
2630                    &mut cx,
2631                );
2632                this.cx.models.insert(handle.model_id, model);
2633                result
2634            })
2635        } else {
2636            panic!("circular model update");
2637        }
2638    }
2639}
2640
2641impl UpgradeModelHandle for MutableAppContext {
2642    fn upgrade_model_handle<T: Entity>(
2643        &self,
2644        handle: &WeakModelHandle<T>,
2645    ) -> Option<ModelHandle<T>> {
2646        self.cx.upgrade_model_handle(handle)
2647    }
2648
2649    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2650        self.cx.model_handle_is_upgradable(handle)
2651    }
2652
2653    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2654        self.cx.upgrade_any_model_handle(handle)
2655    }
2656}
2657
2658impl UpgradeViewHandle for MutableAppContext {
2659    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2660        self.cx.upgrade_view_handle(handle)
2661    }
2662
2663    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
2664        self.cx.upgrade_any_view_handle(handle)
2665    }
2666}
2667
2668impl ReadView for MutableAppContext {
2669    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2670        if let Some(view) = self.cx.views.get(&(handle.window_id, handle.view_id)) {
2671            view.as_any().downcast_ref().expect("downcast is type safe")
2672        } else {
2673            panic!("circular view reference for type {}", type_name::<T>());
2674        }
2675    }
2676}
2677
2678impl UpdateView for MutableAppContext {
2679    fn update_view<T, S>(
2680        &mut self,
2681        handle: &ViewHandle<T>,
2682        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
2683    ) -> S
2684    where
2685        T: View,
2686    {
2687        self.update(|this| {
2688            let mut view = this
2689                .cx
2690                .views
2691                .remove(&(handle.window_id, handle.view_id))
2692                .expect("circular view update");
2693
2694            let mut cx = ViewContext::new(this, handle.window_id, handle.view_id);
2695            let result = update(
2696                view.as_any_mut()
2697                    .downcast_mut()
2698                    .expect("downcast is type safe"),
2699                &mut cx,
2700            );
2701            this.cx
2702                .views
2703                .insert((handle.window_id, handle.view_id), view);
2704            result
2705        })
2706    }
2707}
2708
2709impl AsRef<AppContext> for MutableAppContext {
2710    fn as_ref(&self) -> &AppContext {
2711        &self.cx
2712    }
2713}
2714
2715impl Deref for MutableAppContext {
2716    type Target = AppContext;
2717
2718    fn deref(&self) -> &Self::Target {
2719        &self.cx
2720    }
2721}
2722
2723#[derive(Debug)]
2724pub enum ParentId {
2725    View(usize),
2726    Root,
2727}
2728
2729pub struct AppContext {
2730    models: HashMap<usize, Box<dyn AnyModel>>,
2731    views: HashMap<(usize, usize), Box<dyn AnyView>>,
2732    pub(crate) parents: HashMap<(usize, usize), ParentId>,
2733    windows: HashMap<usize, Window>,
2734    globals: HashMap<TypeId, Box<dyn Any>>,
2735    element_states: HashMap<ElementStateId, Box<dyn Any>>,
2736    background: Arc<executor::Background>,
2737    ref_counts: Arc<Mutex<RefCounts>>,
2738    font_cache: Arc<FontCache>,
2739    platform: Arc<dyn Platform>,
2740}
2741
2742impl AppContext {
2743    pub(crate) fn root_view(&self, window_id: usize) -> Option<AnyViewHandle> {
2744        self.windows
2745            .get(&window_id)
2746            .map(|window| window.root_view.clone())
2747    }
2748
2749    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
2750        self.windows
2751            .get(&window_id)
2752            .map(|window| window.root_view.id())
2753    }
2754
2755    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
2756        self.windows
2757            .get(&window_id)
2758            .and_then(|window| window.focused_view_id)
2759    }
2760
2761    pub fn view_ui_name(&self, window_id: usize, view_id: usize) -> Option<&'static str> {
2762        Some(self.views.get(&(window_id, view_id))?.ui_name())
2763    }
2764
2765    pub fn view_type_id(&self, window_id: usize, view_id: usize) -> Option<TypeId> {
2766        self.views
2767            .get(&(window_id, view_id))
2768            .map(|view| view.as_any().type_id())
2769    }
2770
2771    pub fn background(&self) -> &Arc<executor::Background> {
2772        &self.background
2773    }
2774
2775    pub fn font_cache(&self) -> &Arc<FontCache> {
2776        &self.font_cache
2777    }
2778
2779    pub fn platform(&self) -> &Arc<dyn Platform> {
2780        &self.platform
2781    }
2782
2783    pub fn has_global<T: 'static>(&self) -> bool {
2784        self.globals.contains_key(&TypeId::of::<T>())
2785    }
2786
2787    pub fn global<T: 'static>(&self) -> &T {
2788        if let Some(global) = self.globals.get(&TypeId::of::<T>()) {
2789            global.downcast_ref().unwrap()
2790        } else {
2791            panic!("no global has been added for {}", type_name::<T>());
2792        }
2793    }
2794
2795    /// Returns an iterator over all of the view ids from the passed view up to the root of the window
2796    /// Includes the passed view itself
2797    fn ancestors(&self, window_id: usize, mut view_id: usize) -> impl Iterator<Item = usize> + '_ {
2798        std::iter::once(view_id)
2799            .into_iter()
2800            .chain(std::iter::from_fn(move || {
2801                if let Some(ParentId::View(parent_id)) = self.parents.get(&(window_id, view_id)) {
2802                    view_id = *parent_id;
2803                    Some(view_id)
2804                } else {
2805                    None
2806                }
2807            }))
2808    }
2809
2810    /// Returns the id of the parent of the given view, or none if the given
2811    /// view is the root.
2812    fn parent(&self, window_id: usize, view_id: usize) -> Option<usize> {
2813        if let Some(ParentId::View(view_id)) = self.parents.get(&(window_id, view_id)) {
2814            Some(*view_id)
2815        } else {
2816            None
2817        }
2818    }
2819
2820    pub fn is_child_focused(&self, view: impl Into<AnyViewHandle>) -> bool {
2821        let view = view.into();
2822        if let Some(focused_view_id) = self.focused_view_id(view.window_id) {
2823            self.ancestors(view.window_id, focused_view_id)
2824                .skip(1) // Skip self id
2825                .any(|parent| parent == view.view_id)
2826        } else {
2827            false
2828        }
2829    }
2830}
2831
2832impl ReadModel for AppContext {
2833    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2834        if let Some(model) = self.models.get(&handle.model_id) {
2835            model
2836                .as_any()
2837                .downcast_ref()
2838                .expect("downcast should be type safe")
2839        } else {
2840            panic!("circular model reference");
2841        }
2842    }
2843}
2844
2845impl UpgradeModelHandle for AppContext {
2846    fn upgrade_model_handle<T: Entity>(
2847        &self,
2848        handle: &WeakModelHandle<T>,
2849    ) -> Option<ModelHandle<T>> {
2850        if self.models.contains_key(&handle.model_id) {
2851            Some(ModelHandle::new(handle.model_id, &self.ref_counts))
2852        } else {
2853            None
2854        }
2855    }
2856
2857    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2858        self.models.contains_key(&handle.model_id)
2859    }
2860
2861    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2862        if self.models.contains_key(&handle.model_id) {
2863            Some(AnyModelHandle::new(
2864                handle.model_id,
2865                handle.model_type,
2866                self.ref_counts.clone(),
2867            ))
2868        } else {
2869            None
2870        }
2871    }
2872}
2873
2874impl UpgradeViewHandle for AppContext {
2875    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2876        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2877            Some(ViewHandle::new(
2878                handle.window_id,
2879                handle.view_id,
2880                &self.ref_counts,
2881            ))
2882        } else {
2883            None
2884        }
2885    }
2886
2887    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
2888        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2889            Some(AnyViewHandle::new(
2890                handle.window_id,
2891                handle.view_id,
2892                handle.view_type,
2893                self.ref_counts.clone(),
2894            ))
2895        } else {
2896            None
2897        }
2898    }
2899}
2900
2901impl ReadView for AppContext {
2902    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2903        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
2904            view.as_any()
2905                .downcast_ref()
2906                .expect("downcast should be type safe")
2907        } else {
2908            panic!("circular view reference");
2909        }
2910    }
2911}
2912
2913struct Window {
2914    root_view: AnyViewHandle,
2915    focused_view_id: Option<usize>,
2916    is_active: bool,
2917    is_fullscreen: bool,
2918    invalidation: Option<WindowInvalidation>,
2919}
2920
2921#[derive(Default, Clone)]
2922pub struct WindowInvalidation {
2923    pub updated: HashSet<usize>,
2924    pub removed: Vec<usize>,
2925}
2926
2927pub enum Effect {
2928    Subscription {
2929        entity_id: usize,
2930        subscription_id: usize,
2931        callback: SubscriptionCallback,
2932    },
2933    Event {
2934        entity_id: usize,
2935        payload: Box<dyn Any>,
2936    },
2937    GlobalSubscription {
2938        type_id: TypeId,
2939        subscription_id: usize,
2940        callback: GlobalSubscriptionCallback,
2941    },
2942    GlobalEvent {
2943        payload: Box<dyn Any>,
2944    },
2945    Observation {
2946        entity_id: usize,
2947        subscription_id: usize,
2948        callback: ObservationCallback,
2949    },
2950    ModelNotification {
2951        model_id: usize,
2952    },
2953    ViewNotification {
2954        window_id: usize,
2955        view_id: usize,
2956    },
2957    Deferred {
2958        callback: Box<dyn FnOnce(&mut MutableAppContext)>,
2959        after_window_update: bool,
2960    },
2961    GlobalNotification {
2962        type_id: TypeId,
2963    },
2964    ModelRelease {
2965        model_id: usize,
2966        model: Box<dyn AnyModel>,
2967    },
2968    ViewRelease {
2969        view_id: usize,
2970        view: Box<dyn AnyView>,
2971    },
2972    Focus {
2973        window_id: usize,
2974        view_id: Option<usize>,
2975    },
2976    FocusObservation {
2977        view_id: usize,
2978        subscription_id: usize,
2979        callback: FocusObservationCallback,
2980    },
2981    ResizeWindow {
2982        window_id: usize,
2983    },
2984    MoveWindow {
2985        window_id: usize,
2986    },
2987    ActivateWindow {
2988        window_id: usize,
2989        is_active: bool,
2990    },
2991    WindowActivationObservation {
2992        window_id: usize,
2993        subscription_id: usize,
2994        callback: WindowActivationCallback,
2995    },
2996    FullscreenWindow {
2997        window_id: usize,
2998        is_fullscreen: bool,
2999    },
3000    WindowFullscreenObservation {
3001        window_id: usize,
3002        subscription_id: usize,
3003        callback: WindowFullscreenCallback,
3004    },
3005    WindowBoundsObservation {
3006        window_id: usize,
3007        subscription_id: usize,
3008        callback: WindowBoundsCallback,
3009    },
3010    Keystroke {
3011        window_id: usize,
3012        keystroke: Keystroke,
3013        handled_by: Option<Box<dyn Action>>,
3014        result: MatchResult,
3015    },
3016    RefreshWindows,
3017    DispatchActionFrom {
3018        window_id: usize,
3019        view_id: usize,
3020        action: Box<dyn Action>,
3021    },
3022    ActionDispatchNotification {
3023        action_id: TypeId,
3024    },
3025    WindowShouldCloseSubscription {
3026        window_id: usize,
3027        callback: WindowShouldCloseSubscriptionCallback,
3028    },
3029    ActiveLabeledTasksChanged,
3030    ActiveLabeledTasksObservation {
3031        subscription_id: usize,
3032        callback: ActiveLabeledTasksCallback,
3033    },
3034}
3035
3036impl Debug for Effect {
3037    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3038        match self {
3039            Effect::Subscription {
3040                entity_id,
3041                subscription_id,
3042                ..
3043            } => f
3044                .debug_struct("Effect::Subscribe")
3045                .field("entity_id", entity_id)
3046                .field("subscription_id", subscription_id)
3047                .finish(),
3048            Effect::Event { entity_id, .. } => f
3049                .debug_struct("Effect::Event")
3050                .field("entity_id", entity_id)
3051                .finish(),
3052            Effect::GlobalSubscription {
3053                type_id,
3054                subscription_id,
3055                ..
3056            } => f
3057                .debug_struct("Effect::Subscribe")
3058                .field("type_id", type_id)
3059                .field("subscription_id", subscription_id)
3060                .finish(),
3061            Effect::GlobalEvent { payload, .. } => f
3062                .debug_struct("Effect::GlobalEvent")
3063                .field("type_id", &(&*payload).type_id())
3064                .finish(),
3065            Effect::Observation {
3066                entity_id,
3067                subscription_id,
3068                ..
3069            } => f
3070                .debug_struct("Effect::Observation")
3071                .field("entity_id", entity_id)
3072                .field("subscription_id", subscription_id)
3073                .finish(),
3074            Effect::ModelNotification { model_id } => f
3075                .debug_struct("Effect::ModelNotification")
3076                .field("model_id", model_id)
3077                .finish(),
3078            Effect::ViewNotification { window_id, view_id } => f
3079                .debug_struct("Effect::ViewNotification")
3080                .field("window_id", window_id)
3081                .field("view_id", view_id)
3082                .finish(),
3083            Effect::GlobalNotification { type_id } => f
3084                .debug_struct("Effect::GlobalNotification")
3085                .field("type_id", type_id)
3086                .finish(),
3087            Effect::Deferred { .. } => f.debug_struct("Effect::Deferred").finish(),
3088            Effect::ModelRelease { model_id, .. } => f
3089                .debug_struct("Effect::ModelRelease")
3090                .field("model_id", model_id)
3091                .finish(),
3092            Effect::ViewRelease { view_id, .. } => f
3093                .debug_struct("Effect::ViewRelease")
3094                .field("view_id", view_id)
3095                .finish(),
3096            Effect::Focus { window_id, view_id } => f
3097                .debug_struct("Effect::Focus")
3098                .field("window_id", window_id)
3099                .field("view_id", view_id)
3100                .finish(),
3101            Effect::FocusObservation {
3102                view_id,
3103                subscription_id,
3104                ..
3105            } => f
3106                .debug_struct("Effect::FocusObservation")
3107                .field("view_id", view_id)
3108                .field("subscription_id", subscription_id)
3109                .finish(),
3110            Effect::DispatchActionFrom {
3111                window_id, view_id, ..
3112            } => f
3113                .debug_struct("Effect::DispatchActionFrom")
3114                .field("window_id", window_id)
3115                .field("view_id", view_id)
3116                .finish(),
3117            Effect::ActionDispatchNotification { action_id, .. } => f
3118                .debug_struct("Effect::ActionDispatchNotification")
3119                .field("action_id", action_id)
3120                .finish(),
3121            Effect::ResizeWindow { window_id } => f
3122                .debug_struct("Effect::RefreshWindow")
3123                .field("window_id", window_id)
3124                .finish(),
3125            Effect::MoveWindow { window_id } => f
3126                .debug_struct("Effect::MoveWindow")
3127                .field("window_id", window_id)
3128                .finish(),
3129            Effect::WindowActivationObservation {
3130                window_id,
3131                subscription_id,
3132                ..
3133            } => f
3134                .debug_struct("Effect::WindowActivationObservation")
3135                .field("window_id", window_id)
3136                .field("subscription_id", subscription_id)
3137                .finish(),
3138            Effect::ActivateWindow {
3139                window_id,
3140                is_active,
3141            } => f
3142                .debug_struct("Effect::ActivateWindow")
3143                .field("window_id", window_id)
3144                .field("is_active", is_active)
3145                .finish(),
3146            Effect::FullscreenWindow {
3147                window_id,
3148                is_fullscreen,
3149            } => f
3150                .debug_struct("Effect::FullscreenWindow")
3151                .field("window_id", window_id)
3152                .field("is_fullscreen", is_fullscreen)
3153                .finish(),
3154            Effect::WindowFullscreenObservation {
3155                window_id,
3156                subscription_id,
3157                callback: _,
3158            } => f
3159                .debug_struct("Effect::WindowFullscreenObservation")
3160                .field("window_id", window_id)
3161                .field("subscription_id", subscription_id)
3162                .finish(),
3163
3164            Effect::WindowBoundsObservation {
3165                window_id,
3166                subscription_id,
3167                callback: _,
3168            } => f
3169                .debug_struct("Effect::WindowBoundsObservation")
3170                .field("window_id", window_id)
3171                .field("subscription_id", subscription_id)
3172                .finish(),
3173            Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
3174            Effect::WindowShouldCloseSubscription { window_id, .. } => f
3175                .debug_struct("Effect::WindowShouldCloseSubscription")
3176                .field("window_id", window_id)
3177                .finish(),
3178            Effect::Keystroke {
3179                window_id,
3180                keystroke,
3181                handled_by,
3182                result,
3183            } => f
3184                .debug_struct("Effect::Keystroke")
3185                .field("window_id", window_id)
3186                .field("keystroke", keystroke)
3187                .field(
3188                    "keystroke",
3189                    &handled_by.as_ref().map(|handled_by| handled_by.name()),
3190                )
3191                .field("result", result)
3192                .finish(),
3193            Effect::ActiveLabeledTasksChanged => {
3194                f.debug_struct("Effect::ActiveLabeledTasksChanged").finish()
3195            }
3196            Effect::ActiveLabeledTasksObservation {
3197                subscription_id,
3198                callback: _,
3199            } => f
3200                .debug_struct("Effect::ActiveLabeledTasksObservation")
3201                .field("subscription_id", subscription_id)
3202                .finish(),
3203        }
3204    }
3205}
3206
3207pub trait AnyModel {
3208    fn as_any(&self) -> &dyn Any;
3209    fn as_any_mut(&mut self) -> &mut dyn Any;
3210    fn release(&mut self, cx: &mut MutableAppContext);
3211    fn app_will_quit(
3212        &mut self,
3213        cx: &mut MutableAppContext,
3214    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
3215}
3216
3217impl<T> AnyModel for T
3218where
3219    T: Entity,
3220{
3221    fn as_any(&self) -> &dyn Any {
3222        self
3223    }
3224
3225    fn as_any_mut(&mut self) -> &mut dyn Any {
3226        self
3227    }
3228
3229    fn release(&mut self, cx: &mut MutableAppContext) {
3230        self.release(cx);
3231    }
3232
3233    fn app_will_quit(
3234        &mut self,
3235        cx: &mut MutableAppContext,
3236    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
3237        self.app_will_quit(cx)
3238    }
3239}
3240
3241pub trait AnyView {
3242    fn as_any(&self) -> &dyn Any;
3243    fn as_any_mut(&mut self) -> &mut dyn Any;
3244    fn release(&mut self, cx: &mut MutableAppContext);
3245    fn app_will_quit(
3246        &mut self,
3247        cx: &mut MutableAppContext,
3248    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
3249    fn ui_name(&self) -> &'static str;
3250    fn render(&mut self, params: RenderParams, cx: &mut MutableAppContext) -> ElementBox;
3251    fn focus_in(
3252        &mut self,
3253        cx: &mut MutableAppContext,
3254        window_id: usize,
3255        view_id: usize,
3256        focused_id: usize,
3257    );
3258    fn focus_out(
3259        &mut self,
3260        cx: &mut MutableAppContext,
3261        window_id: usize,
3262        view_id: usize,
3263        focused_id: usize,
3264    );
3265    fn key_down(
3266        &mut self,
3267        event: &KeyDownEvent,
3268        cx: &mut MutableAppContext,
3269        window_id: usize,
3270        view_id: usize,
3271    ) -> bool;
3272    fn key_up(
3273        &mut self,
3274        event: &KeyUpEvent,
3275        cx: &mut MutableAppContext,
3276        window_id: usize,
3277        view_id: usize,
3278    ) -> bool;
3279    fn modifiers_changed(
3280        &mut self,
3281        event: &ModifiersChangedEvent,
3282        cx: &mut MutableAppContext,
3283        window_id: usize,
3284        view_id: usize,
3285    ) -> bool;
3286    fn keymap_context(&self, cx: &AppContext) -> KeymapContext;
3287    fn debug_json(&self, cx: &AppContext) -> serde_json::Value;
3288
3289    fn text_for_range(&self, range: Range<usize>, cx: &AppContext) -> Option<String>;
3290    fn selected_text_range(&self, cx: &AppContext) -> Option<Range<usize>>;
3291    fn marked_text_range(&self, cx: &AppContext) -> Option<Range<usize>>;
3292    fn unmark_text(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
3293    fn replace_text_in_range(
3294        &mut self,
3295        range: Option<Range<usize>>,
3296        text: &str,
3297        cx: &mut MutableAppContext,
3298        window_id: usize,
3299        view_id: usize,
3300    );
3301    fn replace_and_mark_text_in_range(
3302        &mut self,
3303        range: Option<Range<usize>>,
3304        new_text: &str,
3305        new_selected_range: Option<Range<usize>>,
3306        cx: &mut MutableAppContext,
3307        window_id: usize,
3308        view_id: usize,
3309    );
3310    fn any_handle(&self, window_id: usize, view_id: usize, cx: &AppContext) -> AnyViewHandle {
3311        AnyViewHandle::new(
3312            window_id,
3313            view_id,
3314            self.as_any().type_id(),
3315            cx.ref_counts.clone(),
3316        )
3317    }
3318}
3319
3320impl<T> AnyView for T
3321where
3322    T: View,
3323{
3324    fn as_any(&self) -> &dyn Any {
3325        self
3326    }
3327
3328    fn as_any_mut(&mut self) -> &mut dyn Any {
3329        self
3330    }
3331
3332    fn release(&mut self, cx: &mut MutableAppContext) {
3333        self.release(cx);
3334    }
3335
3336    fn app_will_quit(
3337        &mut self,
3338        cx: &mut MutableAppContext,
3339    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
3340        self.app_will_quit(cx)
3341    }
3342
3343    fn ui_name(&self) -> &'static str {
3344        T::ui_name()
3345    }
3346
3347    fn render(&mut self, params: RenderParams, cx: &mut MutableAppContext) -> ElementBox {
3348        View::render(self, &mut RenderContext::new(params, cx))
3349    }
3350
3351    fn focus_in(
3352        &mut self,
3353        cx: &mut MutableAppContext,
3354        window_id: usize,
3355        view_id: usize,
3356        focused_id: usize,
3357    ) {
3358        let mut cx = ViewContext::new(cx, window_id, view_id);
3359        let focused_view_handle: AnyViewHandle = if view_id == focused_id {
3360            cx.handle().into()
3361        } else {
3362            let focused_type = cx
3363                .views
3364                .get(&(window_id, focused_id))
3365                .unwrap()
3366                .as_any()
3367                .type_id();
3368            AnyViewHandle::new(window_id, focused_id, focused_type, cx.ref_counts.clone())
3369        };
3370        View::focus_in(self, focused_view_handle, &mut cx);
3371    }
3372
3373    fn focus_out(
3374        &mut self,
3375        cx: &mut MutableAppContext,
3376        window_id: usize,
3377        view_id: usize,
3378        blurred_id: usize,
3379    ) {
3380        let mut cx = ViewContext::new(cx, window_id, view_id);
3381        let blurred_view_handle: AnyViewHandle = if view_id == blurred_id {
3382            cx.handle().into()
3383        } else {
3384            let blurred_type = cx
3385                .views
3386                .get(&(window_id, blurred_id))
3387                .unwrap()
3388                .as_any()
3389                .type_id();
3390            AnyViewHandle::new(window_id, blurred_id, blurred_type, cx.ref_counts.clone())
3391        };
3392        View::focus_out(self, blurred_view_handle, &mut cx);
3393    }
3394
3395    fn key_down(
3396        &mut self,
3397        event: &KeyDownEvent,
3398        cx: &mut MutableAppContext,
3399        window_id: usize,
3400        view_id: usize,
3401    ) -> bool {
3402        let mut cx = ViewContext::new(cx, window_id, view_id);
3403        View::key_down(self, event, &mut cx)
3404    }
3405
3406    fn key_up(
3407        &mut self,
3408        event: &KeyUpEvent,
3409        cx: &mut MutableAppContext,
3410        window_id: usize,
3411        view_id: usize,
3412    ) -> bool {
3413        let mut cx = ViewContext::new(cx, window_id, view_id);
3414        View::key_up(self, event, &mut cx)
3415    }
3416
3417    fn modifiers_changed(
3418        &mut self,
3419        event: &ModifiersChangedEvent,
3420        cx: &mut MutableAppContext,
3421        window_id: usize,
3422        view_id: usize,
3423    ) -> bool {
3424        let mut cx = ViewContext::new(cx, window_id, view_id);
3425        View::modifiers_changed(self, event, &mut cx)
3426    }
3427
3428    fn keymap_context(&self, cx: &AppContext) -> KeymapContext {
3429        View::keymap_context(self, cx)
3430    }
3431
3432    fn debug_json(&self, cx: &AppContext) -> serde_json::Value {
3433        View::debug_json(self, cx)
3434    }
3435
3436    fn text_for_range(&self, range: Range<usize>, cx: &AppContext) -> Option<String> {
3437        View::text_for_range(self, range, cx)
3438    }
3439
3440    fn selected_text_range(&self, cx: &AppContext) -> Option<Range<usize>> {
3441        View::selected_text_range(self, cx)
3442    }
3443
3444    fn marked_text_range(&self, cx: &AppContext) -> Option<Range<usize>> {
3445        View::marked_text_range(self, cx)
3446    }
3447
3448    fn unmark_text(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
3449        let mut cx = ViewContext::new(cx, window_id, view_id);
3450        View::unmark_text(self, &mut cx)
3451    }
3452
3453    fn replace_text_in_range(
3454        &mut self,
3455        range: Option<Range<usize>>,
3456        text: &str,
3457        cx: &mut MutableAppContext,
3458        window_id: usize,
3459        view_id: usize,
3460    ) {
3461        let mut cx = ViewContext::new(cx, window_id, view_id);
3462        View::replace_text_in_range(self, range, text, &mut cx)
3463    }
3464
3465    fn replace_and_mark_text_in_range(
3466        &mut self,
3467        range: Option<Range<usize>>,
3468        new_text: &str,
3469        new_selected_range: Option<Range<usize>>,
3470        cx: &mut MutableAppContext,
3471        window_id: usize,
3472        view_id: usize,
3473    ) {
3474        let mut cx = ViewContext::new(cx, window_id, view_id);
3475        View::replace_and_mark_text_in_range(self, range, new_text, new_selected_range, &mut cx)
3476    }
3477}
3478
3479pub struct ModelContext<'a, T: ?Sized> {
3480    app: &'a mut MutableAppContext,
3481    model_id: usize,
3482    model_type: PhantomData<T>,
3483    halt_stream: bool,
3484}
3485
3486impl<'a, T: Entity> ModelContext<'a, T> {
3487    fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
3488        Self {
3489            app,
3490            model_id,
3491            model_type: PhantomData,
3492            halt_stream: false,
3493        }
3494    }
3495
3496    pub fn background(&self) -> &Arc<executor::Background> {
3497        &self.app.cx.background
3498    }
3499
3500    pub fn halt_stream(&mut self) {
3501        self.halt_stream = true;
3502    }
3503
3504    pub fn model_id(&self) -> usize {
3505        self.model_id
3506    }
3507
3508    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
3509    where
3510        S: Entity,
3511        F: FnOnce(&mut ModelContext<S>) -> S,
3512    {
3513        self.app.add_model(build_model)
3514    }
3515
3516    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ModelContext<T>)) {
3517        let handle = self.handle();
3518        self.app.defer(move |cx| {
3519            handle.update(cx, |model, cx| {
3520                callback(model, cx);
3521            })
3522        })
3523    }
3524
3525    pub fn emit(&mut self, payload: T::Event) {
3526        self.app.pending_effects.push_back(Effect::Event {
3527            entity_id: self.model_id,
3528            payload: Box::new(payload),
3529        });
3530    }
3531
3532    pub fn notify(&mut self) {
3533        self.app.notify_model(self.model_id);
3534    }
3535
3536    pub fn subscribe<S: Entity, F>(
3537        &mut self,
3538        handle: &ModelHandle<S>,
3539        mut callback: F,
3540    ) -> Subscription
3541    where
3542        S::Event: 'static,
3543        F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
3544    {
3545        let subscriber = self.weak_handle();
3546        self.app
3547            .subscribe_internal(handle, move |emitter, event, cx| {
3548                if let Some(subscriber) = subscriber.upgrade(cx) {
3549                    subscriber.update(cx, |subscriber, cx| {
3550                        callback(subscriber, emitter, event, cx);
3551                    });
3552                    true
3553                } else {
3554                    false
3555                }
3556            })
3557    }
3558
3559    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
3560    where
3561        S: Entity,
3562        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
3563    {
3564        let observer = self.weak_handle();
3565        self.app.observe_internal(handle, move |observed, cx| {
3566            if let Some(observer) = observer.upgrade(cx) {
3567                observer.update(cx, |observer, cx| {
3568                    callback(observer, observed, cx);
3569                });
3570                true
3571            } else {
3572                false
3573            }
3574        })
3575    }
3576
3577    pub fn observe_global<G, F>(&mut self, mut callback: F) -> Subscription
3578    where
3579        G: Any,
3580        F: 'static + FnMut(&mut T, &mut ModelContext<T>),
3581    {
3582        let observer = self.weak_handle();
3583        self.app.observe_global::<G, _>(move |cx| {
3584            if let Some(observer) = observer.upgrade(cx) {
3585                observer.update(cx, |observer, cx| callback(observer, cx));
3586            }
3587        })
3588    }
3589
3590    pub fn observe_release<S, F>(
3591        &mut self,
3592        handle: &ModelHandle<S>,
3593        mut callback: F,
3594    ) -> Subscription
3595    where
3596        S: Entity,
3597        F: 'static + FnMut(&mut T, &S, &mut ModelContext<T>),
3598    {
3599        let observer = self.weak_handle();
3600        self.app.observe_release(handle, move |released, cx| {
3601            if let Some(observer) = observer.upgrade(cx) {
3602                observer.update(cx, |observer, cx| {
3603                    callback(observer, released, cx);
3604                });
3605            }
3606        })
3607    }
3608
3609    pub fn handle(&self) -> ModelHandle<T> {
3610        ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
3611    }
3612
3613    pub fn weak_handle(&self) -> WeakModelHandle<T> {
3614        WeakModelHandle::new(self.model_id)
3615    }
3616
3617    pub fn spawn<F, Fut, S>(&mut self, f: F) -> Task<S>
3618    where
3619        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
3620        Fut: 'static + Future<Output = S>,
3621        S: 'static,
3622    {
3623        let handle = self.handle();
3624        self.app.spawn(|cx| f(handle, cx))
3625    }
3626
3627    pub fn spawn_weak<F, Fut, S>(&mut self, f: F) -> Task<S>
3628    where
3629        F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
3630        Fut: 'static + Future<Output = S>,
3631        S: 'static,
3632    {
3633        let handle = self.weak_handle();
3634        self.app.spawn(|cx| f(handle, cx))
3635    }
3636}
3637
3638impl<M> AsRef<AppContext> for ModelContext<'_, M> {
3639    fn as_ref(&self) -> &AppContext {
3640        &self.app.cx
3641    }
3642}
3643
3644impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
3645    fn as_mut(&mut self) -> &mut MutableAppContext {
3646        self.app
3647    }
3648}
3649
3650impl<M> ReadModel for ModelContext<'_, M> {
3651    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
3652        self.app.read_model(handle)
3653    }
3654}
3655
3656impl<M> UpdateModel for ModelContext<'_, M> {
3657    fn update_model<T: Entity, V>(
3658        &mut self,
3659        handle: &ModelHandle<T>,
3660        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
3661    ) -> V {
3662        self.app.update_model(handle, update)
3663    }
3664}
3665
3666impl<M> UpgradeModelHandle for ModelContext<'_, M> {
3667    fn upgrade_model_handle<T: Entity>(
3668        &self,
3669        handle: &WeakModelHandle<T>,
3670    ) -> Option<ModelHandle<T>> {
3671        self.cx.upgrade_model_handle(handle)
3672    }
3673
3674    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
3675        self.cx.model_handle_is_upgradable(handle)
3676    }
3677
3678    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
3679        self.cx.upgrade_any_model_handle(handle)
3680    }
3681}
3682
3683impl<M> Deref for ModelContext<'_, M> {
3684    type Target = MutableAppContext;
3685
3686    fn deref(&self) -> &Self::Target {
3687        self.app
3688    }
3689}
3690
3691impl<M> DerefMut for ModelContext<'_, M> {
3692    fn deref_mut(&mut self) -> &mut Self::Target {
3693        &mut self.app
3694    }
3695}
3696
3697pub struct ViewContext<'a, T: ?Sized> {
3698    app: &'a mut MutableAppContext,
3699    window_id: usize,
3700    view_id: usize,
3701    view_type: PhantomData<T>,
3702}
3703
3704impl<'a, T: View> ViewContext<'a, T> {
3705    fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
3706        Self {
3707            app,
3708            window_id,
3709            view_id,
3710            view_type: PhantomData,
3711        }
3712    }
3713
3714    pub fn handle(&self) -> ViewHandle<T> {
3715        ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
3716    }
3717
3718    pub fn weak_handle(&self) -> WeakViewHandle<T> {
3719        WeakViewHandle::new(self.window_id, self.view_id)
3720    }
3721
3722    pub fn window_id(&self) -> usize {
3723        self.window_id
3724    }
3725
3726    pub fn view_id(&self) -> usize {
3727        self.view_id
3728    }
3729
3730    pub fn foreground(&self) -> &Rc<executor::Foreground> {
3731        self.app.foreground()
3732    }
3733
3734    pub fn background_executor(&self) -> &Arc<executor::Background> {
3735        &self.app.cx.background
3736    }
3737
3738    pub fn platform(&self) -> Arc<dyn Platform> {
3739        self.app.platform()
3740    }
3741
3742    pub fn show_character_palette(&self) {
3743        self.app.show_character_palette(self.window_id);
3744    }
3745
3746    pub fn minimize_window(&self) {
3747        self.app.minimize_window(self.window_id)
3748    }
3749
3750    pub fn zoom_window(&self) {
3751        self.app.zoom_window(self.window_id)
3752    }
3753
3754    pub fn toggle_full_screen(&self) {
3755        self.app.toggle_window_full_screen(self.window_id)
3756    }
3757
3758    pub fn prompt(
3759        &self,
3760        level: PromptLevel,
3761        msg: &str,
3762        answers: &[&str],
3763    ) -> oneshot::Receiver<usize> {
3764        self.app.prompt(self.window_id, level, msg, answers)
3765    }
3766
3767    pub fn prompt_for_paths(
3768        &self,
3769        options: PathPromptOptions,
3770    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
3771        self.app.prompt_for_paths(options)
3772    }
3773
3774    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
3775        self.app.prompt_for_new_path(directory)
3776    }
3777
3778    pub fn reveal_path(&self, path: &Path) {
3779        self.app.reveal_path(path)
3780    }
3781
3782    pub fn debug_elements(&self) -> crate::json::Value {
3783        self.app.debug_elements(self.window_id).unwrap()
3784    }
3785
3786    pub fn focus<S>(&mut self, handle: S)
3787    where
3788        S: Into<AnyViewHandle>,
3789    {
3790        let handle = handle.into();
3791        self.app.focus(handle.window_id, Some(handle.view_id));
3792    }
3793
3794    pub fn focus_self(&mut self) {
3795        self.app.focus(self.window_id, Some(self.view_id));
3796    }
3797
3798    pub fn is_self_focused(&self) -> bool {
3799        self.app.focused_view_id(self.window_id) == Some(self.view_id)
3800    }
3801
3802    pub fn is_child(&self, view: impl Into<AnyViewHandle>) -> bool {
3803        let view = view.into();
3804        if self.window_id != view.window_id {
3805            return false;
3806        }
3807        self.ancestors(view.window_id, view.view_id)
3808            .skip(1) // Skip self id
3809            .any(|parent| parent == self.view_id)
3810    }
3811
3812    pub fn blur(&mut self) {
3813        self.app.focus(self.window_id, None);
3814    }
3815
3816    pub fn set_window_title(&mut self, title: &str) {
3817        let window_id = self.window_id();
3818        if let Some((_, window)) = self.presenters_and_platform_windows.get_mut(&window_id) {
3819            window.set_title(title);
3820        }
3821    }
3822
3823    pub fn set_window_edited(&mut self, edited: bool) {
3824        let window_id = self.window_id();
3825        if let Some((_, window)) = self.presenters_and_platform_windows.get_mut(&window_id) {
3826            window.set_edited(edited);
3827        }
3828    }
3829
3830    pub fn on_window_should_close<F>(&mut self, mut callback: F)
3831    where
3832        F: 'static + FnMut(&mut T, &mut ViewContext<T>) -> bool,
3833    {
3834        let window_id = self.window_id();
3835        let view = self.weak_handle();
3836        self.pending_effects
3837            .push_back(Effect::WindowShouldCloseSubscription {
3838                window_id,
3839                callback: Box::new(move |cx| {
3840                    if let Some(view) = view.upgrade(cx) {
3841                        view.update(cx, |view, cx| callback(view, cx))
3842                    } else {
3843                        true
3844                    }
3845                }),
3846            });
3847    }
3848
3849    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
3850    where
3851        S: Entity,
3852        F: FnOnce(&mut ModelContext<S>) -> S,
3853    {
3854        self.app.add_model(build_model)
3855    }
3856
3857    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
3858    where
3859        S: View,
3860        F: FnOnce(&mut ViewContext<S>) -> S,
3861    {
3862        self.app
3863            .build_and_insert_view(self.window_id, ParentId::View(self.view_id), |cx| {
3864                Some(build_view(cx))
3865            })
3866            .unwrap()
3867    }
3868
3869    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
3870    where
3871        S: View,
3872        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
3873    {
3874        self.app
3875            .build_and_insert_view(self.window_id, ParentId::View(self.view_id), build_view)
3876    }
3877
3878    pub fn parent(&mut self) -> Option<usize> {
3879        self.cx.parent(self.window_id, self.view_id)
3880    }
3881
3882    pub fn reparent(&mut self, view_handle: impl Into<AnyViewHandle>) {
3883        let view_handle = view_handle.into();
3884        if self.window_id != view_handle.window_id {
3885            panic!("Can't reparent view to a view from a different window");
3886        }
3887        self.cx
3888            .parents
3889            .remove(&(view_handle.window_id, view_handle.view_id));
3890        let new_parent_id = self.view_id;
3891        self.cx.parents.insert(
3892            (view_handle.window_id, view_handle.view_id),
3893            ParentId::View(new_parent_id),
3894        );
3895    }
3896
3897    pub fn replace_root_view<V, F>(&mut self, build_root_view: F) -> ViewHandle<V>
3898    where
3899        V: View,
3900        F: FnOnce(&mut ViewContext<V>) -> V,
3901    {
3902        let window_id = self.window_id;
3903        self.update(|this| {
3904            let root_view = this
3905                .build_and_insert_view(window_id, ParentId::Root, |cx| Some(build_root_view(cx)))
3906                .unwrap();
3907            let window = this.cx.windows.get_mut(&window_id).unwrap();
3908            window.root_view = root_view.clone().into();
3909            window.focused_view_id = Some(root_view.id());
3910            root_view
3911        })
3912    }
3913
3914    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
3915    where
3916        E: Entity,
3917        E::Event: 'static,
3918        H: Handle<E>,
3919        F: 'static + FnMut(&mut T, H, &E::Event, &mut ViewContext<T>),
3920    {
3921        let subscriber = self.weak_handle();
3922        self.app
3923            .subscribe_internal(handle, move |emitter, event, cx| {
3924                if let Some(subscriber) = subscriber.upgrade(cx) {
3925                    subscriber.update(cx, |subscriber, cx| {
3926                        callback(subscriber, emitter, event, cx);
3927                    });
3928                    true
3929                } else {
3930                    false
3931                }
3932            })
3933    }
3934
3935    pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3936    where
3937        E: Entity,
3938        H: Handle<E>,
3939        F: 'static + FnMut(&mut T, H, &mut ViewContext<T>),
3940    {
3941        let observer = self.weak_handle();
3942        self.app.observe_internal(handle, move |observed, cx| {
3943            if let Some(observer) = observer.upgrade(cx) {
3944                observer.update(cx, |observer, cx| {
3945                    callback(observer, observed, cx);
3946                });
3947                true
3948            } else {
3949                false
3950            }
3951        })
3952    }
3953
3954    pub fn observe_global<G, F>(&mut self, mut callback: F) -> Subscription
3955    where
3956        G: Any,
3957        F: 'static + FnMut(&mut T, &mut ViewContext<T>),
3958    {
3959        let observer = self.weak_handle();
3960        self.app.observe_global::<G, _>(move |cx| {
3961            if let Some(observer) = observer.upgrade(cx) {
3962                observer.update(cx, |observer, cx| callback(observer, cx));
3963            }
3964        })
3965    }
3966
3967    pub fn observe_focus<F, V>(&mut self, handle: &ViewHandle<V>, mut callback: F) -> Subscription
3968    where
3969        F: 'static + FnMut(&mut T, ViewHandle<V>, bool, &mut ViewContext<T>),
3970        V: View,
3971    {
3972        let observer = self.weak_handle();
3973        self.app
3974            .observe_focus(handle, move |observed, focused, cx| {
3975                if let Some(observer) = observer.upgrade(cx) {
3976                    observer.update(cx, |observer, cx| {
3977                        callback(observer, observed, focused, cx);
3978                    });
3979                    true
3980                } else {
3981                    false
3982                }
3983            })
3984    }
3985
3986    pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3987    where
3988        E: Entity,
3989        H: Handle<E>,
3990        F: 'static + FnMut(&mut T, &E, &mut ViewContext<T>),
3991    {
3992        let observer = self.weak_handle();
3993        self.app.observe_release(handle, move |released, cx| {
3994            if let Some(observer) = observer.upgrade(cx) {
3995                observer.update(cx, |observer, cx| {
3996                    callback(observer, released, cx);
3997                });
3998            }
3999        })
4000    }
4001
4002    pub fn observe_actions<F>(&mut self, mut callback: F) -> Subscription
4003    where
4004        F: 'static + FnMut(&mut T, TypeId, &mut ViewContext<T>),
4005    {
4006        let observer = self.weak_handle();
4007        self.app.observe_actions(move |action_id, cx| {
4008            if let Some(observer) = observer.upgrade(cx) {
4009                observer.update(cx, |observer, cx| {
4010                    callback(observer, action_id, cx);
4011                });
4012            }
4013        })
4014    }
4015
4016    pub fn observe_window_activation<F>(&mut self, mut callback: F) -> Subscription
4017    where
4018        F: 'static + FnMut(&mut T, bool, &mut ViewContext<T>),
4019    {
4020        let observer = self.weak_handle();
4021        self.app
4022            .observe_window_activation(self.window_id(), move |active, cx| {
4023                if let Some(observer) = observer.upgrade(cx) {
4024                    observer.update(cx, |observer, cx| {
4025                        callback(observer, active, cx);
4026                    });
4027                    true
4028                } else {
4029                    false
4030                }
4031            })
4032    }
4033
4034    pub fn observe_fullscreen<F>(&mut self, mut callback: F) -> Subscription
4035    where
4036        F: 'static + FnMut(&mut T, bool, &mut ViewContext<T>),
4037    {
4038        let observer = self.weak_handle();
4039        self.app
4040            .observe_fullscreen(self.window_id(), move |active, cx| {
4041                if let Some(observer) = observer.upgrade(cx) {
4042                    observer.update(cx, |observer, cx| {
4043                        callback(observer, active, cx);
4044                    });
4045                    true
4046                } else {
4047                    false
4048                }
4049            })
4050    }
4051
4052    pub fn observe_keystrokes<F>(&mut self, mut callback: F) -> Subscription
4053    where
4054        F: 'static
4055            + FnMut(
4056                &mut T,
4057                &Keystroke,
4058                Option<&Box<dyn Action>>,
4059                &MatchResult,
4060                &mut ViewContext<T>,
4061            ) -> bool,
4062    {
4063        let observer = self.weak_handle();
4064        self.app.observe_keystrokes(
4065            self.window_id(),
4066            move |keystroke, result, handled_by, cx| {
4067                if let Some(observer) = observer.upgrade(cx) {
4068                    observer.update(cx, |observer, cx| {
4069                        callback(observer, keystroke, handled_by, result, cx);
4070                    });
4071                    true
4072                } else {
4073                    false
4074                }
4075            },
4076        )
4077    }
4078
4079    pub fn observe_window_bounds<F>(&mut self, mut callback: F) -> Subscription
4080    where
4081        F: 'static + FnMut(&mut T, WindowBounds, Uuid, &mut ViewContext<T>),
4082    {
4083        let observer = self.weak_handle();
4084        self.app
4085            .observe_window_bounds(self.window_id(), move |bounds, display, cx| {
4086                if let Some(observer) = observer.upgrade(cx) {
4087                    observer.update(cx, |observer, cx| {
4088                        callback(observer, bounds, display, cx);
4089                    });
4090                    true
4091                } else {
4092                    false
4093                }
4094            })
4095    }
4096
4097    pub fn observe_active_labeled_tasks<F>(&mut self, mut callback: F) -> Subscription
4098    where
4099        F: 'static + FnMut(&mut T, &mut ViewContext<T>),
4100    {
4101        let observer = self.weak_handle();
4102        self.app.observe_active_labeled_tasks(move |cx| {
4103            if let Some(observer) = observer.upgrade(cx) {
4104                observer.update(cx, |observer, cx| {
4105                    callback(observer, cx);
4106                });
4107                true
4108            } else {
4109                false
4110            }
4111        })
4112    }
4113
4114    pub fn emit(&mut self, payload: T::Event) {
4115        self.app.pending_effects.push_back(Effect::Event {
4116            entity_id: self.view_id,
4117            payload: Box::new(payload),
4118        });
4119    }
4120
4121    pub fn notify(&mut self) {
4122        self.app.notify_view(self.window_id, self.view_id);
4123    }
4124
4125    pub fn dispatch_action(&mut self, action: impl Action) {
4126        self.app
4127            .dispatch_action_at(self.window_id, self.view_id, action)
4128    }
4129
4130    pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
4131        self.app
4132            .dispatch_any_action_at(self.window_id, self.view_id, action)
4133    }
4134
4135    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>)) {
4136        let handle = self.handle();
4137        self.app.defer(move |cx| {
4138            handle.update(cx, |view, cx| {
4139                callback(view, cx);
4140            })
4141        })
4142    }
4143
4144    pub fn after_window_update(
4145        &mut self,
4146        callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>),
4147    ) {
4148        let handle = self.handle();
4149        self.app.after_window_update(move |cx| {
4150            handle.update(cx, |view, cx| {
4151                callback(view, cx);
4152            })
4153        })
4154    }
4155
4156    pub fn propagate_action(&mut self) {
4157        self.app.halt_action_dispatch = false;
4158    }
4159
4160    pub fn spawn_labeled<F, Fut, S>(&mut self, task_label: &'static str, f: F) -> Task<S>
4161    where
4162        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
4163        Fut: 'static + Future<Output = S>,
4164        S: 'static,
4165    {
4166        let handle = self.handle();
4167        self.app.spawn_labeled(task_label, |cx| f(handle, cx))
4168    }
4169
4170    pub fn spawn<F, Fut, S>(&mut self, f: F) -> Task<S>
4171    where
4172        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
4173        Fut: 'static + Future<Output = S>,
4174        S: 'static,
4175    {
4176        let handle = self.handle();
4177        self.app.spawn(|cx| f(handle, cx))
4178    }
4179
4180    pub fn spawn_weak<F, Fut, S>(&mut self, f: F) -> Task<S>
4181    where
4182        F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut,
4183        Fut: 'static + Future<Output = S>,
4184        S: 'static,
4185    {
4186        let handle = self.weak_handle();
4187        self.app.spawn(|cx| f(handle, cx))
4188    }
4189}
4190
4191pub struct RenderParams {
4192    pub window_id: usize,
4193    pub view_id: usize,
4194    pub titlebar_height: f32,
4195    pub hovered_region_ids: HashSet<MouseRegionId>,
4196    pub clicked_region_ids: Option<(HashSet<MouseRegionId>, MouseButton)>,
4197    pub refreshing: bool,
4198    pub appearance: Appearance,
4199}
4200
4201pub struct RenderContext<'a, T: View> {
4202    pub(crate) window_id: usize,
4203    pub(crate) view_id: usize,
4204    pub(crate) view_type: PhantomData<T>,
4205    pub(crate) hovered_region_ids: HashSet<MouseRegionId>,
4206    pub(crate) clicked_region_ids: Option<(HashSet<MouseRegionId>, MouseButton)>,
4207    pub app: &'a mut MutableAppContext,
4208    pub titlebar_height: f32,
4209    pub appearance: Appearance,
4210    pub refreshing: bool,
4211}
4212
4213#[derive(Debug, Clone, Default)]
4214pub struct MouseState {
4215    pub(crate) hovered: bool,
4216    pub(crate) clicked: Option<MouseButton>,
4217    pub(crate) accessed_hovered: bool,
4218    pub(crate) accessed_clicked: bool,
4219}
4220
4221impl MouseState {
4222    pub fn hovered(&mut self) -> bool {
4223        self.accessed_hovered = true;
4224        self.hovered
4225    }
4226
4227    pub fn clicked(&mut self) -> Option<MouseButton> {
4228        self.accessed_clicked = true;
4229        self.clicked
4230    }
4231
4232    pub fn accessed_hovered(&self) -> bool {
4233        self.accessed_hovered
4234    }
4235
4236    pub fn accessed_clicked(&self) -> bool {
4237        self.accessed_clicked
4238    }
4239}
4240
4241impl<'a, V: View> RenderContext<'a, V> {
4242    fn new(params: RenderParams, app: &'a mut MutableAppContext) -> Self {
4243        Self {
4244            app,
4245            window_id: params.window_id,
4246            view_id: params.view_id,
4247            view_type: PhantomData,
4248            titlebar_height: params.titlebar_height,
4249            hovered_region_ids: params.hovered_region_ids.clone(),
4250            clicked_region_ids: params.clicked_region_ids.clone(),
4251            refreshing: params.refreshing,
4252            appearance: params.appearance,
4253        }
4254    }
4255
4256    pub fn handle(&self) -> WeakViewHandle<V> {
4257        WeakViewHandle::new(self.window_id, self.view_id)
4258    }
4259
4260    pub fn window_id(&self) -> usize {
4261        self.window_id
4262    }
4263
4264    pub fn view_id(&self) -> usize {
4265        self.view_id
4266    }
4267
4268    pub fn mouse_state<Tag: 'static>(&self, region_id: usize) -> MouseState {
4269        let region_id = MouseRegionId::new::<Tag>(self.view_id, region_id);
4270        MouseState {
4271            hovered: self.hovered_region_ids.contains(&region_id),
4272            clicked: self.clicked_region_ids.as_ref().and_then(|(ids, button)| {
4273                if ids.contains(&region_id) {
4274                    Some(*button)
4275                } else {
4276                    None
4277                }
4278            }),
4279            accessed_hovered: false,
4280            accessed_clicked: false,
4281        }
4282    }
4283
4284    pub fn element_state<Tag: 'static, T: 'static>(
4285        &mut self,
4286        element_id: usize,
4287        initial: T,
4288    ) -> ElementStateHandle<T> {
4289        let id = ElementStateId {
4290            view_id: self.view_id(),
4291            element_id,
4292            tag: TypeId::of::<Tag>(),
4293        };
4294        self.cx
4295            .element_states
4296            .entry(id)
4297            .or_insert_with(|| Box::new(initial));
4298        ElementStateHandle::new(id, self.frame_count, &self.cx.ref_counts)
4299    }
4300
4301    pub fn default_element_state<Tag: 'static, T: 'static + Default>(
4302        &mut self,
4303        element_id: usize,
4304    ) -> ElementStateHandle<T> {
4305        self.element_state::<Tag, T>(element_id, T::default())
4306    }
4307}
4308
4309impl AsRef<AppContext> for &AppContext {
4310    fn as_ref(&self) -> &AppContext {
4311        self
4312    }
4313}
4314
4315impl<V: View> Deref for RenderContext<'_, V> {
4316    type Target = MutableAppContext;
4317
4318    fn deref(&self) -> &Self::Target {
4319        self.app
4320    }
4321}
4322
4323impl<V: View> DerefMut for RenderContext<'_, V> {
4324    fn deref_mut(&mut self) -> &mut Self::Target {
4325        self.app
4326    }
4327}
4328
4329impl<V: View> ReadModel for RenderContext<'_, V> {
4330    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
4331        self.app.read_model(handle)
4332    }
4333}
4334
4335impl<V: View> UpdateModel for RenderContext<'_, V> {
4336    fn update_model<T: Entity, O>(
4337        &mut self,
4338        handle: &ModelHandle<T>,
4339        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
4340    ) -> O {
4341        self.app.update_model(handle, update)
4342    }
4343}
4344
4345impl<V: View> ReadView for RenderContext<'_, V> {
4346    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
4347        self.app.read_view(handle)
4348    }
4349}
4350
4351impl<M> AsRef<AppContext> for ViewContext<'_, M> {
4352    fn as_ref(&self) -> &AppContext {
4353        &self.app.cx
4354    }
4355}
4356
4357impl<M> Deref for ViewContext<'_, M> {
4358    type Target = MutableAppContext;
4359
4360    fn deref(&self) -> &Self::Target {
4361        self.app
4362    }
4363}
4364
4365impl<M> DerefMut for ViewContext<'_, M> {
4366    fn deref_mut(&mut self) -> &mut Self::Target {
4367        &mut self.app
4368    }
4369}
4370
4371impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
4372    fn as_mut(&mut self) -> &mut MutableAppContext {
4373        self.app
4374    }
4375}
4376
4377impl<V> ReadModel for ViewContext<'_, V> {
4378    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
4379        self.app.read_model(handle)
4380    }
4381}
4382
4383impl<V> UpgradeModelHandle for ViewContext<'_, V> {
4384    fn upgrade_model_handle<T: Entity>(
4385        &self,
4386        handle: &WeakModelHandle<T>,
4387    ) -> Option<ModelHandle<T>> {
4388        self.cx.upgrade_model_handle(handle)
4389    }
4390
4391    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
4392        self.cx.model_handle_is_upgradable(handle)
4393    }
4394
4395    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
4396        self.cx.upgrade_any_model_handle(handle)
4397    }
4398}
4399
4400impl<V> UpgradeViewHandle for ViewContext<'_, V> {
4401    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
4402        self.cx.upgrade_view_handle(handle)
4403    }
4404
4405    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
4406        self.cx.upgrade_any_view_handle(handle)
4407    }
4408}
4409
4410impl<V: View> UpgradeViewHandle for RenderContext<'_, V> {
4411    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
4412        self.cx.upgrade_view_handle(handle)
4413    }
4414
4415    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
4416        self.cx.upgrade_any_view_handle(handle)
4417    }
4418}
4419
4420impl<V: View> UpdateModel for ViewContext<'_, V> {
4421    fn update_model<T: Entity, O>(
4422        &mut self,
4423        handle: &ModelHandle<T>,
4424        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
4425    ) -> O {
4426        self.app.update_model(handle, update)
4427    }
4428}
4429
4430impl<V: View> ReadView for ViewContext<'_, V> {
4431    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
4432        self.app.read_view(handle)
4433    }
4434}
4435
4436impl<V: View> UpdateView for ViewContext<'_, V> {
4437    fn update_view<T, S>(
4438        &mut self,
4439        handle: &ViewHandle<T>,
4440        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
4441    ) -> S
4442    where
4443        T: View,
4444    {
4445        self.app.update_view(handle, update)
4446    }
4447}
4448
4449pub trait Handle<T> {
4450    type Weak: 'static;
4451    fn id(&self) -> usize;
4452    fn location(&self) -> EntityLocation;
4453    fn downgrade(&self) -> Self::Weak;
4454    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4455    where
4456        Self: Sized;
4457}
4458
4459pub trait WeakHandle {
4460    fn id(&self) -> usize;
4461}
4462
4463#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
4464pub enum EntityLocation {
4465    Model(usize),
4466    View(usize, usize),
4467}
4468
4469pub struct ModelHandle<T: Entity> {
4470    model_id: usize,
4471    model_type: PhantomData<T>,
4472    ref_counts: Arc<Mutex<RefCounts>>,
4473
4474    #[cfg(any(test, feature = "test-support"))]
4475    handle_id: usize,
4476}
4477
4478impl<T: Entity> ModelHandle<T> {
4479    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4480        ref_counts.lock().inc_model(model_id);
4481
4482        #[cfg(any(test, feature = "test-support"))]
4483        let handle_id = ref_counts
4484            .lock()
4485            .leak_detector
4486            .lock()
4487            .handle_created(Some(type_name::<T>()), model_id);
4488
4489        Self {
4490            model_id,
4491            model_type: PhantomData,
4492            ref_counts: ref_counts.clone(),
4493
4494            #[cfg(any(test, feature = "test-support"))]
4495            handle_id,
4496        }
4497    }
4498
4499    pub fn downgrade(&self) -> WeakModelHandle<T> {
4500        WeakModelHandle::new(self.model_id)
4501    }
4502
4503    pub fn id(&self) -> usize {
4504        self.model_id
4505    }
4506
4507    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
4508        cx.read_model(self)
4509    }
4510
4511    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
4512    where
4513        C: ReadModelWith,
4514        F: FnOnce(&T, &AppContext) -> S,
4515    {
4516        let mut read = Some(read);
4517        cx.read_model_with(self, &mut |model, cx| {
4518            let read = read.take().unwrap();
4519            read(model, cx)
4520        })
4521    }
4522
4523    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
4524    where
4525        C: UpdateModel,
4526        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
4527    {
4528        let mut update = Some(update);
4529        cx.update_model(self, &mut |model, cx| {
4530            let update = update.take().unwrap();
4531            update(model, cx)
4532        })
4533    }
4534}
4535
4536impl<T: Entity> Clone for ModelHandle<T> {
4537    fn clone(&self) -> Self {
4538        Self::new(self.model_id, &self.ref_counts)
4539    }
4540}
4541
4542impl<T: Entity> PartialEq for ModelHandle<T> {
4543    fn eq(&self, other: &Self) -> bool {
4544        self.model_id == other.model_id
4545    }
4546}
4547
4548impl<T: Entity> Eq for ModelHandle<T> {}
4549
4550impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
4551    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
4552        self.model_id == other.model_id
4553    }
4554}
4555
4556impl<T: Entity> Hash for ModelHandle<T> {
4557    fn hash<H: Hasher>(&self, state: &mut H) {
4558        self.model_id.hash(state);
4559    }
4560}
4561
4562impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
4563    fn borrow(&self) -> &usize {
4564        &self.model_id
4565    }
4566}
4567
4568impl<T: Entity> Debug for ModelHandle<T> {
4569    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4570        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
4571            .field(&self.model_id)
4572            .finish()
4573    }
4574}
4575
4576unsafe impl<T: Entity> Send for ModelHandle<T> {}
4577unsafe impl<T: Entity> Sync for ModelHandle<T> {}
4578
4579impl<T: Entity> Drop for ModelHandle<T> {
4580    fn drop(&mut self) {
4581        let mut ref_counts = self.ref_counts.lock();
4582        ref_counts.dec_model(self.model_id);
4583
4584        #[cfg(any(test, feature = "test-support"))]
4585        ref_counts
4586            .leak_detector
4587            .lock()
4588            .handle_dropped(self.model_id, self.handle_id);
4589    }
4590}
4591
4592impl<T: Entity> Handle<T> for ModelHandle<T> {
4593    type Weak = WeakModelHandle<T>;
4594
4595    fn id(&self) -> usize {
4596        self.model_id
4597    }
4598
4599    fn location(&self) -> EntityLocation {
4600        EntityLocation::Model(self.model_id)
4601    }
4602
4603    fn downgrade(&self) -> Self::Weak {
4604        self.downgrade()
4605    }
4606
4607    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4608    where
4609        Self: Sized,
4610    {
4611        weak.upgrade(cx)
4612    }
4613}
4614
4615pub struct WeakModelHandle<T> {
4616    model_id: usize,
4617    model_type: PhantomData<T>,
4618}
4619
4620impl<T> WeakHandle for WeakModelHandle<T> {
4621    fn id(&self) -> usize {
4622        self.model_id
4623    }
4624}
4625
4626unsafe impl<T> Send for WeakModelHandle<T> {}
4627unsafe impl<T> Sync for WeakModelHandle<T> {}
4628
4629impl<T: Entity> WeakModelHandle<T> {
4630    fn new(model_id: usize) -> Self {
4631        Self {
4632            model_id,
4633            model_type: PhantomData,
4634        }
4635    }
4636
4637    pub fn id(&self) -> usize {
4638        self.model_id
4639    }
4640
4641    pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
4642        cx.model_handle_is_upgradable(self)
4643    }
4644
4645    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
4646        cx.upgrade_model_handle(self)
4647    }
4648}
4649
4650impl<T> Hash for WeakModelHandle<T> {
4651    fn hash<H: Hasher>(&self, state: &mut H) {
4652        self.model_id.hash(state)
4653    }
4654}
4655
4656impl<T> PartialEq for WeakModelHandle<T> {
4657    fn eq(&self, other: &Self) -> bool {
4658        self.model_id == other.model_id
4659    }
4660}
4661
4662impl<T> Eq for WeakModelHandle<T> {}
4663
4664impl<T: Entity> PartialEq<ModelHandle<T>> for WeakModelHandle<T> {
4665    fn eq(&self, other: &ModelHandle<T>) -> bool {
4666        self.model_id == other.model_id
4667    }
4668}
4669
4670impl<T> Clone for WeakModelHandle<T> {
4671    fn clone(&self) -> Self {
4672        Self {
4673            model_id: self.model_id,
4674            model_type: PhantomData,
4675        }
4676    }
4677}
4678
4679impl<T> Copy for WeakModelHandle<T> {}
4680
4681pub struct ViewHandle<T> {
4682    window_id: usize,
4683    view_id: usize,
4684    view_type: PhantomData<T>,
4685    ref_counts: Arc<Mutex<RefCounts>>,
4686    #[cfg(any(test, feature = "test-support"))]
4687    handle_id: usize,
4688}
4689
4690impl<T: View> ViewHandle<T> {
4691    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4692        ref_counts.lock().inc_view(window_id, view_id);
4693        #[cfg(any(test, feature = "test-support"))]
4694        let handle_id = ref_counts
4695            .lock()
4696            .leak_detector
4697            .lock()
4698            .handle_created(Some(type_name::<T>()), view_id);
4699
4700        Self {
4701            window_id,
4702            view_id,
4703            view_type: PhantomData,
4704            ref_counts: ref_counts.clone(),
4705
4706            #[cfg(any(test, feature = "test-support"))]
4707            handle_id,
4708        }
4709    }
4710
4711    pub fn downgrade(&self) -> WeakViewHandle<T> {
4712        WeakViewHandle::new(self.window_id, self.view_id)
4713    }
4714
4715    pub fn window_id(&self) -> usize {
4716        self.window_id
4717    }
4718
4719    pub fn id(&self) -> usize {
4720        self.view_id
4721    }
4722
4723    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
4724        cx.read_view(self)
4725    }
4726
4727    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
4728    where
4729        C: ReadViewWith,
4730        F: FnOnce(&T, &AppContext) -> S,
4731    {
4732        let mut read = Some(read);
4733        cx.read_view_with(self, &mut |view, cx| {
4734            let read = read.take().unwrap();
4735            read(view, cx)
4736        })
4737    }
4738
4739    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
4740    where
4741        C: UpdateView,
4742        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
4743    {
4744        let mut update = Some(update);
4745        cx.update_view(self, &mut |view, cx| {
4746            let update = update.take().unwrap();
4747            update(view, cx)
4748        })
4749    }
4750
4751    pub fn defer<C, F>(&self, cx: &mut C, update: F)
4752    where
4753        C: AsMut<MutableAppContext>,
4754        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
4755    {
4756        let this = self.clone();
4757        cx.as_mut().defer(move |cx| {
4758            this.update(cx, |view, cx| update(view, cx));
4759        });
4760    }
4761
4762    pub fn is_focused(&self, cx: &AppContext) -> bool {
4763        cx.focused_view_id(self.window_id)
4764            .map_or(false, |focused_id| focused_id == self.view_id)
4765    }
4766}
4767
4768impl<T: View> Clone for ViewHandle<T> {
4769    fn clone(&self) -> Self {
4770        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
4771    }
4772}
4773
4774impl<T> PartialEq for ViewHandle<T> {
4775    fn eq(&self, other: &Self) -> bool {
4776        self.window_id == other.window_id && self.view_id == other.view_id
4777    }
4778}
4779
4780impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
4781    fn eq(&self, other: &WeakViewHandle<T>) -> bool {
4782        self.window_id == other.window_id && self.view_id == other.view_id
4783    }
4784}
4785
4786impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
4787    fn eq(&self, other: &ViewHandle<T>) -> bool {
4788        self.window_id == other.window_id && self.view_id == other.view_id
4789    }
4790}
4791
4792impl<T> Eq for ViewHandle<T> {}
4793
4794impl<T> Hash for ViewHandle<T> {
4795    fn hash<H: Hasher>(&self, state: &mut H) {
4796        self.window_id.hash(state);
4797        self.view_id.hash(state);
4798    }
4799}
4800
4801impl<T> Debug for ViewHandle<T> {
4802    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4803        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
4804            .field("window_id", &self.window_id)
4805            .field("view_id", &self.view_id)
4806            .finish()
4807    }
4808}
4809
4810impl<T> Drop for ViewHandle<T> {
4811    fn drop(&mut self) {
4812        self.ref_counts
4813            .lock()
4814            .dec_view(self.window_id, self.view_id);
4815        #[cfg(any(test, feature = "test-support"))]
4816        self.ref_counts
4817            .lock()
4818            .leak_detector
4819            .lock()
4820            .handle_dropped(self.view_id, self.handle_id);
4821    }
4822}
4823
4824impl<T: View> Handle<T> for ViewHandle<T> {
4825    type Weak = WeakViewHandle<T>;
4826
4827    fn id(&self) -> usize {
4828        self.view_id
4829    }
4830
4831    fn location(&self) -> EntityLocation {
4832        EntityLocation::View(self.window_id, self.view_id)
4833    }
4834
4835    fn downgrade(&self) -> Self::Weak {
4836        self.downgrade()
4837    }
4838
4839    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4840    where
4841        Self: Sized,
4842    {
4843        weak.upgrade(cx)
4844    }
4845}
4846
4847pub struct AnyViewHandle {
4848    window_id: usize,
4849    view_id: usize,
4850    view_type: TypeId,
4851    ref_counts: Arc<Mutex<RefCounts>>,
4852
4853    #[cfg(any(test, feature = "test-support"))]
4854    handle_id: usize,
4855}
4856
4857impl AnyViewHandle {
4858    fn new(
4859        window_id: usize,
4860        view_id: usize,
4861        view_type: TypeId,
4862        ref_counts: Arc<Mutex<RefCounts>>,
4863    ) -> Self {
4864        ref_counts.lock().inc_view(window_id, view_id);
4865
4866        #[cfg(any(test, feature = "test-support"))]
4867        let handle_id = ref_counts
4868            .lock()
4869            .leak_detector
4870            .lock()
4871            .handle_created(None, view_id);
4872
4873        Self {
4874            window_id,
4875            view_id,
4876            view_type,
4877            ref_counts,
4878            #[cfg(any(test, feature = "test-support"))]
4879            handle_id,
4880        }
4881    }
4882
4883    pub fn window_id(&self) -> usize {
4884        self.window_id
4885    }
4886
4887    pub fn id(&self) -> usize {
4888        self.view_id
4889    }
4890
4891    pub fn is<T: 'static>(&self) -> bool {
4892        TypeId::of::<T>() == self.view_type
4893    }
4894
4895    pub fn is_focused(&self, cx: &AppContext) -> bool {
4896        cx.focused_view_id(self.window_id)
4897            .map_or(false, |focused_id| focused_id == self.view_id)
4898    }
4899
4900    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
4901        if self.is::<T>() {
4902            let result = Some(ViewHandle {
4903                window_id: self.window_id,
4904                view_id: self.view_id,
4905                ref_counts: self.ref_counts.clone(),
4906                view_type: PhantomData,
4907                #[cfg(any(test, feature = "test-support"))]
4908                handle_id: self.handle_id,
4909            });
4910            unsafe {
4911                Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
4912            }
4913            std::mem::forget(self);
4914            result
4915        } else {
4916            None
4917        }
4918    }
4919
4920    pub fn downgrade(&self) -> AnyWeakViewHandle {
4921        AnyWeakViewHandle {
4922            window_id: self.window_id,
4923            view_id: self.view_id,
4924            view_type: self.view_type,
4925        }
4926    }
4927
4928    pub fn view_type(&self) -> TypeId {
4929        self.view_type
4930    }
4931
4932    pub fn debug_json(&self, cx: &AppContext) -> serde_json::Value {
4933        cx.views
4934            .get(&(self.window_id, self.view_id))
4935            .map_or_else(|| serde_json::Value::Null, |view| view.debug_json(cx))
4936    }
4937}
4938
4939impl Clone for AnyViewHandle {
4940    fn clone(&self) -> Self {
4941        Self::new(
4942            self.window_id,
4943            self.view_id,
4944            self.view_type,
4945            self.ref_counts.clone(),
4946        )
4947    }
4948}
4949
4950impl From<&AnyViewHandle> for AnyViewHandle {
4951    fn from(handle: &AnyViewHandle) -> Self {
4952        handle.clone()
4953    }
4954}
4955
4956impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
4957    fn from(handle: &ViewHandle<T>) -> Self {
4958        Self::new(
4959            handle.window_id,
4960            handle.view_id,
4961            TypeId::of::<T>(),
4962            handle.ref_counts.clone(),
4963        )
4964    }
4965}
4966
4967impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
4968    fn from(handle: ViewHandle<T>) -> Self {
4969        let any_handle = AnyViewHandle {
4970            window_id: handle.window_id,
4971            view_id: handle.view_id,
4972            view_type: TypeId::of::<T>(),
4973            ref_counts: handle.ref_counts.clone(),
4974            #[cfg(any(test, feature = "test-support"))]
4975            handle_id: handle.handle_id,
4976        };
4977
4978        unsafe {
4979            Arc::decrement_strong_count(Arc::as_ptr(&handle.ref_counts));
4980        }
4981        std::mem::forget(handle);
4982        any_handle
4983    }
4984}
4985
4986impl<T> PartialEq<ViewHandle<T>> for AnyViewHandle {
4987    fn eq(&self, other: &ViewHandle<T>) -> bool {
4988        self.window_id == other.window_id && self.view_id == other.view_id
4989    }
4990}
4991
4992impl Drop for AnyViewHandle {
4993    fn drop(&mut self) {
4994        self.ref_counts
4995            .lock()
4996            .dec_view(self.window_id, self.view_id);
4997        #[cfg(any(test, feature = "test-support"))]
4998        self.ref_counts
4999            .lock()
5000            .leak_detector
5001            .lock()
5002            .handle_dropped(self.view_id, self.handle_id);
5003    }
5004}
5005
5006pub struct AnyModelHandle {
5007    model_id: usize,
5008    model_type: TypeId,
5009    ref_counts: Arc<Mutex<RefCounts>>,
5010
5011    #[cfg(any(test, feature = "test-support"))]
5012    handle_id: usize,
5013}
5014
5015impl AnyModelHandle {
5016    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
5017        ref_counts.lock().inc_model(model_id);
5018
5019        #[cfg(any(test, feature = "test-support"))]
5020        let handle_id = ref_counts
5021            .lock()
5022            .leak_detector
5023            .lock()
5024            .handle_created(None, model_id);
5025
5026        Self {
5027            model_id,
5028            model_type,
5029            ref_counts,
5030
5031            #[cfg(any(test, feature = "test-support"))]
5032            handle_id,
5033        }
5034    }
5035
5036    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
5037        if self.is::<T>() {
5038            let result = Some(ModelHandle {
5039                model_id: self.model_id,
5040                model_type: PhantomData,
5041                ref_counts: self.ref_counts.clone(),
5042
5043                #[cfg(any(test, feature = "test-support"))]
5044                handle_id: self.handle_id,
5045            });
5046            unsafe {
5047                Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
5048            }
5049            std::mem::forget(self);
5050            result
5051        } else {
5052            None
5053        }
5054    }
5055
5056    pub fn downgrade(&self) -> AnyWeakModelHandle {
5057        AnyWeakModelHandle {
5058            model_id: self.model_id,
5059            model_type: self.model_type,
5060        }
5061    }
5062
5063    pub fn is<T: Entity>(&self) -> bool {
5064        self.model_type == TypeId::of::<T>()
5065    }
5066
5067    pub fn model_type(&self) -> TypeId {
5068        self.model_type
5069    }
5070}
5071
5072impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
5073    fn from(handle: ModelHandle<T>) -> Self {
5074        Self::new(
5075            handle.model_id,
5076            TypeId::of::<T>(),
5077            handle.ref_counts.clone(),
5078        )
5079    }
5080}
5081
5082impl Clone for AnyModelHandle {
5083    fn clone(&self) -> Self {
5084        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
5085    }
5086}
5087
5088impl Drop for AnyModelHandle {
5089    fn drop(&mut self) {
5090        let mut ref_counts = self.ref_counts.lock();
5091        ref_counts.dec_model(self.model_id);
5092
5093        #[cfg(any(test, feature = "test-support"))]
5094        ref_counts
5095            .leak_detector
5096            .lock()
5097            .handle_dropped(self.model_id, self.handle_id);
5098    }
5099}
5100
5101#[derive(Hash, PartialEq, Eq, Debug)]
5102pub struct AnyWeakModelHandle {
5103    model_id: usize,
5104    model_type: TypeId,
5105}
5106
5107impl AnyWeakModelHandle {
5108    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
5109        cx.upgrade_any_model_handle(self)
5110    }
5111    pub fn model_type(&self) -> TypeId {
5112        self.model_type
5113    }
5114
5115    fn is<T: 'static>(&self) -> bool {
5116        TypeId::of::<T>() == self.model_type
5117    }
5118
5119    pub fn downcast<T: Entity>(&self) -> Option<WeakModelHandle<T>> {
5120        if self.is::<T>() {
5121            let result = Some(WeakModelHandle {
5122                model_id: self.model_id,
5123                model_type: PhantomData,
5124            });
5125
5126            result
5127        } else {
5128            None
5129        }
5130    }
5131}
5132
5133impl<T: Entity> From<WeakModelHandle<T>> for AnyWeakModelHandle {
5134    fn from(handle: WeakModelHandle<T>) -> Self {
5135        AnyWeakModelHandle {
5136            model_id: handle.model_id,
5137            model_type: TypeId::of::<T>(),
5138        }
5139    }
5140}
5141
5142#[derive(Debug, Copy)]
5143pub struct WeakViewHandle<T> {
5144    window_id: usize,
5145    view_id: usize,
5146    view_type: PhantomData<T>,
5147}
5148
5149impl<T> WeakHandle for WeakViewHandle<T> {
5150    fn id(&self) -> usize {
5151        self.view_id
5152    }
5153}
5154
5155impl<T: View> WeakViewHandle<T> {
5156    fn new(window_id: usize, view_id: usize) -> Self {
5157        Self {
5158            window_id,
5159            view_id,
5160            view_type: PhantomData,
5161        }
5162    }
5163
5164    pub fn id(&self) -> usize {
5165        self.view_id
5166    }
5167
5168    pub fn window_id(&self) -> usize {
5169        self.window_id
5170    }
5171
5172    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
5173        cx.upgrade_view_handle(self)
5174    }
5175}
5176
5177impl<T> Clone for WeakViewHandle<T> {
5178    fn clone(&self) -> Self {
5179        Self {
5180            window_id: self.window_id,
5181            view_id: self.view_id,
5182            view_type: PhantomData,
5183        }
5184    }
5185}
5186
5187impl<T> PartialEq for WeakViewHandle<T> {
5188    fn eq(&self, other: &Self) -> bool {
5189        self.window_id == other.window_id && self.view_id == other.view_id
5190    }
5191}
5192
5193impl<T> Eq for WeakViewHandle<T> {}
5194
5195impl<T> Hash for WeakViewHandle<T> {
5196    fn hash<H: Hasher>(&self, state: &mut H) {
5197        self.window_id.hash(state);
5198        self.view_id.hash(state);
5199    }
5200}
5201
5202pub struct AnyWeakViewHandle {
5203    window_id: usize,
5204    view_id: usize,
5205    view_type: TypeId,
5206}
5207
5208impl AnyWeakViewHandle {
5209    pub fn id(&self) -> usize {
5210        self.view_id
5211    }
5212
5213    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<AnyViewHandle> {
5214        cx.upgrade_any_view_handle(self)
5215    }
5216}
5217
5218impl<T: View> From<WeakViewHandle<T>> for AnyWeakViewHandle {
5219    fn from(handle: WeakViewHandle<T>) -> Self {
5220        AnyWeakViewHandle {
5221            window_id: handle.window_id,
5222            view_id: handle.view_id,
5223            view_type: TypeId::of::<T>(),
5224        }
5225    }
5226}
5227
5228#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
5229pub struct ElementStateId {
5230    view_id: usize,
5231    element_id: usize,
5232    tag: TypeId,
5233}
5234
5235pub struct ElementStateHandle<T> {
5236    value_type: PhantomData<T>,
5237    id: ElementStateId,
5238    ref_counts: Weak<Mutex<RefCounts>>,
5239}
5240
5241impl<T: 'static> ElementStateHandle<T> {
5242    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
5243        ref_counts.lock().inc_element_state(id, frame_id);
5244        Self {
5245            value_type: PhantomData,
5246            id,
5247            ref_counts: Arc::downgrade(ref_counts),
5248        }
5249    }
5250
5251    pub fn id(&self) -> ElementStateId {
5252        self.id
5253    }
5254
5255    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
5256        cx.element_states
5257            .get(&self.id)
5258            .unwrap()
5259            .downcast_ref()
5260            .unwrap()
5261    }
5262
5263    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
5264    where
5265        C: DerefMut<Target = MutableAppContext>,
5266    {
5267        let mut element_state = cx.deref_mut().cx.element_states.remove(&self.id).unwrap();
5268        let result = f(element_state.downcast_mut().unwrap(), cx);
5269        cx.deref_mut()
5270            .cx
5271            .element_states
5272            .insert(self.id, element_state);
5273        result
5274    }
5275}
5276
5277impl<T> Drop for ElementStateHandle<T> {
5278    fn drop(&mut self) {
5279        if let Some(ref_counts) = self.ref_counts.upgrade() {
5280            ref_counts.lock().dec_element_state(self.id);
5281        }
5282    }
5283}
5284
5285#[must_use]
5286pub enum Subscription {
5287    Subscription(callback_collection::Subscription<usize, SubscriptionCallback>),
5288    Observation(callback_collection::Subscription<usize, ObservationCallback>),
5289    GlobalSubscription(callback_collection::Subscription<TypeId, GlobalSubscriptionCallback>),
5290    GlobalObservation(callback_collection::Subscription<TypeId, GlobalObservationCallback>),
5291    FocusObservation(callback_collection::Subscription<usize, FocusObservationCallback>),
5292    WindowActivationObservation(callback_collection::Subscription<usize, WindowActivationCallback>),
5293    WindowFullscreenObservation(callback_collection::Subscription<usize, WindowFullscreenCallback>),
5294    WindowBoundsObservation(callback_collection::Subscription<usize, WindowBoundsCallback>),
5295    KeystrokeObservation(callback_collection::Subscription<usize, KeystrokeCallback>),
5296    ReleaseObservation(callback_collection::Subscription<usize, ReleaseObservationCallback>),
5297    ActionObservation(callback_collection::Subscription<(), ActionObservationCallback>),
5298    ActiveLabeledTasksObservation(
5299        callback_collection::Subscription<(), ActiveLabeledTasksCallback>,
5300    ),
5301}
5302
5303impl Subscription {
5304    pub fn id(&self) -> usize {
5305        match self {
5306            Subscription::Subscription(subscription) => subscription.id(),
5307            Subscription::Observation(subscription) => subscription.id(),
5308            Subscription::GlobalSubscription(subscription) => subscription.id(),
5309            Subscription::GlobalObservation(subscription) => subscription.id(),
5310            Subscription::FocusObservation(subscription) => subscription.id(),
5311            Subscription::WindowActivationObservation(subscription) => subscription.id(),
5312            Subscription::WindowFullscreenObservation(subscription) => subscription.id(),
5313            Subscription::WindowBoundsObservation(subscription) => subscription.id(),
5314            Subscription::KeystrokeObservation(subscription) => subscription.id(),
5315            Subscription::ReleaseObservation(subscription) => subscription.id(),
5316            Subscription::ActionObservation(subscription) => subscription.id(),
5317            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.id(),
5318        }
5319    }
5320
5321    pub fn detach(&mut self) {
5322        match self {
5323            Subscription::Subscription(subscription) => subscription.detach(),
5324            Subscription::GlobalSubscription(subscription) => subscription.detach(),
5325            Subscription::Observation(subscription) => subscription.detach(),
5326            Subscription::GlobalObservation(subscription) => subscription.detach(),
5327            Subscription::FocusObservation(subscription) => subscription.detach(),
5328            Subscription::KeystrokeObservation(subscription) => subscription.detach(),
5329            Subscription::WindowActivationObservation(subscription) => subscription.detach(),
5330            Subscription::WindowFullscreenObservation(subscription) => subscription.detach(),
5331            Subscription::WindowBoundsObservation(subscription) => subscription.detach(),
5332            Subscription::ReleaseObservation(subscription) => subscription.detach(),
5333            Subscription::ActionObservation(subscription) => subscription.detach(),
5334            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.detach(),
5335        }
5336    }
5337}
5338
5339#[cfg(test)]
5340mod tests {
5341    use super::*;
5342    use crate::{actions, elements::*, impl_actions, MouseButton, MouseButtonEvent};
5343    use itertools::Itertools;
5344    use postage::{sink::Sink, stream::Stream};
5345    use serde::Deserialize;
5346    use smol::future::poll_once;
5347    use std::{
5348        cell::Cell,
5349        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
5350    };
5351
5352    #[crate::test(self)]
5353    fn test_model_handles(cx: &mut MutableAppContext) {
5354        struct Model {
5355            other: Option<ModelHandle<Model>>,
5356            events: Vec<String>,
5357        }
5358
5359        impl Entity for Model {
5360            type Event = usize;
5361        }
5362
5363        impl Model {
5364            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
5365                if let Some(other) = other.as_ref() {
5366                    cx.observe(other, |me, _, _| {
5367                        me.events.push("notified".into());
5368                    })
5369                    .detach();
5370                    cx.subscribe(other, |me, _, event, _| {
5371                        me.events.push(format!("observed event {}", event));
5372                    })
5373                    .detach();
5374                }
5375
5376                Self {
5377                    other,
5378                    events: Vec::new(),
5379                }
5380            }
5381        }
5382
5383        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
5384        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
5385        assert_eq!(cx.cx.models.len(), 2);
5386
5387        handle_1.update(cx, |model, cx| {
5388            model.events.push("updated".into());
5389            cx.emit(1);
5390            cx.notify();
5391            cx.emit(2);
5392        });
5393        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5394        assert_eq!(
5395            handle_2.read(cx).events,
5396            vec![
5397                "observed event 1".to_string(),
5398                "notified".to_string(),
5399                "observed event 2".to_string(),
5400            ]
5401        );
5402
5403        handle_2.update(cx, |model, _| {
5404            drop(handle_1);
5405            model.other.take();
5406        });
5407
5408        assert_eq!(cx.cx.models.len(), 1);
5409        assert!(cx.subscriptions.is_empty());
5410        assert!(cx.observations.is_empty());
5411    }
5412
5413    #[crate::test(self)]
5414    fn test_model_events(cx: &mut MutableAppContext) {
5415        #[derive(Default)]
5416        struct Model {
5417            events: Vec<usize>,
5418        }
5419
5420        impl Entity for Model {
5421            type Event = usize;
5422        }
5423
5424        let handle_1 = cx.add_model(|_| Model::default());
5425        let handle_2 = cx.add_model(|_| Model::default());
5426
5427        handle_1.update(cx, |_, cx| {
5428            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
5429                model.events.push(*event);
5430
5431                cx.subscribe(&emitter, |model, _, event, _| {
5432                    model.events.push(*event * 2);
5433                })
5434                .detach();
5435            })
5436            .detach();
5437        });
5438
5439        handle_2.update(cx, |_, c| c.emit(7));
5440        assert_eq!(handle_1.read(cx).events, vec![7]);
5441
5442        handle_2.update(cx, |_, c| c.emit(5));
5443        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
5444    }
5445
5446    #[crate::test(self)]
5447    fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
5448        #[derive(Default)]
5449        struct Model;
5450
5451        impl Entity for Model {
5452            type Event = ();
5453        }
5454
5455        let events = Rc::new(RefCell::new(Vec::new()));
5456        cx.add_model(|cx| {
5457            drop(cx.subscribe(&cx.handle(), {
5458                let events = events.clone();
5459                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
5460            }));
5461            cx.subscribe(&cx.handle(), {
5462                let events = events.clone();
5463                move |_, _, _, _| events.borrow_mut().push("before emit")
5464            })
5465            .detach();
5466            cx.emit(());
5467            cx.subscribe(&cx.handle(), {
5468                let events = events.clone();
5469                move |_, _, _, _| events.borrow_mut().push("after emit")
5470            })
5471            .detach();
5472            Model
5473        });
5474        assert_eq!(*events.borrow(), ["before emit"]);
5475    }
5476
5477    #[crate::test(self)]
5478    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
5479        #[derive(Default)]
5480        struct Model {
5481            count: usize,
5482            events: Vec<usize>,
5483        }
5484
5485        impl Entity for Model {
5486            type Event = ();
5487        }
5488
5489        let handle_1 = cx.add_model(|_| Model::default());
5490        let handle_2 = cx.add_model(|_| Model::default());
5491
5492        handle_1.update(cx, |_, c| {
5493            c.observe(&handle_2, move |model, observed, c| {
5494                model.events.push(observed.read(c).count);
5495                c.observe(&observed, |model, observed, c| {
5496                    model.events.push(observed.read(c).count * 2);
5497                })
5498                .detach();
5499            })
5500            .detach();
5501        });
5502
5503        handle_2.update(cx, |model, c| {
5504            model.count = 7;
5505            c.notify()
5506        });
5507        assert_eq!(handle_1.read(cx).events, vec![7]);
5508
5509        handle_2.update(cx, |model, c| {
5510            model.count = 5;
5511            c.notify()
5512        });
5513        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
5514    }
5515
5516    #[crate::test(self)]
5517    fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
5518        #[derive(Default)]
5519        struct Model;
5520
5521        impl Entity for Model {
5522            type Event = ();
5523        }
5524
5525        let events = Rc::new(RefCell::new(Vec::new()));
5526        cx.add_model(|cx| {
5527            drop(cx.observe(&cx.handle(), {
5528                let events = events.clone();
5529                move |_, _, _| events.borrow_mut().push("dropped before flush")
5530            }));
5531            cx.observe(&cx.handle(), {
5532                let events = events.clone();
5533                move |_, _, _| events.borrow_mut().push("before notify")
5534            })
5535            .detach();
5536            cx.notify();
5537            cx.observe(&cx.handle(), {
5538                let events = events.clone();
5539                move |_, _, _| events.borrow_mut().push("after notify")
5540            })
5541            .detach();
5542            Model
5543        });
5544        assert_eq!(*events.borrow(), ["before notify"]);
5545    }
5546
5547    #[crate::test(self)]
5548    fn test_defer_and_after_window_update(cx: &mut MutableAppContext) {
5549        struct View {
5550            render_count: usize,
5551        }
5552
5553        impl Entity for View {
5554            type Event = usize;
5555        }
5556
5557        impl super::View for View {
5558            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5559                post_inc(&mut self.render_count);
5560                Empty::new().boxed()
5561            }
5562
5563            fn ui_name() -> &'static str {
5564                "View"
5565            }
5566        }
5567
5568        let (_, view) = cx.add_window(Default::default(), |_| View { render_count: 0 });
5569        let called_defer = Rc::new(AtomicBool::new(false));
5570        let called_after_window_update = Rc::new(AtomicBool::new(false));
5571
5572        view.update(cx, |this, cx| {
5573            assert_eq!(this.render_count, 1);
5574            cx.defer({
5575                let called_defer = called_defer.clone();
5576                move |this, _| {
5577                    assert_eq!(this.render_count, 1);
5578                    called_defer.store(true, SeqCst);
5579                }
5580            });
5581            cx.after_window_update({
5582                let called_after_window_update = called_after_window_update.clone();
5583                move |this, cx| {
5584                    assert_eq!(this.render_count, 2);
5585                    called_after_window_update.store(true, SeqCst);
5586                    cx.notify();
5587                }
5588            });
5589            assert!(!called_defer.load(SeqCst));
5590            assert!(!called_after_window_update.load(SeqCst));
5591            cx.notify();
5592        });
5593
5594        assert!(called_defer.load(SeqCst));
5595        assert!(called_after_window_update.load(SeqCst));
5596        assert_eq!(view.read(cx).render_count, 3);
5597    }
5598
5599    #[crate::test(self)]
5600    fn test_view_handles(cx: &mut MutableAppContext) {
5601        struct View {
5602            other: Option<ViewHandle<View>>,
5603            events: Vec<String>,
5604        }
5605
5606        impl Entity for View {
5607            type Event = usize;
5608        }
5609
5610        impl super::View for View {
5611            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5612                Empty::new().boxed()
5613            }
5614
5615            fn ui_name() -> &'static str {
5616                "View"
5617            }
5618        }
5619
5620        impl View {
5621            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
5622                if let Some(other) = other.as_ref() {
5623                    cx.subscribe(other, |me, _, event, _| {
5624                        me.events.push(format!("observed event {}", event));
5625                    })
5626                    .detach();
5627                }
5628                Self {
5629                    other,
5630                    events: Vec::new(),
5631                }
5632            }
5633        }
5634
5635        let (_, root_view) = cx.add_window(Default::default(), |cx| View::new(None, cx));
5636        let handle_1 = cx.add_view(&root_view, |cx| View::new(None, cx));
5637        let handle_2 = cx.add_view(&root_view, |cx| View::new(Some(handle_1.clone()), cx));
5638        assert_eq!(cx.cx.views.len(), 3);
5639
5640        handle_1.update(cx, |view, cx| {
5641            view.events.push("updated".into());
5642            cx.emit(1);
5643            cx.emit(2);
5644        });
5645        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5646        assert_eq!(
5647            handle_2.read(cx).events,
5648            vec![
5649                "observed event 1".to_string(),
5650                "observed event 2".to_string(),
5651            ]
5652        );
5653
5654        handle_2.update(cx, |view, _| {
5655            drop(handle_1);
5656            view.other.take();
5657        });
5658
5659        assert_eq!(cx.cx.views.len(), 2);
5660        assert!(cx.subscriptions.is_empty());
5661        assert!(cx.observations.is_empty());
5662    }
5663
5664    #[crate::test(self)]
5665    fn test_add_window(cx: &mut MutableAppContext) {
5666        struct View {
5667            mouse_down_count: Arc<AtomicUsize>,
5668        }
5669
5670        impl Entity for View {
5671            type Event = ();
5672        }
5673
5674        impl super::View for View {
5675            fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
5676                enum Handler {}
5677                let mouse_down_count = self.mouse_down_count.clone();
5678                MouseEventHandler::<Handler>::new(0, cx, |_, _| Empty::new().boxed())
5679                    .on_down(MouseButton::Left, move |_, _| {
5680                        mouse_down_count.fetch_add(1, SeqCst);
5681                    })
5682                    .boxed()
5683            }
5684
5685            fn ui_name() -> &'static str {
5686                "View"
5687            }
5688        }
5689
5690        let mouse_down_count = Arc::new(AtomicUsize::new(0));
5691        let (window_id, _) = cx.add_window(Default::default(), |_| View {
5692            mouse_down_count: mouse_down_count.clone(),
5693        });
5694        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
5695        // Ensure window's root element is in a valid lifecycle state.
5696        presenter.borrow_mut().dispatch_event(
5697            Event::MouseDown(MouseButtonEvent {
5698                position: Default::default(),
5699                button: MouseButton::Left,
5700                modifiers: Default::default(),
5701                click_count: 1,
5702            }),
5703            false,
5704            cx,
5705        );
5706        assert_eq!(mouse_down_count.load(SeqCst), 1);
5707    }
5708
5709    #[crate::test(self)]
5710    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
5711        struct Model {
5712            released: Rc<Cell<bool>>,
5713        }
5714
5715        struct View {
5716            released: Rc<Cell<bool>>,
5717        }
5718
5719        impl Entity for Model {
5720            type Event = ();
5721
5722            fn release(&mut self, _: &mut MutableAppContext) {
5723                self.released.set(true);
5724            }
5725        }
5726
5727        impl Entity for View {
5728            type Event = ();
5729
5730            fn release(&mut self, _: &mut MutableAppContext) {
5731                self.released.set(true);
5732            }
5733        }
5734
5735        impl super::View for View {
5736            fn ui_name() -> &'static str {
5737                "View"
5738            }
5739
5740            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5741                Empty::new().boxed()
5742            }
5743        }
5744
5745        let model_released = Rc::new(Cell::new(false));
5746        let model_release_observed = Rc::new(Cell::new(false));
5747        let view_released = Rc::new(Cell::new(false));
5748        let view_release_observed = Rc::new(Cell::new(false));
5749
5750        let model = cx.add_model(|_| Model {
5751            released: model_released.clone(),
5752        });
5753        let (window_id, view) = cx.add_window(Default::default(), |_| View {
5754            released: view_released.clone(),
5755        });
5756        assert!(!model_released.get());
5757        assert!(!view_released.get());
5758
5759        cx.observe_release(&model, {
5760            let model_release_observed = model_release_observed.clone();
5761            move |_, _| model_release_observed.set(true)
5762        })
5763        .detach();
5764        cx.observe_release(&view, {
5765            let view_release_observed = view_release_observed.clone();
5766            move |_, _| view_release_observed.set(true)
5767        })
5768        .detach();
5769
5770        cx.update(move |_| {
5771            drop(model);
5772        });
5773        assert!(model_released.get());
5774        assert!(model_release_observed.get());
5775
5776        drop(view);
5777        cx.remove_window(window_id);
5778        assert!(view_released.get());
5779        assert!(view_release_observed.get());
5780    }
5781
5782    #[crate::test(self)]
5783    fn test_view_events(cx: &mut MutableAppContext) {
5784        struct Model;
5785
5786        impl Entity for Model {
5787            type Event = String;
5788        }
5789
5790        let (_, handle_1) = cx.add_window(Default::default(), |_| TestView::default());
5791        let handle_2 = cx.add_view(&handle_1, |_| TestView::default());
5792        let handle_3 = cx.add_model(|_| Model);
5793
5794        handle_1.update(cx, |_, cx| {
5795            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
5796                me.events.push(event.clone());
5797
5798                cx.subscribe(&emitter, |me, _, event, _| {
5799                    me.events.push(format!("{event} from inner"));
5800                })
5801                .detach();
5802            })
5803            .detach();
5804
5805            cx.subscribe(&handle_3, |me, _, event, _| {
5806                me.events.push(event.clone());
5807            })
5808            .detach();
5809        });
5810
5811        handle_2.update(cx, |_, c| c.emit("7".into()));
5812        assert_eq!(handle_1.read(cx).events, vec!["7"]);
5813
5814        handle_2.update(cx, |_, c| c.emit("5".into()));
5815        assert_eq!(handle_1.read(cx).events, vec!["7", "5", "5 from inner"]);
5816
5817        handle_3.update(cx, |_, c| c.emit("9".into()));
5818        assert_eq!(
5819            handle_1.read(cx).events,
5820            vec!["7", "5", "5 from inner", "9"]
5821        );
5822    }
5823
5824    #[crate::test(self)]
5825    fn test_global_events(cx: &mut MutableAppContext) {
5826        #[derive(Clone, Debug, Eq, PartialEq)]
5827        struct GlobalEvent(u64);
5828
5829        let events = Rc::new(RefCell::new(Vec::new()));
5830        let first_subscription;
5831        let second_subscription;
5832
5833        {
5834            let events = events.clone();
5835            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5836                events.borrow_mut().push(("First", e.clone()));
5837            });
5838        }
5839
5840        {
5841            let events = events.clone();
5842            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5843                events.borrow_mut().push(("Second", e.clone()));
5844            });
5845        }
5846
5847        cx.update(|cx| {
5848            cx.emit_global(GlobalEvent(1));
5849            cx.emit_global(GlobalEvent(2));
5850        });
5851
5852        drop(first_subscription);
5853
5854        cx.update(|cx| {
5855            cx.emit_global(GlobalEvent(3));
5856        });
5857
5858        drop(second_subscription);
5859
5860        cx.update(|cx| {
5861            cx.emit_global(GlobalEvent(4));
5862        });
5863
5864        assert_eq!(
5865            &*events.borrow(),
5866            &[
5867                ("First", GlobalEvent(1)),
5868                ("Second", GlobalEvent(1)),
5869                ("First", GlobalEvent(2)),
5870                ("Second", GlobalEvent(2)),
5871                ("Second", GlobalEvent(3)),
5872            ]
5873        );
5874    }
5875
5876    #[crate::test(self)]
5877    fn test_global_events_emitted_before_subscription_in_same_update_cycle(
5878        cx: &mut MutableAppContext,
5879    ) {
5880        let events = Rc::new(RefCell::new(Vec::new()));
5881        cx.update(|cx| {
5882            {
5883                let events = events.clone();
5884                drop(cx.subscribe_global(move |_: &(), _| {
5885                    events.borrow_mut().push("dropped before emit");
5886                }));
5887            }
5888
5889            {
5890                let events = events.clone();
5891                cx.subscribe_global(move |_: &(), _| {
5892                    events.borrow_mut().push("before emit");
5893                })
5894                .detach();
5895            }
5896
5897            cx.emit_global(());
5898
5899            {
5900                let events = events.clone();
5901                cx.subscribe_global(move |_: &(), _| {
5902                    events.borrow_mut().push("after emit");
5903                })
5904                .detach();
5905            }
5906        });
5907
5908        assert_eq!(*events.borrow(), ["before emit"]);
5909    }
5910
5911    #[crate::test(self)]
5912    fn test_global_nested_events(cx: &mut MutableAppContext) {
5913        #[derive(Clone, Debug, Eq, PartialEq)]
5914        struct GlobalEvent(u64);
5915
5916        let events = Rc::new(RefCell::new(Vec::new()));
5917
5918        {
5919            let events = events.clone();
5920            cx.subscribe_global(move |e: &GlobalEvent, cx| {
5921                events.borrow_mut().push(("Outer", e.clone()));
5922
5923                if e.0 == 1 {
5924                    let events = events.clone();
5925                    cx.subscribe_global(move |e: &GlobalEvent, _| {
5926                        events.borrow_mut().push(("Inner", e.clone()));
5927                    })
5928                    .detach();
5929                }
5930            })
5931            .detach();
5932        }
5933
5934        cx.update(|cx| {
5935            cx.emit_global(GlobalEvent(1));
5936            cx.emit_global(GlobalEvent(2));
5937            cx.emit_global(GlobalEvent(3));
5938        });
5939        cx.update(|cx| {
5940            cx.emit_global(GlobalEvent(4));
5941        });
5942
5943        assert_eq!(
5944            &*events.borrow(),
5945            &[
5946                ("Outer", GlobalEvent(1)),
5947                ("Outer", GlobalEvent(2)),
5948                ("Outer", GlobalEvent(3)),
5949                ("Outer", GlobalEvent(4)),
5950                ("Inner", GlobalEvent(4)),
5951            ]
5952        );
5953    }
5954
5955    #[crate::test(self)]
5956    fn test_global(cx: &mut MutableAppContext) {
5957        type Global = usize;
5958
5959        let observation_count = Rc::new(RefCell::new(0));
5960        let subscription = cx.observe_global::<Global, _>({
5961            let observation_count = observation_count.clone();
5962            move |_| {
5963                *observation_count.borrow_mut() += 1;
5964            }
5965        });
5966
5967        assert!(!cx.has_global::<Global>());
5968        assert_eq!(cx.default_global::<Global>(), &0);
5969        assert_eq!(*observation_count.borrow(), 1);
5970        assert!(cx.has_global::<Global>());
5971        assert_eq!(
5972            cx.update_global::<Global, _, _>(|global, _| {
5973                *global = 1;
5974                "Update Result"
5975            }),
5976            "Update Result"
5977        );
5978        assert_eq!(*observation_count.borrow(), 2);
5979        assert_eq!(cx.global::<Global>(), &1);
5980
5981        drop(subscription);
5982        cx.update_global::<Global, _, _>(|global, _| {
5983            *global = 2;
5984        });
5985        assert_eq!(*observation_count.borrow(), 2);
5986
5987        type OtherGlobal = f32;
5988
5989        let observation_count = Rc::new(RefCell::new(0));
5990        cx.observe_global::<OtherGlobal, _>({
5991            let observation_count = observation_count.clone();
5992            move |_| {
5993                *observation_count.borrow_mut() += 1;
5994            }
5995        })
5996        .detach();
5997
5998        assert_eq!(
5999            cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
6000                assert_eq!(global, &0.0);
6001                *global = 2.0;
6002                "Default update result"
6003            }),
6004            "Default update result"
6005        );
6006        assert_eq!(cx.global::<OtherGlobal>(), &2.0);
6007        assert_eq!(*observation_count.borrow(), 1);
6008    }
6009
6010    #[crate::test(self)]
6011    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
6012        struct Model;
6013
6014        impl Entity for Model {
6015            type Event = ();
6016        }
6017
6018        let (_, root_view) = cx.add_window(Default::default(), |_| TestView::default());
6019        let observing_view = cx.add_view(&root_view, |_| TestView::default());
6020        let emitting_view = cx.add_view(&root_view, |_| TestView::default());
6021        let observing_model = cx.add_model(|_| Model);
6022        let observed_model = cx.add_model(|_| Model);
6023
6024        observing_view.update(cx, |_, cx| {
6025            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
6026            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
6027        });
6028        observing_model.update(cx, |_, cx| {
6029            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
6030        });
6031
6032        cx.update(|_| {
6033            drop(observing_view);
6034            drop(observing_model);
6035        });
6036
6037        emitting_view.update(cx, |_, cx| cx.emit(Default::default()));
6038        observed_model.update(cx, |_, cx| cx.emit(()));
6039    }
6040
6041    #[crate::test(self)]
6042    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
6043        let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
6044            drop(cx.subscribe(&cx.handle(), {
6045                move |this, _, _, _| this.events.push("dropped before flush".into())
6046            }));
6047            cx.subscribe(&cx.handle(), {
6048                move |this, _, _, _| this.events.push("before emit".into())
6049            })
6050            .detach();
6051            cx.emit("the event".into());
6052            cx.subscribe(&cx.handle(), {
6053                move |this, _, _, _| this.events.push("after emit".into())
6054            })
6055            .detach();
6056            TestView { events: Vec::new() }
6057        });
6058
6059        assert_eq!(view.read(cx).events, ["before emit"]);
6060    }
6061
6062    #[crate::test(self)]
6063    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
6064        #[derive(Default)]
6065        struct Model {
6066            state: String,
6067        }
6068
6069        impl Entity for Model {
6070            type Event = ();
6071        }
6072
6073        let (_, view) = cx.add_window(Default::default(), |_| TestView::default());
6074        let model = cx.add_model(|_| Model {
6075            state: "old-state".into(),
6076        });
6077
6078        view.update(cx, |_, c| {
6079            c.observe(&model, |me, observed, c| {
6080                me.events.push(observed.read(c).state.clone())
6081            })
6082            .detach();
6083        });
6084
6085        model.update(cx, |model, cx| {
6086            model.state = "new-state".into();
6087            cx.notify();
6088        });
6089        assert_eq!(view.read(cx).events, vec!["new-state"]);
6090    }
6091
6092    #[crate::test(self)]
6093    fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
6094        let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
6095            drop(cx.observe(&cx.handle(), {
6096                move |this, _, _| this.events.push("dropped before flush".into())
6097            }));
6098            cx.observe(&cx.handle(), {
6099                move |this, _, _| this.events.push("before notify".into())
6100            })
6101            .detach();
6102            cx.notify();
6103            cx.observe(&cx.handle(), {
6104                move |this, _, _| this.events.push("after notify".into())
6105            })
6106            .detach();
6107            TestView { events: Vec::new() }
6108        });
6109
6110        assert_eq!(view.read(cx).events, ["before notify"]);
6111    }
6112
6113    #[crate::test(self)]
6114    fn test_notify_and_drop_observe_subscription_in_same_update_cycle(cx: &mut MutableAppContext) {
6115        struct Model;
6116        impl Entity for Model {
6117            type Event = ();
6118        }
6119
6120        let model = cx.add_model(|_| Model);
6121        let (_, view) = cx.add_window(Default::default(), |_| TestView::default());
6122
6123        view.update(cx, |_, cx| {
6124            model.update(cx, |_, cx| cx.notify());
6125            drop(cx.observe(&model, move |this, _, _| {
6126                this.events.push("model notified".into());
6127            }));
6128            model.update(cx, |_, cx| cx.notify());
6129        });
6130
6131        for _ in 0..3 {
6132            model.update(cx, |_, cx| cx.notify());
6133        }
6134
6135        assert_eq!(view.read(cx).events, Vec::<String>::new());
6136    }
6137
6138    #[crate::test(self)]
6139    fn test_dropping_observers(cx: &mut MutableAppContext) {
6140        struct Model;
6141
6142        impl Entity for Model {
6143            type Event = ();
6144        }
6145
6146        let (_, root_view) = cx.add_window(Default::default(), |_| TestView::default());
6147        let observing_view = cx.add_view(root_view, |_| TestView::default());
6148        let observing_model = cx.add_model(|_| Model);
6149        let observed_model = cx.add_model(|_| Model);
6150
6151        observing_view.update(cx, |_, cx| {
6152            cx.observe(&observed_model, |_, _, _| {}).detach();
6153        });
6154        observing_model.update(cx, |_, cx| {
6155            cx.observe(&observed_model, |_, _, _| {}).detach();
6156        });
6157
6158        cx.update(|_| {
6159            drop(observing_view);
6160            drop(observing_model);
6161        });
6162
6163        observed_model.update(cx, |_, cx| cx.notify());
6164    }
6165
6166    #[crate::test(self)]
6167    fn test_dropping_subscriptions_during_callback(cx: &mut MutableAppContext) {
6168        struct Model;
6169
6170        impl Entity for Model {
6171            type Event = u64;
6172        }
6173
6174        // Events
6175        let observing_model = cx.add_model(|_| Model);
6176        let observed_model = cx.add_model(|_| Model);
6177
6178        let events = Rc::new(RefCell::new(Vec::new()));
6179
6180        observing_model.update(cx, |_, cx| {
6181            let events = events.clone();
6182            let subscription = Rc::new(RefCell::new(None));
6183            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
6184                let subscription = subscription.clone();
6185                move |_, _, e, _| {
6186                    subscription.borrow_mut().take();
6187                    events.borrow_mut().push(*e);
6188                }
6189            }));
6190        });
6191
6192        observed_model.update(cx, |_, cx| {
6193            cx.emit(1);
6194            cx.emit(2);
6195        });
6196
6197        assert_eq!(*events.borrow(), [1]);
6198
6199        // Global Events
6200        #[derive(Clone, Debug, Eq, PartialEq)]
6201        struct GlobalEvent(u64);
6202
6203        let events = Rc::new(RefCell::new(Vec::new()));
6204
6205        {
6206            let events = events.clone();
6207            let subscription = Rc::new(RefCell::new(None));
6208            *subscription.borrow_mut() = Some(cx.subscribe_global({
6209                let subscription = subscription.clone();
6210                move |e: &GlobalEvent, _| {
6211                    subscription.borrow_mut().take();
6212                    events.borrow_mut().push(e.clone());
6213                }
6214            }));
6215        }
6216
6217        cx.update(|cx| {
6218            cx.emit_global(GlobalEvent(1));
6219            cx.emit_global(GlobalEvent(2));
6220        });
6221
6222        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
6223
6224        // Model Observation
6225        let observing_model = cx.add_model(|_| Model);
6226        let observed_model = cx.add_model(|_| Model);
6227
6228        let observation_count = Rc::new(RefCell::new(0));
6229
6230        observing_model.update(cx, |_, cx| {
6231            let observation_count = observation_count.clone();
6232            let subscription = Rc::new(RefCell::new(None));
6233            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
6234                let subscription = subscription.clone();
6235                move |_, _, _| {
6236                    subscription.borrow_mut().take();
6237                    *observation_count.borrow_mut() += 1;
6238                }
6239            }));
6240        });
6241
6242        observed_model.update(cx, |_, cx| {
6243            cx.notify();
6244        });
6245
6246        observed_model.update(cx, |_, cx| {
6247            cx.notify();
6248        });
6249
6250        assert_eq!(*observation_count.borrow(), 1);
6251
6252        // View Observation
6253        struct View;
6254
6255        impl Entity for View {
6256            type Event = ();
6257        }
6258
6259        impl super::View for View {
6260            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6261                Empty::new().boxed()
6262            }
6263
6264            fn ui_name() -> &'static str {
6265                "View"
6266            }
6267        }
6268
6269        let (_, root_view) = cx.add_window(Default::default(), |_| View);
6270        let observing_view = cx.add_view(&root_view, |_| View);
6271        let observed_view = cx.add_view(&root_view, |_| View);
6272
6273        let observation_count = Rc::new(RefCell::new(0));
6274        observing_view.update(cx, |_, cx| {
6275            let observation_count = observation_count.clone();
6276            let subscription = Rc::new(RefCell::new(None));
6277            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
6278                let subscription = subscription.clone();
6279                move |_, _, _| {
6280                    subscription.borrow_mut().take();
6281                    *observation_count.borrow_mut() += 1;
6282                }
6283            }));
6284        });
6285
6286        observed_view.update(cx, |_, cx| {
6287            cx.notify();
6288        });
6289
6290        observed_view.update(cx, |_, cx| {
6291            cx.notify();
6292        });
6293
6294        assert_eq!(*observation_count.borrow(), 1);
6295
6296        // Global Observation
6297        let observation_count = Rc::new(RefCell::new(0));
6298        let subscription = Rc::new(RefCell::new(None));
6299        *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
6300            let observation_count = observation_count.clone();
6301            let subscription = subscription.clone();
6302            move |_| {
6303                subscription.borrow_mut().take();
6304                *observation_count.borrow_mut() += 1;
6305            }
6306        }));
6307
6308        cx.default_global::<()>();
6309        cx.set_global(());
6310        assert_eq!(*observation_count.borrow(), 1);
6311    }
6312
6313    #[crate::test(self)]
6314    fn test_focus(cx: &mut MutableAppContext) {
6315        struct View {
6316            name: String,
6317            events: Arc<Mutex<Vec<String>>>,
6318        }
6319
6320        impl Entity for View {
6321            type Event = ();
6322        }
6323
6324        impl super::View for View {
6325            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6326                Empty::new().boxed()
6327            }
6328
6329            fn ui_name() -> &'static str {
6330                "View"
6331            }
6332
6333            fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
6334                if cx.handle().id() == focused.id() {
6335                    self.events.lock().push(format!("{} focused", &self.name));
6336                }
6337            }
6338
6339            fn focus_out(&mut self, blurred: AnyViewHandle, cx: &mut ViewContext<Self>) {
6340                if cx.handle().id() == blurred.id() {
6341                    self.events.lock().push(format!("{} blurred", &self.name));
6342                }
6343            }
6344        }
6345
6346        let view_events: Arc<Mutex<Vec<String>>> = Default::default();
6347        let (_, view_1) = cx.add_window(Default::default(), |_| View {
6348            events: view_events.clone(),
6349            name: "view 1".to_string(),
6350        });
6351        let view_2 = cx.add_view(&view_1, |_| View {
6352            events: view_events.clone(),
6353            name: "view 2".to_string(),
6354        });
6355
6356        let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
6357        view_1.update(cx, |_, cx| {
6358            cx.observe_focus(&view_2, {
6359                let observed_events = observed_events.clone();
6360                move |this, view, focused, cx| {
6361                    let label = if focused { "focus" } else { "blur" };
6362                    observed_events.lock().push(format!(
6363                        "{} observed {}'s {}",
6364                        this.name,
6365                        view.read(cx).name,
6366                        label
6367                    ))
6368                }
6369            })
6370            .detach();
6371        });
6372        view_2.update(cx, |_, cx| {
6373            cx.observe_focus(&view_1, {
6374                let observed_events = observed_events.clone();
6375                move |this, view, focused, cx| {
6376                    let label = if focused { "focus" } else { "blur" };
6377                    observed_events.lock().push(format!(
6378                        "{} observed {}'s {}",
6379                        this.name,
6380                        view.read(cx).name,
6381                        label
6382                    ))
6383                }
6384            })
6385            .detach();
6386        });
6387        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6388        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6389
6390        view_1.update(cx, |_, cx| {
6391            // Ensure focus events are sent for all intermediate focuses
6392            cx.focus(&view_2);
6393            cx.focus(&view_1);
6394            cx.focus(&view_2);
6395        });
6396        assert!(cx.is_child_focused(view_1.clone()));
6397        assert!(!cx.is_child_focused(view_2.clone()));
6398        assert_eq!(
6399            mem::take(&mut *view_events.lock()),
6400            [
6401                "view 1 blurred",
6402                "view 2 focused",
6403                "view 2 blurred",
6404                "view 1 focused",
6405                "view 1 blurred",
6406                "view 2 focused"
6407            ],
6408        );
6409        assert_eq!(
6410            mem::take(&mut *observed_events.lock()),
6411            [
6412                "view 2 observed view 1's blur",
6413                "view 1 observed view 2's focus",
6414                "view 1 observed view 2's blur",
6415                "view 2 observed view 1's focus",
6416                "view 2 observed view 1's blur",
6417                "view 1 observed view 2's focus"
6418            ]
6419        );
6420
6421        view_1.update(cx, |_, cx| cx.focus(&view_1));
6422        assert!(!cx.is_child_focused(view_1.clone()));
6423        assert!(!cx.is_child_focused(view_2.clone()));
6424        assert_eq!(
6425            mem::take(&mut *view_events.lock()),
6426            ["view 2 blurred", "view 1 focused"],
6427        );
6428        assert_eq!(
6429            mem::take(&mut *observed_events.lock()),
6430            [
6431                "view 1 observed view 2's blur",
6432                "view 2 observed view 1's focus"
6433            ]
6434        );
6435
6436        view_1.update(cx, |_, cx| cx.focus(&view_2));
6437        assert_eq!(
6438            mem::take(&mut *view_events.lock()),
6439            ["view 1 blurred", "view 2 focused"],
6440        );
6441        assert_eq!(
6442            mem::take(&mut *observed_events.lock()),
6443            [
6444                "view 2 observed view 1's blur",
6445                "view 1 observed view 2's focus"
6446            ]
6447        );
6448
6449        view_1.update(cx, |_, _| drop(view_2));
6450        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6451        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6452    }
6453
6454    #[crate::test(self)]
6455    fn test_deserialize_actions(cx: &mut MutableAppContext) {
6456        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6457        pub struct ComplexAction {
6458            arg: String,
6459            count: usize,
6460        }
6461
6462        actions!(test::something, [SimpleAction]);
6463        impl_actions!(test::something, [ComplexAction]);
6464
6465        cx.add_global_action(move |_: &SimpleAction, _: &mut MutableAppContext| {});
6466        cx.add_global_action(move |_: &ComplexAction, _: &mut MutableAppContext| {});
6467
6468        let action1 = cx
6469            .deserialize_action(
6470                "test::something::ComplexAction",
6471                Some(r#"{"arg": "a", "count": 5}"#),
6472            )
6473            .unwrap();
6474        let action2 = cx
6475            .deserialize_action("test::something::SimpleAction", None)
6476            .unwrap();
6477        assert_eq!(
6478            action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
6479            &ComplexAction {
6480                arg: "a".to_string(),
6481                count: 5,
6482            }
6483        );
6484        assert_eq!(
6485            action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
6486            &SimpleAction
6487        );
6488    }
6489
6490    #[crate::test(self)]
6491    fn test_dispatch_action(cx: &mut MutableAppContext) {
6492        struct ViewA {
6493            id: usize,
6494        }
6495
6496        impl Entity for ViewA {
6497            type Event = ();
6498        }
6499
6500        impl View for ViewA {
6501            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6502                Empty::new().boxed()
6503            }
6504
6505            fn ui_name() -> &'static str {
6506                "View"
6507            }
6508        }
6509
6510        struct ViewB {
6511            id: usize,
6512        }
6513
6514        impl Entity for ViewB {
6515            type Event = ();
6516        }
6517
6518        impl View for ViewB {
6519            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6520                Empty::new().boxed()
6521            }
6522
6523            fn ui_name() -> &'static str {
6524                "View"
6525            }
6526        }
6527
6528        #[derive(Clone, Default, Deserialize, PartialEq)]
6529        pub struct Action(pub String);
6530
6531        impl_actions!(test, [Action]);
6532
6533        let actions = Rc::new(RefCell::new(Vec::new()));
6534
6535        cx.add_global_action({
6536            let actions = actions.clone();
6537            move |_: &Action, _: &mut MutableAppContext| {
6538                actions.borrow_mut().push("global".to_string());
6539            }
6540        });
6541
6542        cx.add_action({
6543            let actions = actions.clone();
6544            move |view: &mut ViewA, action: &Action, cx| {
6545                assert_eq!(action.0, "bar");
6546                cx.propagate_action();
6547                actions.borrow_mut().push(format!("{} a", view.id));
6548            }
6549        });
6550
6551        cx.add_action({
6552            let actions = actions.clone();
6553            move |view: &mut ViewA, _: &Action, cx| {
6554                if view.id != 1 {
6555                    cx.add_view(|cx| {
6556                        cx.propagate_action(); // Still works on a nested ViewContext
6557                        ViewB { id: 5 }
6558                    });
6559                }
6560                actions.borrow_mut().push(format!("{} b", view.id));
6561            }
6562        });
6563
6564        cx.add_action({
6565            let actions = actions.clone();
6566            move |view: &mut ViewB, _: &Action, cx| {
6567                cx.propagate_action();
6568                actions.borrow_mut().push(format!("{} c", view.id));
6569            }
6570        });
6571
6572        cx.add_action({
6573            let actions = actions.clone();
6574            move |view: &mut ViewB, _: &Action, cx| {
6575                cx.propagate_action();
6576                actions.borrow_mut().push(format!("{} d", view.id));
6577            }
6578        });
6579
6580        cx.capture_action({
6581            let actions = actions.clone();
6582            move |view: &mut ViewA, _: &Action, cx| {
6583                cx.propagate_action();
6584                actions.borrow_mut().push(format!("{} capture", view.id));
6585            }
6586        });
6587
6588        let observed_actions = Rc::new(RefCell::new(Vec::new()));
6589        cx.observe_actions({
6590            let observed_actions = observed_actions.clone();
6591            move |action_id, _| observed_actions.borrow_mut().push(action_id)
6592        })
6593        .detach();
6594
6595        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
6596        let view_2 = cx.add_view(&view_1, |_| ViewB { id: 2 });
6597        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
6598        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
6599
6600        cx.handle_dispatch_action_from_effect(
6601            window_id,
6602            Some(view_4.id()),
6603            &Action("bar".to_string()),
6604        );
6605
6606        assert_eq!(
6607            *actions.borrow(),
6608            vec![
6609                "1 capture",
6610                "3 capture",
6611                "4 d",
6612                "4 c",
6613                "3 b",
6614                "3 a",
6615                "2 d",
6616                "2 c",
6617                "1 b"
6618            ]
6619        );
6620        assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
6621
6622        // Remove view_1, which doesn't propagate the action
6623
6624        let (window_id, view_2) = cx.add_window(Default::default(), |_| ViewB { id: 2 });
6625        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
6626        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
6627
6628        actions.borrow_mut().clear();
6629        cx.handle_dispatch_action_from_effect(
6630            window_id,
6631            Some(view_4.id()),
6632            &Action("bar".to_string()),
6633        );
6634
6635        assert_eq!(
6636            *actions.borrow(),
6637            vec![
6638                "3 capture",
6639                "4 d",
6640                "4 c",
6641                "3 b",
6642                "3 a",
6643                "2 d",
6644                "2 c",
6645                "global"
6646            ]
6647        );
6648        assert_eq!(
6649            *observed_actions.borrow(),
6650            [Action::default().id(), Action::default().id()]
6651        );
6652    }
6653
6654    #[crate::test(self)]
6655    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
6656        #[derive(Clone, Deserialize, PartialEq)]
6657        pub struct Action(String);
6658
6659        impl_actions!(test, [Action]);
6660
6661        struct View {
6662            id: usize,
6663            keymap_context: KeymapContext,
6664        }
6665
6666        impl Entity for View {
6667            type Event = ();
6668        }
6669
6670        impl super::View for View {
6671            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6672                Empty::new().boxed()
6673            }
6674
6675            fn ui_name() -> &'static str {
6676                "View"
6677            }
6678
6679            fn keymap_context(&self, _: &AppContext) -> KeymapContext {
6680                self.keymap_context.clone()
6681            }
6682        }
6683
6684        impl View {
6685            fn new(id: usize) -> Self {
6686                View {
6687                    id,
6688                    keymap_context: KeymapContext::default(),
6689                }
6690            }
6691        }
6692
6693        let mut view_1 = View::new(1);
6694        let mut view_2 = View::new(2);
6695        let mut view_3 = View::new(3);
6696        view_1.keymap_context.add_identifier("a");
6697        view_2.keymap_context.add_identifier("a");
6698        view_2.keymap_context.add_identifier("b");
6699        view_3.keymap_context.add_identifier("a");
6700        view_3.keymap_context.add_identifier("b");
6701        view_3.keymap_context.add_identifier("c");
6702
6703        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
6704        let view_2 = cx.add_view(&view_1, |_| view_2);
6705        let _view_3 = cx.add_view(&view_2, |cx| {
6706            cx.focus_self();
6707            view_3
6708        });
6709
6710        // This binding only dispatches an action on view 2 because that view will have
6711        // "a" and "b" in its context, but not "c".
6712        cx.add_bindings(vec![Binding::new(
6713            "a",
6714            Action("a".to_string()),
6715            Some("a && b && !c"),
6716        )]);
6717
6718        cx.add_bindings(vec![Binding::new("b", Action("b".to_string()), None)]);
6719
6720        // This binding only dispatches an action on views 2 and 3, because they have
6721        // a parent view with a in its context
6722        cx.add_bindings(vec![Binding::new(
6723            "c",
6724            Action("c".to_string()),
6725            Some("b > c"),
6726        )]);
6727
6728        // This binding only dispatches an action on view 2, because they have
6729        // a parent view with a in its context
6730        cx.add_bindings(vec![Binding::new(
6731            "d",
6732            Action("d".to_string()),
6733            Some("a && !b > b"),
6734        )]);
6735
6736        let actions = Rc::new(RefCell::new(Vec::new()));
6737        cx.add_action({
6738            let actions = actions.clone();
6739            move |view: &mut View, action: &Action, cx| {
6740                actions
6741                    .borrow_mut()
6742                    .push(format!("{} {}", view.id, action.0));
6743
6744                if action.0 == "b" {
6745                    cx.propagate_action();
6746                }
6747            }
6748        });
6749
6750        cx.add_global_action({
6751            let actions = actions.clone();
6752            move |action: &Action, _| {
6753                actions.borrow_mut().push(format!("global {}", action.0));
6754            }
6755        });
6756
6757        cx.dispatch_keystroke(window_id, &Keystroke::parse("a").unwrap());
6758        assert_eq!(&*actions.borrow(), &["2 a"]);
6759        actions.borrow_mut().clear();
6760
6761        cx.dispatch_keystroke(window_id, &Keystroke::parse("b").unwrap());
6762        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
6763        actions.borrow_mut().clear();
6764
6765        cx.dispatch_keystroke(window_id, &Keystroke::parse("c").unwrap());
6766        assert_eq!(&*actions.borrow(), &["3 c"]);
6767        actions.borrow_mut().clear();
6768
6769        cx.dispatch_keystroke(window_id, &Keystroke::parse("d").unwrap());
6770        assert_eq!(&*actions.borrow(), &["2 d"]);
6771        actions.borrow_mut().clear();
6772    }
6773
6774    #[crate::test(self)]
6775    fn test_keystrokes_for_action(cx: &mut MutableAppContext) {
6776        actions!(test, [Action1, Action2, GlobalAction]);
6777
6778        struct View1 {}
6779        struct View2 {}
6780
6781        impl Entity for View1 {
6782            type Event = ();
6783        }
6784        impl Entity for View2 {
6785            type Event = ();
6786        }
6787
6788        impl super::View for View1 {
6789            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6790                Empty::new().boxed()
6791            }
6792            fn ui_name() -> &'static str {
6793                "View1"
6794            }
6795        }
6796        impl super::View for View2 {
6797            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6798                Empty::new().boxed()
6799            }
6800            fn ui_name() -> &'static str {
6801                "View2"
6802            }
6803        }
6804
6805        let (window_id, view_1) = cx.add_window(Default::default(), |_| View1 {});
6806        let view_2 = cx.add_view(&view_1, |cx| {
6807            cx.focus_self();
6808            View2 {}
6809        });
6810
6811        cx.add_action(|_: &mut View1, _: &Action1, _cx| {});
6812        cx.add_action(|_: &mut View2, _: &Action2, _cx| {});
6813        cx.add_global_action(|_: &GlobalAction, _| {});
6814
6815        cx.add_bindings(vec![
6816            Binding::new("a", Action1, Some("View1")),
6817            Binding::new("b", Action2, Some("View1 > View2")),
6818            Binding::new("c", GlobalAction, Some("View3")), // View 3 does not exist
6819        ]);
6820
6821        // Sanity check
6822        assert_eq!(
6823            cx.keystrokes_for_action(window_id, view_1.id(), &Action1)
6824                .unwrap()
6825                .as_slice(),
6826            &[Keystroke::parse("a").unwrap()]
6827        );
6828        assert_eq!(
6829            cx.keystrokes_for_action(window_id, view_2.id(), &Action2)
6830                .unwrap()
6831                .as_slice(),
6832            &[Keystroke::parse("b").unwrap()]
6833        );
6834
6835        // The 'a' keystroke propagates up the view tree from view_2
6836        // to view_1. The action, Action1, is handled by view_1.
6837        assert_eq!(
6838            cx.keystrokes_for_action(window_id, view_2.id(), &Action1)
6839                .unwrap()
6840                .as_slice(),
6841            &[Keystroke::parse("a").unwrap()]
6842        );
6843
6844        // Actions that are handled below the current view don't have bindings
6845        assert_eq!(
6846            cx.keystrokes_for_action(window_id, view_1.id(), &Action2),
6847            None
6848        );
6849
6850        // Actions that are handled in other branches of the tree should not have a binding
6851        assert_eq!(
6852            cx.keystrokes_for_action(window_id, view_2.id(), &GlobalAction),
6853            None
6854        );
6855
6856        // Produces a list of actions and key bindings
6857        fn available_actions(
6858            window_id: usize,
6859            view_id: usize,
6860            cx: &mut MutableAppContext,
6861        ) -> Vec<(&'static str, Vec<Keystroke>)> {
6862            cx.available_actions(window_id, view_id)
6863                .map(|(action_name, _, bindings)| {
6864                    (
6865                        action_name,
6866                        bindings
6867                            .iter()
6868                            .map(|binding| binding.keystrokes()[0].clone())
6869                            .collect::<Vec<_>>(),
6870                    )
6871                })
6872                .sorted_by(|(name1, _), (name2, _)| name1.cmp(name2))
6873                .collect()
6874        }
6875
6876        // Check that global actions do not have a binding, even if a binding does exist in another view
6877        assert_eq!(
6878            &available_actions(window_id, view_1.id(), cx),
6879            &[
6880                ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
6881                ("test::GlobalAction", vec![])
6882            ],
6883        );
6884
6885        // Check that view 1 actions and bindings are available even when called from view 2
6886        assert_eq!(
6887            &available_actions(window_id, view_2.id(), cx),
6888            &[
6889                ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
6890                ("test::Action2", vec![Keystroke::parse("b").unwrap()]),
6891                ("test::GlobalAction", vec![]),
6892            ],
6893        );
6894    }
6895
6896    #[crate::test(self)]
6897    async fn test_model_condition(cx: &mut TestAppContext) {
6898        struct Counter(usize);
6899
6900        impl super::Entity for Counter {
6901            type Event = ();
6902        }
6903
6904        impl Counter {
6905            fn inc(&mut self, cx: &mut ModelContext<Self>) {
6906                self.0 += 1;
6907                cx.notify();
6908            }
6909        }
6910
6911        let model = cx.add_model(|_| Counter(0));
6912
6913        let condition1 = model.condition(cx, |model, _| model.0 == 2);
6914        let condition2 = model.condition(cx, |model, _| model.0 == 3);
6915        smol::pin!(condition1, condition2);
6916
6917        model.update(cx, |model, cx| model.inc(cx));
6918        assert_eq!(poll_once(&mut condition1).await, None);
6919        assert_eq!(poll_once(&mut condition2).await, None);
6920
6921        model.update(cx, |model, cx| model.inc(cx));
6922        assert_eq!(poll_once(&mut condition1).await, Some(()));
6923        assert_eq!(poll_once(&mut condition2).await, None);
6924
6925        model.update(cx, |model, cx| model.inc(cx));
6926        assert_eq!(poll_once(&mut condition2).await, Some(()));
6927
6928        model.update(cx, |_, cx| cx.notify());
6929    }
6930
6931    #[crate::test(self)]
6932    #[should_panic]
6933    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
6934        struct Model;
6935
6936        impl super::Entity for Model {
6937            type Event = ();
6938        }
6939
6940        let model = cx.add_model(|_| Model);
6941        model.condition(cx, |_, _| false).await;
6942    }
6943
6944    #[crate::test(self)]
6945    #[should_panic(expected = "model dropped with pending condition")]
6946    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
6947        struct Model;
6948
6949        impl super::Entity for Model {
6950            type Event = ();
6951        }
6952
6953        let model = cx.add_model(|_| Model);
6954        let condition = model.condition(cx, |_, _| false);
6955        cx.update(|_| drop(model));
6956        condition.await;
6957    }
6958
6959    #[crate::test(self)]
6960    async fn test_view_condition(cx: &mut TestAppContext) {
6961        struct Counter(usize);
6962
6963        impl super::Entity for Counter {
6964            type Event = ();
6965        }
6966
6967        impl super::View for Counter {
6968            fn ui_name() -> &'static str {
6969                "test view"
6970            }
6971
6972            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6973                Empty::new().boxed()
6974            }
6975        }
6976
6977        impl Counter {
6978            fn inc(&mut self, cx: &mut ViewContext<Self>) {
6979                self.0 += 1;
6980                cx.notify();
6981            }
6982        }
6983
6984        let (_, view) = cx.add_window(|_| Counter(0));
6985
6986        let condition1 = view.condition(cx, |view, _| view.0 == 2);
6987        let condition2 = view.condition(cx, |view, _| view.0 == 3);
6988        smol::pin!(condition1, condition2);
6989
6990        view.update(cx, |view, cx| view.inc(cx));
6991        assert_eq!(poll_once(&mut condition1).await, None);
6992        assert_eq!(poll_once(&mut condition2).await, None);
6993
6994        view.update(cx, |view, cx| view.inc(cx));
6995        assert_eq!(poll_once(&mut condition1).await, Some(()));
6996        assert_eq!(poll_once(&mut condition2).await, None);
6997
6998        view.update(cx, |view, cx| view.inc(cx));
6999        assert_eq!(poll_once(&mut condition2).await, Some(()));
7000        view.update(cx, |_, cx| cx.notify());
7001    }
7002
7003    #[crate::test(self)]
7004    #[should_panic]
7005    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
7006        let (_, view) = cx.add_window(|_| TestView::default());
7007        view.condition(cx, |_, _| false).await;
7008    }
7009
7010    #[crate::test(self)]
7011    #[should_panic(expected = "view dropped with pending condition")]
7012    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
7013        let (_, root_view) = cx.add_window(|_| TestView::default());
7014        let view = cx.add_view(&root_view, |_| TestView::default());
7015
7016        let condition = view.condition(cx, |_, _| false);
7017        cx.update(|_| drop(view));
7018        condition.await;
7019    }
7020
7021    #[crate::test(self)]
7022    fn test_refresh_windows(cx: &mut MutableAppContext) {
7023        struct View(usize);
7024
7025        impl super::Entity for View {
7026            type Event = ();
7027        }
7028
7029        impl super::View for View {
7030            fn ui_name() -> &'static str {
7031                "test view"
7032            }
7033
7034            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7035                Empty::new().named(format!("render count: {}", post_inc(&mut self.0)))
7036            }
7037        }
7038
7039        let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
7040        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
7041
7042        assert_eq!(
7043            presenter.borrow().rendered_views[&root_view.id()].name(),
7044            Some("render count: 0")
7045        );
7046
7047        let view = cx.add_view(&root_view, |cx| {
7048            cx.refresh_windows();
7049            View(0)
7050        });
7051
7052        assert_eq!(
7053            presenter.borrow().rendered_views[&root_view.id()].name(),
7054            Some("render count: 1")
7055        );
7056        assert_eq!(
7057            presenter.borrow().rendered_views[&view.id()].name(),
7058            Some("render count: 0")
7059        );
7060
7061        cx.update(|cx| cx.refresh_windows());
7062        assert_eq!(
7063            presenter.borrow().rendered_views[&root_view.id()].name(),
7064            Some("render count: 2")
7065        );
7066        assert_eq!(
7067            presenter.borrow().rendered_views[&view.id()].name(),
7068            Some("render count: 1")
7069        );
7070
7071        cx.update(|cx| {
7072            cx.refresh_windows();
7073            drop(view);
7074        });
7075        assert_eq!(
7076            presenter.borrow().rendered_views[&root_view.id()].name(),
7077            Some("render count: 3")
7078        );
7079        assert_eq!(presenter.borrow().rendered_views.len(), 1);
7080    }
7081
7082    #[crate::test(self)]
7083    async fn test_labeled_tasks(cx: &mut TestAppContext) {
7084        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
7085        let (mut sender, mut reciever) = postage::oneshot::channel::<()>();
7086        let task = cx
7087            .update(|cx| cx.spawn_labeled("Test Label", |_| async move { reciever.recv().await }));
7088
7089        assert_eq!(
7090            Some("Test Label"),
7091            cx.update(|cx| cx.active_labeled_tasks().next())
7092        );
7093        sender
7094            .send(())
7095            .await
7096            .expect("Could not send message to complete task");
7097        task.await;
7098
7099        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
7100    }
7101
7102    #[crate::test(self)]
7103    async fn test_window_activation(cx: &mut TestAppContext) {
7104        struct View(&'static str);
7105
7106        impl super::Entity for View {
7107            type Event = ();
7108        }
7109
7110        impl super::View for View {
7111            fn ui_name() -> &'static str {
7112                "test view"
7113            }
7114
7115            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7116                Empty::new().boxed()
7117            }
7118        }
7119
7120        let events = Rc::new(RefCell::new(Vec::new()));
7121        let (window_1, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7122            cx.observe_window_activation({
7123                let events = events.clone();
7124                move |this, active, _| events.borrow_mut().push((this.0, active))
7125            })
7126            .detach();
7127            View("window 1")
7128        });
7129        assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
7130
7131        let (window_2, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7132            cx.observe_window_activation({
7133                let events = events.clone();
7134                move |this, active, _| events.borrow_mut().push((this.0, active))
7135            })
7136            .detach();
7137            View("window 2")
7138        });
7139        assert_eq!(
7140            mem::take(&mut *events.borrow_mut()),
7141            [("window 1", false), ("window 2", true)]
7142        );
7143
7144        let (window_3, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7145            cx.observe_window_activation({
7146                let events = events.clone();
7147                move |this, active, _| events.borrow_mut().push((this.0, active))
7148            })
7149            .detach();
7150            View("window 3")
7151        });
7152        assert_eq!(
7153            mem::take(&mut *events.borrow_mut()),
7154            [("window 2", false), ("window 3", true)]
7155        );
7156
7157        cx.simulate_window_activation(Some(window_2));
7158        assert_eq!(
7159            mem::take(&mut *events.borrow_mut()),
7160            [("window 3", false), ("window 2", true)]
7161        );
7162
7163        cx.simulate_window_activation(Some(window_1));
7164        assert_eq!(
7165            mem::take(&mut *events.borrow_mut()),
7166            [("window 2", false), ("window 1", true)]
7167        );
7168
7169        cx.simulate_window_activation(Some(window_3));
7170        assert_eq!(
7171            mem::take(&mut *events.borrow_mut()),
7172            [("window 1", false), ("window 3", true)]
7173        );
7174
7175        cx.simulate_window_activation(Some(window_3));
7176        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
7177    }
7178
7179    #[crate::test(self)]
7180    fn test_child_view(cx: &mut MutableAppContext) {
7181        struct Child {
7182            rendered: Rc<Cell<bool>>,
7183            dropped: Rc<Cell<bool>>,
7184        }
7185
7186        impl super::Entity for Child {
7187            type Event = ();
7188        }
7189
7190        impl super::View for Child {
7191            fn ui_name() -> &'static str {
7192                "child view"
7193            }
7194
7195            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7196                self.rendered.set(true);
7197                Empty::new().boxed()
7198            }
7199        }
7200
7201        impl Drop for Child {
7202            fn drop(&mut self) {
7203                self.dropped.set(true);
7204            }
7205        }
7206
7207        struct Parent {
7208            child: Option<ViewHandle<Child>>,
7209        }
7210
7211        impl super::Entity for Parent {
7212            type Event = ();
7213        }
7214
7215        impl super::View for Parent {
7216            fn ui_name() -> &'static str {
7217                "parent view"
7218            }
7219
7220            fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
7221                if let Some(child) = self.child.as_ref() {
7222                    ChildView::new(child, cx).boxed()
7223                } else {
7224                    Empty::new().boxed()
7225                }
7226            }
7227        }
7228
7229        let child_rendered = Rc::new(Cell::new(false));
7230        let child_dropped = Rc::new(Cell::new(false));
7231        let (_, root_view) = cx.add_window(Default::default(), |cx| Parent {
7232            child: Some(cx.add_view(|_| Child {
7233                rendered: child_rendered.clone(),
7234                dropped: child_dropped.clone(),
7235            })),
7236        });
7237        assert!(child_rendered.take());
7238        assert!(!child_dropped.take());
7239
7240        root_view.update(cx, |view, cx| {
7241            view.child.take();
7242            cx.notify();
7243        });
7244        assert!(!child_rendered.take());
7245        assert!(child_dropped.take());
7246    }
7247
7248    #[derive(Default)]
7249    struct TestView {
7250        events: Vec<String>,
7251    }
7252
7253    impl Entity for TestView {
7254        type Event = String;
7255    }
7256
7257    impl View for TestView {
7258        fn ui_name() -> &'static str {
7259            "TestView"
7260        }
7261
7262        fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7263            Empty::new().boxed()
7264        }
7265    }
7266}