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_focus<F, V>(&mut self, handle: &ViewHandle<V>, mut callback: F) -> Subscription
3955    where
3956        F: 'static + FnMut(&mut T, ViewHandle<V>, bool, &mut ViewContext<T>),
3957        V: View,
3958    {
3959        let observer = self.weak_handle();
3960        self.app
3961            .observe_focus(handle, move |observed, focused, cx| {
3962                if let Some(observer) = observer.upgrade(cx) {
3963                    observer.update(cx, |observer, cx| {
3964                        callback(observer, observed, focused, cx);
3965                    });
3966                    true
3967                } else {
3968                    false
3969                }
3970            })
3971    }
3972
3973    pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3974    where
3975        E: Entity,
3976        H: Handle<E>,
3977        F: 'static + FnMut(&mut T, &E, &mut ViewContext<T>),
3978    {
3979        let observer = self.weak_handle();
3980        self.app.observe_release(handle, move |released, cx| {
3981            if let Some(observer) = observer.upgrade(cx) {
3982                observer.update(cx, |observer, cx| {
3983                    callback(observer, released, cx);
3984                });
3985            }
3986        })
3987    }
3988
3989    pub fn observe_actions<F>(&mut self, mut callback: F) -> Subscription
3990    where
3991        F: 'static + FnMut(&mut T, TypeId, &mut ViewContext<T>),
3992    {
3993        let observer = self.weak_handle();
3994        self.app.observe_actions(move |action_id, cx| {
3995            if let Some(observer) = observer.upgrade(cx) {
3996                observer.update(cx, |observer, cx| {
3997                    callback(observer, action_id, cx);
3998                });
3999            }
4000        })
4001    }
4002
4003    pub fn observe_window_activation<F>(&mut self, mut callback: F) -> Subscription
4004    where
4005        F: 'static + FnMut(&mut T, bool, &mut ViewContext<T>),
4006    {
4007        let observer = self.weak_handle();
4008        self.app
4009            .observe_window_activation(self.window_id(), move |active, cx| {
4010                if let Some(observer) = observer.upgrade(cx) {
4011                    observer.update(cx, |observer, cx| {
4012                        callback(observer, active, cx);
4013                    });
4014                    true
4015                } else {
4016                    false
4017                }
4018            })
4019    }
4020
4021    pub fn observe_fullscreen<F>(&mut self, mut callback: F) -> Subscription
4022    where
4023        F: 'static + FnMut(&mut T, bool, &mut ViewContext<T>),
4024    {
4025        let observer = self.weak_handle();
4026        self.app
4027            .observe_fullscreen(self.window_id(), move |active, cx| {
4028                if let Some(observer) = observer.upgrade(cx) {
4029                    observer.update(cx, |observer, cx| {
4030                        callback(observer, active, cx);
4031                    });
4032                    true
4033                } else {
4034                    false
4035                }
4036            })
4037    }
4038
4039    pub fn observe_keystrokes<F>(&mut self, mut callback: F) -> Subscription
4040    where
4041        F: 'static
4042            + FnMut(
4043                &mut T,
4044                &Keystroke,
4045                Option<&Box<dyn Action>>,
4046                &MatchResult,
4047                &mut ViewContext<T>,
4048            ) -> bool,
4049    {
4050        let observer = self.weak_handle();
4051        self.app.observe_keystrokes(
4052            self.window_id(),
4053            move |keystroke, result, handled_by, cx| {
4054                if let Some(observer) = observer.upgrade(cx) {
4055                    observer.update(cx, |observer, cx| {
4056                        callback(observer, keystroke, handled_by, result, cx);
4057                    });
4058                    true
4059                } else {
4060                    false
4061                }
4062            },
4063        )
4064    }
4065
4066    pub fn observe_window_bounds<F>(&mut self, mut callback: F) -> Subscription
4067    where
4068        F: 'static + FnMut(&mut T, WindowBounds, Uuid, &mut ViewContext<T>),
4069    {
4070        let observer = self.weak_handle();
4071        self.app
4072            .observe_window_bounds(self.window_id(), move |bounds, display, cx| {
4073                if let Some(observer) = observer.upgrade(cx) {
4074                    observer.update(cx, |observer, cx| {
4075                        callback(observer, bounds, display, cx);
4076                    });
4077                    true
4078                } else {
4079                    false
4080                }
4081            })
4082    }
4083
4084    pub fn observe_active_labeled_tasks<F>(&mut self, mut callback: F) -> Subscription
4085    where
4086        F: 'static + FnMut(&mut T, &mut ViewContext<T>),
4087    {
4088        let observer = self.weak_handle();
4089        self.app.observe_active_labeled_tasks(move |cx| {
4090            if let Some(observer) = observer.upgrade(cx) {
4091                observer.update(cx, |observer, cx| {
4092                    callback(observer, cx);
4093                });
4094                true
4095            } else {
4096                false
4097            }
4098        })
4099    }
4100
4101    pub fn emit(&mut self, payload: T::Event) {
4102        self.app.pending_effects.push_back(Effect::Event {
4103            entity_id: self.view_id,
4104            payload: Box::new(payload),
4105        });
4106    }
4107
4108    pub fn notify(&mut self) {
4109        self.app.notify_view(self.window_id, self.view_id);
4110    }
4111
4112    pub fn dispatch_action(&mut self, action: impl Action) {
4113        self.app
4114            .dispatch_action_at(self.window_id, self.view_id, action)
4115    }
4116
4117    pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
4118        self.app
4119            .dispatch_any_action_at(self.window_id, self.view_id, action)
4120    }
4121
4122    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>)) {
4123        let handle = self.handle();
4124        self.app.defer(move |cx| {
4125            handle.update(cx, |view, cx| {
4126                callback(view, cx);
4127            })
4128        })
4129    }
4130
4131    pub fn after_window_update(
4132        &mut self,
4133        callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>),
4134    ) {
4135        let handle = self.handle();
4136        self.app.after_window_update(move |cx| {
4137            handle.update(cx, |view, cx| {
4138                callback(view, cx);
4139            })
4140        })
4141    }
4142
4143    pub fn propagate_action(&mut self) {
4144        self.app.halt_action_dispatch = false;
4145    }
4146
4147    pub fn spawn_labeled<F, Fut, S>(&mut self, task_label: &'static str, f: F) -> Task<S>
4148    where
4149        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
4150        Fut: 'static + Future<Output = S>,
4151        S: 'static,
4152    {
4153        let handle = self.handle();
4154        self.app.spawn_labeled(task_label, |cx| f(handle, cx))
4155    }
4156
4157    pub fn spawn<F, Fut, S>(&mut self, f: F) -> Task<S>
4158    where
4159        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
4160        Fut: 'static + Future<Output = S>,
4161        S: 'static,
4162    {
4163        let handle = self.handle();
4164        self.app.spawn(|cx| f(handle, cx))
4165    }
4166
4167    pub fn spawn_weak<F, Fut, S>(&mut self, f: F) -> Task<S>
4168    where
4169        F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut,
4170        Fut: 'static + Future<Output = S>,
4171        S: 'static,
4172    {
4173        let handle = self.weak_handle();
4174        self.app.spawn(|cx| f(handle, cx))
4175    }
4176}
4177
4178pub struct RenderParams {
4179    pub window_id: usize,
4180    pub view_id: usize,
4181    pub titlebar_height: f32,
4182    pub hovered_region_ids: HashSet<MouseRegionId>,
4183    pub clicked_region_ids: Option<(HashSet<MouseRegionId>, MouseButton)>,
4184    pub refreshing: bool,
4185    pub appearance: Appearance,
4186}
4187
4188pub struct RenderContext<'a, T: View> {
4189    pub(crate) window_id: usize,
4190    pub(crate) view_id: usize,
4191    pub(crate) view_type: PhantomData<T>,
4192    pub(crate) hovered_region_ids: HashSet<MouseRegionId>,
4193    pub(crate) clicked_region_ids: Option<(HashSet<MouseRegionId>, MouseButton)>,
4194    pub app: &'a mut MutableAppContext,
4195    pub titlebar_height: f32,
4196    pub appearance: Appearance,
4197    pub refreshing: bool,
4198}
4199
4200#[derive(Debug, Clone, Default)]
4201pub struct MouseState {
4202    pub(crate) hovered: bool,
4203    pub(crate) clicked: Option<MouseButton>,
4204    pub(crate) accessed_hovered: bool,
4205    pub(crate) accessed_clicked: bool,
4206}
4207
4208impl MouseState {
4209    pub fn hovered(&mut self) -> bool {
4210        self.accessed_hovered = true;
4211        self.hovered
4212    }
4213
4214    pub fn clicked(&mut self) -> Option<MouseButton> {
4215        self.accessed_clicked = true;
4216        self.clicked
4217    }
4218
4219    pub fn accessed_hovered(&self) -> bool {
4220        self.accessed_hovered
4221    }
4222
4223    pub fn accessed_clicked(&self) -> bool {
4224        self.accessed_clicked
4225    }
4226}
4227
4228impl<'a, V: View> RenderContext<'a, V> {
4229    fn new(params: RenderParams, app: &'a mut MutableAppContext) -> Self {
4230        Self {
4231            app,
4232            window_id: params.window_id,
4233            view_id: params.view_id,
4234            view_type: PhantomData,
4235            titlebar_height: params.titlebar_height,
4236            hovered_region_ids: params.hovered_region_ids.clone(),
4237            clicked_region_ids: params.clicked_region_ids.clone(),
4238            refreshing: params.refreshing,
4239            appearance: params.appearance,
4240        }
4241    }
4242
4243    pub fn handle(&self) -> WeakViewHandle<V> {
4244        WeakViewHandle::new(self.window_id, self.view_id)
4245    }
4246
4247    pub fn window_id(&self) -> usize {
4248        self.window_id
4249    }
4250
4251    pub fn view_id(&self) -> usize {
4252        self.view_id
4253    }
4254
4255    pub fn mouse_state<Tag: 'static>(&self, region_id: usize) -> MouseState {
4256        let region_id = MouseRegionId::new::<Tag>(self.view_id, region_id);
4257        MouseState {
4258            hovered: self.hovered_region_ids.contains(&region_id),
4259            clicked: self.clicked_region_ids.as_ref().and_then(|(ids, button)| {
4260                if ids.contains(&region_id) {
4261                    Some(*button)
4262                } else {
4263                    None
4264                }
4265            }),
4266            accessed_hovered: false,
4267            accessed_clicked: false,
4268        }
4269    }
4270
4271    pub fn element_state<Tag: 'static, T: 'static>(
4272        &mut self,
4273        element_id: usize,
4274        initial: T,
4275    ) -> ElementStateHandle<T> {
4276        let id = ElementStateId {
4277            view_id: self.view_id(),
4278            element_id,
4279            tag: TypeId::of::<Tag>(),
4280        };
4281        self.cx
4282            .element_states
4283            .entry(id)
4284            .or_insert_with(|| Box::new(initial));
4285        ElementStateHandle::new(id, self.frame_count, &self.cx.ref_counts)
4286    }
4287
4288    pub fn default_element_state<Tag: 'static, T: 'static + Default>(
4289        &mut self,
4290        element_id: usize,
4291    ) -> ElementStateHandle<T> {
4292        self.element_state::<Tag, T>(element_id, T::default())
4293    }
4294}
4295
4296impl AsRef<AppContext> for &AppContext {
4297    fn as_ref(&self) -> &AppContext {
4298        self
4299    }
4300}
4301
4302impl<V: View> Deref for RenderContext<'_, V> {
4303    type Target = MutableAppContext;
4304
4305    fn deref(&self) -> &Self::Target {
4306        self.app
4307    }
4308}
4309
4310impl<V: View> DerefMut for RenderContext<'_, V> {
4311    fn deref_mut(&mut self) -> &mut Self::Target {
4312        self.app
4313    }
4314}
4315
4316impl<V: View> ReadModel for RenderContext<'_, V> {
4317    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
4318        self.app.read_model(handle)
4319    }
4320}
4321
4322impl<V: View> UpdateModel for RenderContext<'_, V> {
4323    fn update_model<T: Entity, O>(
4324        &mut self,
4325        handle: &ModelHandle<T>,
4326        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
4327    ) -> O {
4328        self.app.update_model(handle, update)
4329    }
4330}
4331
4332impl<V: View> ReadView for RenderContext<'_, V> {
4333    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
4334        self.app.read_view(handle)
4335    }
4336}
4337
4338impl<M> AsRef<AppContext> for ViewContext<'_, M> {
4339    fn as_ref(&self) -> &AppContext {
4340        &self.app.cx
4341    }
4342}
4343
4344impl<M> Deref for ViewContext<'_, M> {
4345    type Target = MutableAppContext;
4346
4347    fn deref(&self) -> &Self::Target {
4348        self.app
4349    }
4350}
4351
4352impl<M> DerefMut for ViewContext<'_, M> {
4353    fn deref_mut(&mut self) -> &mut Self::Target {
4354        &mut self.app
4355    }
4356}
4357
4358impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
4359    fn as_mut(&mut self) -> &mut MutableAppContext {
4360        self.app
4361    }
4362}
4363
4364impl<V> ReadModel for ViewContext<'_, V> {
4365    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
4366        self.app.read_model(handle)
4367    }
4368}
4369
4370impl<V> UpgradeModelHandle for ViewContext<'_, V> {
4371    fn upgrade_model_handle<T: Entity>(
4372        &self,
4373        handle: &WeakModelHandle<T>,
4374    ) -> Option<ModelHandle<T>> {
4375        self.cx.upgrade_model_handle(handle)
4376    }
4377
4378    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
4379        self.cx.model_handle_is_upgradable(handle)
4380    }
4381
4382    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
4383        self.cx.upgrade_any_model_handle(handle)
4384    }
4385}
4386
4387impl<V> UpgradeViewHandle for ViewContext<'_, V> {
4388    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
4389        self.cx.upgrade_view_handle(handle)
4390    }
4391
4392    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
4393        self.cx.upgrade_any_view_handle(handle)
4394    }
4395}
4396
4397impl<V: View> UpgradeViewHandle for RenderContext<'_, V> {
4398    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
4399        self.cx.upgrade_view_handle(handle)
4400    }
4401
4402    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
4403        self.cx.upgrade_any_view_handle(handle)
4404    }
4405}
4406
4407impl<V: View> UpdateModel for ViewContext<'_, V> {
4408    fn update_model<T: Entity, O>(
4409        &mut self,
4410        handle: &ModelHandle<T>,
4411        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
4412    ) -> O {
4413        self.app.update_model(handle, update)
4414    }
4415}
4416
4417impl<V: View> ReadView for ViewContext<'_, V> {
4418    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
4419        self.app.read_view(handle)
4420    }
4421}
4422
4423impl<V: View> UpdateView for ViewContext<'_, V> {
4424    fn update_view<T, S>(
4425        &mut self,
4426        handle: &ViewHandle<T>,
4427        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
4428    ) -> S
4429    where
4430        T: View,
4431    {
4432        self.app.update_view(handle, update)
4433    }
4434}
4435
4436pub trait Handle<T> {
4437    type Weak: 'static;
4438    fn id(&self) -> usize;
4439    fn location(&self) -> EntityLocation;
4440    fn downgrade(&self) -> Self::Weak;
4441    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4442    where
4443        Self: Sized;
4444}
4445
4446pub trait WeakHandle {
4447    fn id(&self) -> usize;
4448}
4449
4450#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
4451pub enum EntityLocation {
4452    Model(usize),
4453    View(usize, usize),
4454}
4455
4456pub struct ModelHandle<T: Entity> {
4457    model_id: usize,
4458    model_type: PhantomData<T>,
4459    ref_counts: Arc<Mutex<RefCounts>>,
4460
4461    #[cfg(any(test, feature = "test-support"))]
4462    handle_id: usize,
4463}
4464
4465impl<T: Entity> ModelHandle<T> {
4466    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4467        ref_counts.lock().inc_model(model_id);
4468
4469        #[cfg(any(test, feature = "test-support"))]
4470        let handle_id = ref_counts
4471            .lock()
4472            .leak_detector
4473            .lock()
4474            .handle_created(Some(type_name::<T>()), model_id);
4475
4476        Self {
4477            model_id,
4478            model_type: PhantomData,
4479            ref_counts: ref_counts.clone(),
4480
4481            #[cfg(any(test, feature = "test-support"))]
4482            handle_id,
4483        }
4484    }
4485
4486    pub fn downgrade(&self) -> WeakModelHandle<T> {
4487        WeakModelHandle::new(self.model_id)
4488    }
4489
4490    pub fn id(&self) -> usize {
4491        self.model_id
4492    }
4493
4494    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
4495        cx.read_model(self)
4496    }
4497
4498    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
4499    where
4500        C: ReadModelWith,
4501        F: FnOnce(&T, &AppContext) -> S,
4502    {
4503        let mut read = Some(read);
4504        cx.read_model_with(self, &mut |model, cx| {
4505            let read = read.take().unwrap();
4506            read(model, cx)
4507        })
4508    }
4509
4510    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
4511    where
4512        C: UpdateModel,
4513        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
4514    {
4515        let mut update = Some(update);
4516        cx.update_model(self, &mut |model, cx| {
4517            let update = update.take().unwrap();
4518            update(model, cx)
4519        })
4520    }
4521}
4522
4523impl<T: Entity> Clone for ModelHandle<T> {
4524    fn clone(&self) -> Self {
4525        Self::new(self.model_id, &self.ref_counts)
4526    }
4527}
4528
4529impl<T: Entity> PartialEq for ModelHandle<T> {
4530    fn eq(&self, other: &Self) -> bool {
4531        self.model_id == other.model_id
4532    }
4533}
4534
4535impl<T: Entity> Eq for ModelHandle<T> {}
4536
4537impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
4538    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
4539        self.model_id == other.model_id
4540    }
4541}
4542
4543impl<T: Entity> Hash for ModelHandle<T> {
4544    fn hash<H: Hasher>(&self, state: &mut H) {
4545        self.model_id.hash(state);
4546    }
4547}
4548
4549impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
4550    fn borrow(&self) -> &usize {
4551        &self.model_id
4552    }
4553}
4554
4555impl<T: Entity> Debug for ModelHandle<T> {
4556    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4557        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
4558            .field(&self.model_id)
4559            .finish()
4560    }
4561}
4562
4563unsafe impl<T: Entity> Send for ModelHandle<T> {}
4564unsafe impl<T: Entity> Sync for ModelHandle<T> {}
4565
4566impl<T: Entity> Drop for ModelHandle<T> {
4567    fn drop(&mut self) {
4568        let mut ref_counts = self.ref_counts.lock();
4569        ref_counts.dec_model(self.model_id);
4570
4571        #[cfg(any(test, feature = "test-support"))]
4572        ref_counts
4573            .leak_detector
4574            .lock()
4575            .handle_dropped(self.model_id, self.handle_id);
4576    }
4577}
4578
4579impl<T: Entity> Handle<T> for ModelHandle<T> {
4580    type Weak = WeakModelHandle<T>;
4581
4582    fn id(&self) -> usize {
4583        self.model_id
4584    }
4585
4586    fn location(&self) -> EntityLocation {
4587        EntityLocation::Model(self.model_id)
4588    }
4589
4590    fn downgrade(&self) -> Self::Weak {
4591        self.downgrade()
4592    }
4593
4594    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4595    where
4596        Self: Sized,
4597    {
4598        weak.upgrade(cx)
4599    }
4600}
4601
4602pub struct WeakModelHandle<T> {
4603    model_id: usize,
4604    model_type: PhantomData<T>,
4605}
4606
4607impl<T> WeakHandle for WeakModelHandle<T> {
4608    fn id(&self) -> usize {
4609        self.model_id
4610    }
4611}
4612
4613unsafe impl<T> Send for WeakModelHandle<T> {}
4614unsafe impl<T> Sync for WeakModelHandle<T> {}
4615
4616impl<T: Entity> WeakModelHandle<T> {
4617    fn new(model_id: usize) -> Self {
4618        Self {
4619            model_id,
4620            model_type: PhantomData,
4621        }
4622    }
4623
4624    pub fn id(&self) -> usize {
4625        self.model_id
4626    }
4627
4628    pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
4629        cx.model_handle_is_upgradable(self)
4630    }
4631
4632    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
4633        cx.upgrade_model_handle(self)
4634    }
4635}
4636
4637impl<T> Hash for WeakModelHandle<T> {
4638    fn hash<H: Hasher>(&self, state: &mut H) {
4639        self.model_id.hash(state)
4640    }
4641}
4642
4643impl<T> PartialEq for WeakModelHandle<T> {
4644    fn eq(&self, other: &Self) -> bool {
4645        self.model_id == other.model_id
4646    }
4647}
4648
4649impl<T> Eq for WeakModelHandle<T> {}
4650
4651impl<T: Entity> PartialEq<ModelHandle<T>> for WeakModelHandle<T> {
4652    fn eq(&self, other: &ModelHandle<T>) -> bool {
4653        self.model_id == other.model_id
4654    }
4655}
4656
4657impl<T> Clone for WeakModelHandle<T> {
4658    fn clone(&self) -> Self {
4659        Self {
4660            model_id: self.model_id,
4661            model_type: PhantomData,
4662        }
4663    }
4664}
4665
4666impl<T> Copy for WeakModelHandle<T> {}
4667
4668pub struct ViewHandle<T> {
4669    window_id: usize,
4670    view_id: usize,
4671    view_type: PhantomData<T>,
4672    ref_counts: Arc<Mutex<RefCounts>>,
4673    #[cfg(any(test, feature = "test-support"))]
4674    handle_id: usize,
4675}
4676
4677impl<T: View> ViewHandle<T> {
4678    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4679        ref_counts.lock().inc_view(window_id, view_id);
4680        #[cfg(any(test, feature = "test-support"))]
4681        let handle_id = ref_counts
4682            .lock()
4683            .leak_detector
4684            .lock()
4685            .handle_created(Some(type_name::<T>()), view_id);
4686
4687        Self {
4688            window_id,
4689            view_id,
4690            view_type: PhantomData,
4691            ref_counts: ref_counts.clone(),
4692
4693            #[cfg(any(test, feature = "test-support"))]
4694            handle_id,
4695        }
4696    }
4697
4698    pub fn downgrade(&self) -> WeakViewHandle<T> {
4699        WeakViewHandle::new(self.window_id, self.view_id)
4700    }
4701
4702    pub fn window_id(&self) -> usize {
4703        self.window_id
4704    }
4705
4706    pub fn id(&self) -> usize {
4707        self.view_id
4708    }
4709
4710    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
4711        cx.read_view(self)
4712    }
4713
4714    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
4715    where
4716        C: ReadViewWith,
4717        F: FnOnce(&T, &AppContext) -> S,
4718    {
4719        let mut read = Some(read);
4720        cx.read_view_with(self, &mut |view, cx| {
4721            let read = read.take().unwrap();
4722            read(view, cx)
4723        })
4724    }
4725
4726    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
4727    where
4728        C: UpdateView,
4729        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
4730    {
4731        let mut update = Some(update);
4732        cx.update_view(self, &mut |view, cx| {
4733            let update = update.take().unwrap();
4734            update(view, cx)
4735        })
4736    }
4737
4738    pub fn defer<C, F>(&self, cx: &mut C, update: F)
4739    where
4740        C: AsMut<MutableAppContext>,
4741        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
4742    {
4743        let this = self.clone();
4744        cx.as_mut().defer(move |cx| {
4745            this.update(cx, |view, cx| update(view, cx));
4746        });
4747    }
4748
4749    pub fn is_focused(&self, cx: &AppContext) -> bool {
4750        cx.focused_view_id(self.window_id)
4751            .map_or(false, |focused_id| focused_id == self.view_id)
4752    }
4753}
4754
4755impl<T: View> Clone for ViewHandle<T> {
4756    fn clone(&self) -> Self {
4757        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
4758    }
4759}
4760
4761impl<T> PartialEq for ViewHandle<T> {
4762    fn eq(&self, other: &Self) -> bool {
4763        self.window_id == other.window_id && self.view_id == other.view_id
4764    }
4765}
4766
4767impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
4768    fn eq(&self, other: &WeakViewHandle<T>) -> bool {
4769        self.window_id == other.window_id && self.view_id == other.view_id
4770    }
4771}
4772
4773impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
4774    fn eq(&self, other: &ViewHandle<T>) -> bool {
4775        self.window_id == other.window_id && self.view_id == other.view_id
4776    }
4777}
4778
4779impl<T> Eq for ViewHandle<T> {}
4780
4781impl<T> Hash for ViewHandle<T> {
4782    fn hash<H: Hasher>(&self, state: &mut H) {
4783        self.window_id.hash(state);
4784        self.view_id.hash(state);
4785    }
4786}
4787
4788impl<T> Debug for ViewHandle<T> {
4789    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4790        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
4791            .field("window_id", &self.window_id)
4792            .field("view_id", &self.view_id)
4793            .finish()
4794    }
4795}
4796
4797impl<T> Drop for ViewHandle<T> {
4798    fn drop(&mut self) {
4799        self.ref_counts
4800            .lock()
4801            .dec_view(self.window_id, self.view_id);
4802        #[cfg(any(test, feature = "test-support"))]
4803        self.ref_counts
4804            .lock()
4805            .leak_detector
4806            .lock()
4807            .handle_dropped(self.view_id, self.handle_id);
4808    }
4809}
4810
4811impl<T: View> Handle<T> for ViewHandle<T> {
4812    type Weak = WeakViewHandle<T>;
4813
4814    fn id(&self) -> usize {
4815        self.view_id
4816    }
4817
4818    fn location(&self) -> EntityLocation {
4819        EntityLocation::View(self.window_id, self.view_id)
4820    }
4821
4822    fn downgrade(&self) -> Self::Weak {
4823        self.downgrade()
4824    }
4825
4826    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4827    where
4828        Self: Sized,
4829    {
4830        weak.upgrade(cx)
4831    }
4832}
4833
4834pub struct AnyViewHandle {
4835    window_id: usize,
4836    view_id: usize,
4837    view_type: TypeId,
4838    ref_counts: Arc<Mutex<RefCounts>>,
4839
4840    #[cfg(any(test, feature = "test-support"))]
4841    handle_id: usize,
4842}
4843
4844impl AnyViewHandle {
4845    fn new(
4846        window_id: usize,
4847        view_id: usize,
4848        view_type: TypeId,
4849        ref_counts: Arc<Mutex<RefCounts>>,
4850    ) -> Self {
4851        ref_counts.lock().inc_view(window_id, view_id);
4852
4853        #[cfg(any(test, feature = "test-support"))]
4854        let handle_id = ref_counts
4855            .lock()
4856            .leak_detector
4857            .lock()
4858            .handle_created(None, view_id);
4859
4860        Self {
4861            window_id,
4862            view_id,
4863            view_type,
4864            ref_counts,
4865            #[cfg(any(test, feature = "test-support"))]
4866            handle_id,
4867        }
4868    }
4869
4870    pub fn window_id(&self) -> usize {
4871        self.window_id
4872    }
4873
4874    pub fn id(&self) -> usize {
4875        self.view_id
4876    }
4877
4878    pub fn is<T: 'static>(&self) -> bool {
4879        TypeId::of::<T>() == self.view_type
4880    }
4881
4882    pub fn is_focused(&self, cx: &AppContext) -> bool {
4883        cx.focused_view_id(self.window_id)
4884            .map_or(false, |focused_id| focused_id == self.view_id)
4885    }
4886
4887    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
4888        if self.is::<T>() {
4889            let result = Some(ViewHandle {
4890                window_id: self.window_id,
4891                view_id: self.view_id,
4892                ref_counts: self.ref_counts.clone(),
4893                view_type: PhantomData,
4894                #[cfg(any(test, feature = "test-support"))]
4895                handle_id: self.handle_id,
4896            });
4897            unsafe {
4898                Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
4899            }
4900            std::mem::forget(self);
4901            result
4902        } else {
4903            None
4904        }
4905    }
4906
4907    pub fn downgrade(&self) -> AnyWeakViewHandle {
4908        AnyWeakViewHandle {
4909            window_id: self.window_id,
4910            view_id: self.view_id,
4911            view_type: self.view_type,
4912        }
4913    }
4914
4915    pub fn view_type(&self) -> TypeId {
4916        self.view_type
4917    }
4918
4919    pub fn debug_json(&self, cx: &AppContext) -> serde_json::Value {
4920        cx.views
4921            .get(&(self.window_id, self.view_id))
4922            .map_or_else(|| serde_json::Value::Null, |view| view.debug_json(cx))
4923    }
4924}
4925
4926impl Clone for AnyViewHandle {
4927    fn clone(&self) -> Self {
4928        Self::new(
4929            self.window_id,
4930            self.view_id,
4931            self.view_type,
4932            self.ref_counts.clone(),
4933        )
4934    }
4935}
4936
4937impl From<&AnyViewHandle> for AnyViewHandle {
4938    fn from(handle: &AnyViewHandle) -> Self {
4939        handle.clone()
4940    }
4941}
4942
4943impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
4944    fn from(handle: &ViewHandle<T>) -> Self {
4945        Self::new(
4946            handle.window_id,
4947            handle.view_id,
4948            TypeId::of::<T>(),
4949            handle.ref_counts.clone(),
4950        )
4951    }
4952}
4953
4954impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
4955    fn from(handle: ViewHandle<T>) -> Self {
4956        let any_handle = AnyViewHandle {
4957            window_id: handle.window_id,
4958            view_id: handle.view_id,
4959            view_type: TypeId::of::<T>(),
4960            ref_counts: handle.ref_counts.clone(),
4961            #[cfg(any(test, feature = "test-support"))]
4962            handle_id: handle.handle_id,
4963        };
4964
4965        unsafe {
4966            Arc::decrement_strong_count(Arc::as_ptr(&handle.ref_counts));
4967        }
4968        std::mem::forget(handle);
4969        any_handle
4970    }
4971}
4972
4973impl<T> PartialEq<ViewHandle<T>> for AnyViewHandle {
4974    fn eq(&self, other: &ViewHandle<T>) -> bool {
4975        self.window_id == other.window_id && self.view_id == other.view_id
4976    }
4977}
4978
4979impl Drop for AnyViewHandle {
4980    fn drop(&mut self) {
4981        self.ref_counts
4982            .lock()
4983            .dec_view(self.window_id, self.view_id);
4984        #[cfg(any(test, feature = "test-support"))]
4985        self.ref_counts
4986            .lock()
4987            .leak_detector
4988            .lock()
4989            .handle_dropped(self.view_id, self.handle_id);
4990    }
4991}
4992
4993pub struct AnyModelHandle {
4994    model_id: usize,
4995    model_type: TypeId,
4996    ref_counts: Arc<Mutex<RefCounts>>,
4997
4998    #[cfg(any(test, feature = "test-support"))]
4999    handle_id: usize,
5000}
5001
5002impl AnyModelHandle {
5003    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
5004        ref_counts.lock().inc_model(model_id);
5005
5006        #[cfg(any(test, feature = "test-support"))]
5007        let handle_id = ref_counts
5008            .lock()
5009            .leak_detector
5010            .lock()
5011            .handle_created(None, model_id);
5012
5013        Self {
5014            model_id,
5015            model_type,
5016            ref_counts,
5017
5018            #[cfg(any(test, feature = "test-support"))]
5019            handle_id,
5020        }
5021    }
5022
5023    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
5024        if self.is::<T>() {
5025            let result = Some(ModelHandle {
5026                model_id: self.model_id,
5027                model_type: PhantomData,
5028                ref_counts: self.ref_counts.clone(),
5029
5030                #[cfg(any(test, feature = "test-support"))]
5031                handle_id: self.handle_id,
5032            });
5033            unsafe {
5034                Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
5035            }
5036            std::mem::forget(self);
5037            result
5038        } else {
5039            None
5040        }
5041    }
5042
5043    pub fn downgrade(&self) -> AnyWeakModelHandle {
5044        AnyWeakModelHandle {
5045            model_id: self.model_id,
5046            model_type: self.model_type,
5047        }
5048    }
5049
5050    pub fn is<T: Entity>(&self) -> bool {
5051        self.model_type == TypeId::of::<T>()
5052    }
5053
5054    pub fn model_type(&self) -> TypeId {
5055        self.model_type
5056    }
5057}
5058
5059impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
5060    fn from(handle: ModelHandle<T>) -> Self {
5061        Self::new(
5062            handle.model_id,
5063            TypeId::of::<T>(),
5064            handle.ref_counts.clone(),
5065        )
5066    }
5067}
5068
5069impl Clone for AnyModelHandle {
5070    fn clone(&self) -> Self {
5071        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
5072    }
5073}
5074
5075impl Drop for AnyModelHandle {
5076    fn drop(&mut self) {
5077        let mut ref_counts = self.ref_counts.lock();
5078        ref_counts.dec_model(self.model_id);
5079
5080        #[cfg(any(test, feature = "test-support"))]
5081        ref_counts
5082            .leak_detector
5083            .lock()
5084            .handle_dropped(self.model_id, self.handle_id);
5085    }
5086}
5087
5088#[derive(Hash, PartialEq, Eq, Debug)]
5089pub struct AnyWeakModelHandle {
5090    model_id: usize,
5091    model_type: TypeId,
5092}
5093
5094impl AnyWeakModelHandle {
5095    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
5096        cx.upgrade_any_model_handle(self)
5097    }
5098    pub fn model_type(&self) -> TypeId {
5099        self.model_type
5100    }
5101
5102    fn is<T: 'static>(&self) -> bool {
5103        TypeId::of::<T>() == self.model_type
5104    }
5105
5106    pub fn downcast<T: Entity>(&self) -> Option<WeakModelHandle<T>> {
5107        if self.is::<T>() {
5108            let result = Some(WeakModelHandle {
5109                model_id: self.model_id,
5110                model_type: PhantomData,
5111            });
5112
5113            result
5114        } else {
5115            None
5116        }
5117    }
5118}
5119
5120impl<T: Entity> From<WeakModelHandle<T>> for AnyWeakModelHandle {
5121    fn from(handle: WeakModelHandle<T>) -> Self {
5122        AnyWeakModelHandle {
5123            model_id: handle.model_id,
5124            model_type: TypeId::of::<T>(),
5125        }
5126    }
5127}
5128
5129#[derive(Debug, Copy)]
5130pub struct WeakViewHandle<T> {
5131    window_id: usize,
5132    view_id: usize,
5133    view_type: PhantomData<T>,
5134}
5135
5136impl<T> WeakHandle for WeakViewHandle<T> {
5137    fn id(&self) -> usize {
5138        self.view_id
5139    }
5140}
5141
5142impl<T: View> WeakViewHandle<T> {
5143    fn new(window_id: usize, view_id: usize) -> Self {
5144        Self {
5145            window_id,
5146            view_id,
5147            view_type: PhantomData,
5148        }
5149    }
5150
5151    pub fn id(&self) -> usize {
5152        self.view_id
5153    }
5154
5155    pub fn window_id(&self) -> usize {
5156        self.window_id
5157    }
5158
5159    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
5160        cx.upgrade_view_handle(self)
5161    }
5162}
5163
5164impl<T> Clone for WeakViewHandle<T> {
5165    fn clone(&self) -> Self {
5166        Self {
5167            window_id: self.window_id,
5168            view_id: self.view_id,
5169            view_type: PhantomData,
5170        }
5171    }
5172}
5173
5174impl<T> PartialEq for WeakViewHandle<T> {
5175    fn eq(&self, other: &Self) -> bool {
5176        self.window_id == other.window_id && self.view_id == other.view_id
5177    }
5178}
5179
5180impl<T> Eq for WeakViewHandle<T> {}
5181
5182impl<T> Hash for WeakViewHandle<T> {
5183    fn hash<H: Hasher>(&self, state: &mut H) {
5184        self.window_id.hash(state);
5185        self.view_id.hash(state);
5186    }
5187}
5188
5189pub struct AnyWeakViewHandle {
5190    window_id: usize,
5191    view_id: usize,
5192    view_type: TypeId,
5193}
5194
5195impl AnyWeakViewHandle {
5196    pub fn id(&self) -> usize {
5197        self.view_id
5198    }
5199
5200    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<AnyViewHandle> {
5201        cx.upgrade_any_view_handle(self)
5202    }
5203}
5204
5205impl<T: View> From<WeakViewHandle<T>> for AnyWeakViewHandle {
5206    fn from(handle: WeakViewHandle<T>) -> Self {
5207        AnyWeakViewHandle {
5208            window_id: handle.window_id,
5209            view_id: handle.view_id,
5210            view_type: TypeId::of::<T>(),
5211        }
5212    }
5213}
5214
5215#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
5216pub struct ElementStateId {
5217    view_id: usize,
5218    element_id: usize,
5219    tag: TypeId,
5220}
5221
5222pub struct ElementStateHandle<T> {
5223    value_type: PhantomData<T>,
5224    id: ElementStateId,
5225    ref_counts: Weak<Mutex<RefCounts>>,
5226}
5227
5228impl<T: 'static> ElementStateHandle<T> {
5229    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
5230        ref_counts.lock().inc_element_state(id, frame_id);
5231        Self {
5232            value_type: PhantomData,
5233            id,
5234            ref_counts: Arc::downgrade(ref_counts),
5235        }
5236    }
5237
5238    pub fn id(&self) -> ElementStateId {
5239        self.id
5240    }
5241
5242    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
5243        cx.element_states
5244            .get(&self.id)
5245            .unwrap()
5246            .downcast_ref()
5247            .unwrap()
5248    }
5249
5250    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
5251    where
5252        C: DerefMut<Target = MutableAppContext>,
5253    {
5254        let mut element_state = cx.deref_mut().cx.element_states.remove(&self.id).unwrap();
5255        let result = f(element_state.downcast_mut().unwrap(), cx);
5256        cx.deref_mut()
5257            .cx
5258            .element_states
5259            .insert(self.id, element_state);
5260        result
5261    }
5262}
5263
5264impl<T> Drop for ElementStateHandle<T> {
5265    fn drop(&mut self) {
5266        if let Some(ref_counts) = self.ref_counts.upgrade() {
5267            ref_counts.lock().dec_element_state(self.id);
5268        }
5269    }
5270}
5271
5272#[must_use]
5273pub enum Subscription {
5274    Subscription(callback_collection::Subscription<usize, SubscriptionCallback>),
5275    Observation(callback_collection::Subscription<usize, ObservationCallback>),
5276    GlobalSubscription(callback_collection::Subscription<TypeId, GlobalSubscriptionCallback>),
5277    GlobalObservation(callback_collection::Subscription<TypeId, GlobalObservationCallback>),
5278    FocusObservation(callback_collection::Subscription<usize, FocusObservationCallback>),
5279    WindowActivationObservation(callback_collection::Subscription<usize, WindowActivationCallback>),
5280    WindowFullscreenObservation(callback_collection::Subscription<usize, WindowFullscreenCallback>),
5281    WindowBoundsObservation(callback_collection::Subscription<usize, WindowBoundsCallback>),
5282    KeystrokeObservation(callback_collection::Subscription<usize, KeystrokeCallback>),
5283    ReleaseObservation(callback_collection::Subscription<usize, ReleaseObservationCallback>),
5284    ActionObservation(callback_collection::Subscription<(), ActionObservationCallback>),
5285    ActiveLabeledTasksObservation(
5286        callback_collection::Subscription<(), ActiveLabeledTasksCallback>,
5287    ),
5288}
5289
5290impl Subscription {
5291    pub fn id(&self) -> usize {
5292        match self {
5293            Subscription::Subscription(subscription) => subscription.id(),
5294            Subscription::Observation(subscription) => subscription.id(),
5295            Subscription::GlobalSubscription(subscription) => subscription.id(),
5296            Subscription::GlobalObservation(subscription) => subscription.id(),
5297            Subscription::FocusObservation(subscription) => subscription.id(),
5298            Subscription::WindowActivationObservation(subscription) => subscription.id(),
5299            Subscription::WindowFullscreenObservation(subscription) => subscription.id(),
5300            Subscription::WindowBoundsObservation(subscription) => subscription.id(),
5301            Subscription::KeystrokeObservation(subscription) => subscription.id(),
5302            Subscription::ReleaseObservation(subscription) => subscription.id(),
5303            Subscription::ActionObservation(subscription) => subscription.id(),
5304            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.id(),
5305        }
5306    }
5307
5308    pub fn detach(&mut self) {
5309        match self {
5310            Subscription::Subscription(subscription) => subscription.detach(),
5311            Subscription::GlobalSubscription(subscription) => subscription.detach(),
5312            Subscription::Observation(subscription) => subscription.detach(),
5313            Subscription::GlobalObservation(subscription) => subscription.detach(),
5314            Subscription::FocusObservation(subscription) => subscription.detach(),
5315            Subscription::KeystrokeObservation(subscription) => subscription.detach(),
5316            Subscription::WindowActivationObservation(subscription) => subscription.detach(),
5317            Subscription::WindowFullscreenObservation(subscription) => subscription.detach(),
5318            Subscription::WindowBoundsObservation(subscription) => subscription.detach(),
5319            Subscription::ReleaseObservation(subscription) => subscription.detach(),
5320            Subscription::ActionObservation(subscription) => subscription.detach(),
5321            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.detach(),
5322        }
5323    }
5324}
5325
5326#[cfg(test)]
5327mod tests {
5328    use super::*;
5329    use crate::{actions, elements::*, impl_actions, MouseButton, MouseButtonEvent};
5330    use itertools::Itertools;
5331    use postage::{sink::Sink, stream::Stream};
5332    use serde::Deserialize;
5333    use smol::future::poll_once;
5334    use std::{
5335        cell::Cell,
5336        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
5337    };
5338
5339    #[crate::test(self)]
5340    fn test_model_handles(cx: &mut MutableAppContext) {
5341        struct Model {
5342            other: Option<ModelHandle<Model>>,
5343            events: Vec<String>,
5344        }
5345
5346        impl Entity for Model {
5347            type Event = usize;
5348        }
5349
5350        impl Model {
5351            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
5352                if let Some(other) = other.as_ref() {
5353                    cx.observe(other, |me, _, _| {
5354                        me.events.push("notified".into());
5355                    })
5356                    .detach();
5357                    cx.subscribe(other, |me, _, event, _| {
5358                        me.events.push(format!("observed event {}", event));
5359                    })
5360                    .detach();
5361                }
5362
5363                Self {
5364                    other,
5365                    events: Vec::new(),
5366                }
5367            }
5368        }
5369
5370        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
5371        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
5372        assert_eq!(cx.cx.models.len(), 2);
5373
5374        handle_1.update(cx, |model, cx| {
5375            model.events.push("updated".into());
5376            cx.emit(1);
5377            cx.notify();
5378            cx.emit(2);
5379        });
5380        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5381        assert_eq!(
5382            handle_2.read(cx).events,
5383            vec![
5384                "observed event 1".to_string(),
5385                "notified".to_string(),
5386                "observed event 2".to_string(),
5387            ]
5388        );
5389
5390        handle_2.update(cx, |model, _| {
5391            drop(handle_1);
5392            model.other.take();
5393        });
5394
5395        assert_eq!(cx.cx.models.len(), 1);
5396        assert!(cx.subscriptions.is_empty());
5397        assert!(cx.observations.is_empty());
5398    }
5399
5400    #[crate::test(self)]
5401    fn test_model_events(cx: &mut MutableAppContext) {
5402        #[derive(Default)]
5403        struct Model {
5404            events: Vec<usize>,
5405        }
5406
5407        impl Entity for Model {
5408            type Event = usize;
5409        }
5410
5411        let handle_1 = cx.add_model(|_| Model::default());
5412        let handle_2 = cx.add_model(|_| Model::default());
5413
5414        handle_1.update(cx, |_, cx| {
5415            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
5416                model.events.push(*event);
5417
5418                cx.subscribe(&emitter, |model, _, event, _| {
5419                    model.events.push(*event * 2);
5420                })
5421                .detach();
5422            })
5423            .detach();
5424        });
5425
5426        handle_2.update(cx, |_, c| c.emit(7));
5427        assert_eq!(handle_1.read(cx).events, vec![7]);
5428
5429        handle_2.update(cx, |_, c| c.emit(5));
5430        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
5431    }
5432
5433    #[crate::test(self)]
5434    fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
5435        #[derive(Default)]
5436        struct Model;
5437
5438        impl Entity for Model {
5439            type Event = ();
5440        }
5441
5442        let events = Rc::new(RefCell::new(Vec::new()));
5443        cx.add_model(|cx| {
5444            drop(cx.subscribe(&cx.handle(), {
5445                let events = events.clone();
5446                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
5447            }));
5448            cx.subscribe(&cx.handle(), {
5449                let events = events.clone();
5450                move |_, _, _, _| events.borrow_mut().push("before emit")
5451            })
5452            .detach();
5453            cx.emit(());
5454            cx.subscribe(&cx.handle(), {
5455                let events = events.clone();
5456                move |_, _, _, _| events.borrow_mut().push("after emit")
5457            })
5458            .detach();
5459            Model
5460        });
5461        assert_eq!(*events.borrow(), ["before emit"]);
5462    }
5463
5464    #[crate::test(self)]
5465    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
5466        #[derive(Default)]
5467        struct Model {
5468            count: usize,
5469            events: Vec<usize>,
5470        }
5471
5472        impl Entity for Model {
5473            type Event = ();
5474        }
5475
5476        let handle_1 = cx.add_model(|_| Model::default());
5477        let handle_2 = cx.add_model(|_| Model::default());
5478
5479        handle_1.update(cx, |_, c| {
5480            c.observe(&handle_2, move |model, observed, c| {
5481                model.events.push(observed.read(c).count);
5482                c.observe(&observed, |model, observed, c| {
5483                    model.events.push(observed.read(c).count * 2);
5484                })
5485                .detach();
5486            })
5487            .detach();
5488        });
5489
5490        handle_2.update(cx, |model, c| {
5491            model.count = 7;
5492            c.notify()
5493        });
5494        assert_eq!(handle_1.read(cx).events, vec![7]);
5495
5496        handle_2.update(cx, |model, c| {
5497            model.count = 5;
5498            c.notify()
5499        });
5500        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
5501    }
5502
5503    #[crate::test(self)]
5504    fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
5505        #[derive(Default)]
5506        struct Model;
5507
5508        impl Entity for Model {
5509            type Event = ();
5510        }
5511
5512        let events = Rc::new(RefCell::new(Vec::new()));
5513        cx.add_model(|cx| {
5514            drop(cx.observe(&cx.handle(), {
5515                let events = events.clone();
5516                move |_, _, _| events.borrow_mut().push("dropped before flush")
5517            }));
5518            cx.observe(&cx.handle(), {
5519                let events = events.clone();
5520                move |_, _, _| events.borrow_mut().push("before notify")
5521            })
5522            .detach();
5523            cx.notify();
5524            cx.observe(&cx.handle(), {
5525                let events = events.clone();
5526                move |_, _, _| events.borrow_mut().push("after notify")
5527            })
5528            .detach();
5529            Model
5530        });
5531        assert_eq!(*events.borrow(), ["before notify"]);
5532    }
5533
5534    #[crate::test(self)]
5535    fn test_defer_and_after_window_update(cx: &mut MutableAppContext) {
5536        struct View {
5537            render_count: usize,
5538        }
5539
5540        impl Entity for View {
5541            type Event = usize;
5542        }
5543
5544        impl super::View for View {
5545            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5546                post_inc(&mut self.render_count);
5547                Empty::new().boxed()
5548            }
5549
5550            fn ui_name() -> &'static str {
5551                "View"
5552            }
5553        }
5554
5555        let (_, view) = cx.add_window(Default::default(), |_| View { render_count: 0 });
5556        let called_defer = Rc::new(AtomicBool::new(false));
5557        let called_after_window_update = Rc::new(AtomicBool::new(false));
5558
5559        view.update(cx, |this, cx| {
5560            assert_eq!(this.render_count, 1);
5561            cx.defer({
5562                let called_defer = called_defer.clone();
5563                move |this, _| {
5564                    assert_eq!(this.render_count, 1);
5565                    called_defer.store(true, SeqCst);
5566                }
5567            });
5568            cx.after_window_update({
5569                let called_after_window_update = called_after_window_update.clone();
5570                move |this, cx| {
5571                    assert_eq!(this.render_count, 2);
5572                    called_after_window_update.store(true, SeqCst);
5573                    cx.notify();
5574                }
5575            });
5576            assert!(!called_defer.load(SeqCst));
5577            assert!(!called_after_window_update.load(SeqCst));
5578            cx.notify();
5579        });
5580
5581        assert!(called_defer.load(SeqCst));
5582        assert!(called_after_window_update.load(SeqCst));
5583        assert_eq!(view.read(cx).render_count, 3);
5584    }
5585
5586    #[crate::test(self)]
5587    fn test_view_handles(cx: &mut MutableAppContext) {
5588        struct View {
5589            other: Option<ViewHandle<View>>,
5590            events: Vec<String>,
5591        }
5592
5593        impl Entity for View {
5594            type Event = usize;
5595        }
5596
5597        impl super::View for View {
5598            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5599                Empty::new().boxed()
5600            }
5601
5602            fn ui_name() -> &'static str {
5603                "View"
5604            }
5605        }
5606
5607        impl View {
5608            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
5609                if let Some(other) = other.as_ref() {
5610                    cx.subscribe(other, |me, _, event, _| {
5611                        me.events.push(format!("observed event {}", event));
5612                    })
5613                    .detach();
5614                }
5615                Self {
5616                    other,
5617                    events: Vec::new(),
5618                }
5619            }
5620        }
5621
5622        let (_, root_view) = cx.add_window(Default::default(), |cx| View::new(None, cx));
5623        let handle_1 = cx.add_view(&root_view, |cx| View::new(None, cx));
5624        let handle_2 = cx.add_view(&root_view, |cx| View::new(Some(handle_1.clone()), cx));
5625        assert_eq!(cx.cx.views.len(), 3);
5626
5627        handle_1.update(cx, |view, cx| {
5628            view.events.push("updated".into());
5629            cx.emit(1);
5630            cx.emit(2);
5631        });
5632        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5633        assert_eq!(
5634            handle_2.read(cx).events,
5635            vec![
5636                "observed event 1".to_string(),
5637                "observed event 2".to_string(),
5638            ]
5639        );
5640
5641        handle_2.update(cx, |view, _| {
5642            drop(handle_1);
5643            view.other.take();
5644        });
5645
5646        assert_eq!(cx.cx.views.len(), 2);
5647        assert!(cx.subscriptions.is_empty());
5648        assert!(cx.observations.is_empty());
5649    }
5650
5651    #[crate::test(self)]
5652    fn test_add_window(cx: &mut MutableAppContext) {
5653        struct View {
5654            mouse_down_count: Arc<AtomicUsize>,
5655        }
5656
5657        impl Entity for View {
5658            type Event = ();
5659        }
5660
5661        impl super::View for View {
5662            fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
5663                enum Handler {}
5664                let mouse_down_count = self.mouse_down_count.clone();
5665                MouseEventHandler::<Handler>::new(0, cx, |_, _| Empty::new().boxed())
5666                    .on_down(MouseButton::Left, move |_, _| {
5667                        mouse_down_count.fetch_add(1, SeqCst);
5668                    })
5669                    .boxed()
5670            }
5671
5672            fn ui_name() -> &'static str {
5673                "View"
5674            }
5675        }
5676
5677        let mouse_down_count = Arc::new(AtomicUsize::new(0));
5678        let (window_id, _) = cx.add_window(Default::default(), |_| View {
5679            mouse_down_count: mouse_down_count.clone(),
5680        });
5681        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
5682        // Ensure window's root element is in a valid lifecycle state.
5683        presenter.borrow_mut().dispatch_event(
5684            Event::MouseDown(MouseButtonEvent {
5685                position: Default::default(),
5686                button: MouseButton::Left,
5687                modifiers: Default::default(),
5688                click_count: 1,
5689            }),
5690            false,
5691            cx,
5692        );
5693        assert_eq!(mouse_down_count.load(SeqCst), 1);
5694    }
5695
5696    #[crate::test(self)]
5697    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
5698        struct Model {
5699            released: Rc<Cell<bool>>,
5700        }
5701
5702        struct View {
5703            released: Rc<Cell<bool>>,
5704        }
5705
5706        impl Entity for Model {
5707            type Event = ();
5708
5709            fn release(&mut self, _: &mut MutableAppContext) {
5710                self.released.set(true);
5711            }
5712        }
5713
5714        impl Entity for View {
5715            type Event = ();
5716
5717            fn release(&mut self, _: &mut MutableAppContext) {
5718                self.released.set(true);
5719            }
5720        }
5721
5722        impl super::View for View {
5723            fn ui_name() -> &'static str {
5724                "View"
5725            }
5726
5727            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5728                Empty::new().boxed()
5729            }
5730        }
5731
5732        let model_released = Rc::new(Cell::new(false));
5733        let model_release_observed = Rc::new(Cell::new(false));
5734        let view_released = Rc::new(Cell::new(false));
5735        let view_release_observed = Rc::new(Cell::new(false));
5736
5737        let model = cx.add_model(|_| Model {
5738            released: model_released.clone(),
5739        });
5740        let (window_id, view) = cx.add_window(Default::default(), |_| View {
5741            released: view_released.clone(),
5742        });
5743        assert!(!model_released.get());
5744        assert!(!view_released.get());
5745
5746        cx.observe_release(&model, {
5747            let model_release_observed = model_release_observed.clone();
5748            move |_, _| model_release_observed.set(true)
5749        })
5750        .detach();
5751        cx.observe_release(&view, {
5752            let view_release_observed = view_release_observed.clone();
5753            move |_, _| view_release_observed.set(true)
5754        })
5755        .detach();
5756
5757        cx.update(move |_| {
5758            drop(model);
5759        });
5760        assert!(model_released.get());
5761        assert!(model_release_observed.get());
5762
5763        drop(view);
5764        cx.remove_window(window_id);
5765        assert!(view_released.get());
5766        assert!(view_release_observed.get());
5767    }
5768
5769    #[crate::test(self)]
5770    fn test_view_events(cx: &mut MutableAppContext) {
5771        struct Model;
5772
5773        impl Entity for Model {
5774            type Event = String;
5775        }
5776
5777        let (_, handle_1) = cx.add_window(Default::default(), |_| TestView::default());
5778        let handle_2 = cx.add_view(&handle_1, |_| TestView::default());
5779        let handle_3 = cx.add_model(|_| Model);
5780
5781        handle_1.update(cx, |_, cx| {
5782            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
5783                me.events.push(event.clone());
5784
5785                cx.subscribe(&emitter, |me, _, event, _| {
5786                    me.events.push(format!("{event} from inner"));
5787                })
5788                .detach();
5789            })
5790            .detach();
5791
5792            cx.subscribe(&handle_3, |me, _, event, _| {
5793                me.events.push(event.clone());
5794            })
5795            .detach();
5796        });
5797
5798        handle_2.update(cx, |_, c| c.emit("7".into()));
5799        assert_eq!(handle_1.read(cx).events, vec!["7"]);
5800
5801        handle_2.update(cx, |_, c| c.emit("5".into()));
5802        assert_eq!(handle_1.read(cx).events, vec!["7", "5", "5 from inner"]);
5803
5804        handle_3.update(cx, |_, c| c.emit("9".into()));
5805        assert_eq!(
5806            handle_1.read(cx).events,
5807            vec!["7", "5", "5 from inner", "9"]
5808        );
5809    }
5810
5811    #[crate::test(self)]
5812    fn test_global_events(cx: &mut MutableAppContext) {
5813        #[derive(Clone, Debug, Eq, PartialEq)]
5814        struct GlobalEvent(u64);
5815
5816        let events = Rc::new(RefCell::new(Vec::new()));
5817        let first_subscription;
5818        let second_subscription;
5819
5820        {
5821            let events = events.clone();
5822            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5823                events.borrow_mut().push(("First", e.clone()));
5824            });
5825        }
5826
5827        {
5828            let events = events.clone();
5829            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5830                events.borrow_mut().push(("Second", e.clone()));
5831            });
5832        }
5833
5834        cx.update(|cx| {
5835            cx.emit_global(GlobalEvent(1));
5836            cx.emit_global(GlobalEvent(2));
5837        });
5838
5839        drop(first_subscription);
5840
5841        cx.update(|cx| {
5842            cx.emit_global(GlobalEvent(3));
5843        });
5844
5845        drop(second_subscription);
5846
5847        cx.update(|cx| {
5848            cx.emit_global(GlobalEvent(4));
5849        });
5850
5851        assert_eq!(
5852            &*events.borrow(),
5853            &[
5854                ("First", GlobalEvent(1)),
5855                ("Second", GlobalEvent(1)),
5856                ("First", GlobalEvent(2)),
5857                ("Second", GlobalEvent(2)),
5858                ("Second", GlobalEvent(3)),
5859            ]
5860        );
5861    }
5862
5863    #[crate::test(self)]
5864    fn test_global_events_emitted_before_subscription_in_same_update_cycle(
5865        cx: &mut MutableAppContext,
5866    ) {
5867        let events = Rc::new(RefCell::new(Vec::new()));
5868        cx.update(|cx| {
5869            {
5870                let events = events.clone();
5871                drop(cx.subscribe_global(move |_: &(), _| {
5872                    events.borrow_mut().push("dropped before emit");
5873                }));
5874            }
5875
5876            {
5877                let events = events.clone();
5878                cx.subscribe_global(move |_: &(), _| {
5879                    events.borrow_mut().push("before emit");
5880                })
5881                .detach();
5882            }
5883
5884            cx.emit_global(());
5885
5886            {
5887                let events = events.clone();
5888                cx.subscribe_global(move |_: &(), _| {
5889                    events.borrow_mut().push("after emit");
5890                })
5891                .detach();
5892            }
5893        });
5894
5895        assert_eq!(*events.borrow(), ["before emit"]);
5896    }
5897
5898    #[crate::test(self)]
5899    fn test_global_nested_events(cx: &mut MutableAppContext) {
5900        #[derive(Clone, Debug, Eq, PartialEq)]
5901        struct GlobalEvent(u64);
5902
5903        let events = Rc::new(RefCell::new(Vec::new()));
5904
5905        {
5906            let events = events.clone();
5907            cx.subscribe_global(move |e: &GlobalEvent, cx| {
5908                events.borrow_mut().push(("Outer", e.clone()));
5909
5910                if e.0 == 1 {
5911                    let events = events.clone();
5912                    cx.subscribe_global(move |e: &GlobalEvent, _| {
5913                        events.borrow_mut().push(("Inner", e.clone()));
5914                    })
5915                    .detach();
5916                }
5917            })
5918            .detach();
5919        }
5920
5921        cx.update(|cx| {
5922            cx.emit_global(GlobalEvent(1));
5923            cx.emit_global(GlobalEvent(2));
5924            cx.emit_global(GlobalEvent(3));
5925        });
5926        cx.update(|cx| {
5927            cx.emit_global(GlobalEvent(4));
5928        });
5929
5930        assert_eq!(
5931            &*events.borrow(),
5932            &[
5933                ("Outer", GlobalEvent(1)),
5934                ("Outer", GlobalEvent(2)),
5935                ("Outer", GlobalEvent(3)),
5936                ("Outer", GlobalEvent(4)),
5937                ("Inner", GlobalEvent(4)),
5938            ]
5939        );
5940    }
5941
5942    #[crate::test(self)]
5943    fn test_global(cx: &mut MutableAppContext) {
5944        type Global = usize;
5945
5946        let observation_count = Rc::new(RefCell::new(0));
5947        let subscription = cx.observe_global::<Global, _>({
5948            let observation_count = observation_count.clone();
5949            move |_| {
5950                *observation_count.borrow_mut() += 1;
5951            }
5952        });
5953
5954        assert!(!cx.has_global::<Global>());
5955        assert_eq!(cx.default_global::<Global>(), &0);
5956        assert_eq!(*observation_count.borrow(), 1);
5957        assert!(cx.has_global::<Global>());
5958        assert_eq!(
5959            cx.update_global::<Global, _, _>(|global, _| {
5960                *global = 1;
5961                "Update Result"
5962            }),
5963            "Update Result"
5964        );
5965        assert_eq!(*observation_count.borrow(), 2);
5966        assert_eq!(cx.global::<Global>(), &1);
5967
5968        drop(subscription);
5969        cx.update_global::<Global, _, _>(|global, _| {
5970            *global = 2;
5971        });
5972        assert_eq!(*observation_count.borrow(), 2);
5973
5974        type OtherGlobal = f32;
5975
5976        let observation_count = Rc::new(RefCell::new(0));
5977        cx.observe_global::<OtherGlobal, _>({
5978            let observation_count = observation_count.clone();
5979            move |_| {
5980                *observation_count.borrow_mut() += 1;
5981            }
5982        })
5983        .detach();
5984
5985        assert_eq!(
5986            cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
5987                assert_eq!(global, &0.0);
5988                *global = 2.0;
5989                "Default update result"
5990            }),
5991            "Default update result"
5992        );
5993        assert_eq!(cx.global::<OtherGlobal>(), &2.0);
5994        assert_eq!(*observation_count.borrow(), 1);
5995    }
5996
5997    #[crate::test(self)]
5998    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
5999        struct Model;
6000
6001        impl Entity for Model {
6002            type Event = ();
6003        }
6004
6005        let (_, root_view) = cx.add_window(Default::default(), |_| TestView::default());
6006        let observing_view = cx.add_view(&root_view, |_| TestView::default());
6007        let emitting_view = cx.add_view(&root_view, |_| TestView::default());
6008        let observing_model = cx.add_model(|_| Model);
6009        let observed_model = cx.add_model(|_| Model);
6010
6011        observing_view.update(cx, |_, cx| {
6012            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
6013            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
6014        });
6015        observing_model.update(cx, |_, cx| {
6016            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
6017        });
6018
6019        cx.update(|_| {
6020            drop(observing_view);
6021            drop(observing_model);
6022        });
6023
6024        emitting_view.update(cx, |_, cx| cx.emit(Default::default()));
6025        observed_model.update(cx, |_, cx| cx.emit(()));
6026    }
6027
6028    #[crate::test(self)]
6029    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
6030        let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
6031            drop(cx.subscribe(&cx.handle(), {
6032                move |this, _, _, _| this.events.push("dropped before flush".into())
6033            }));
6034            cx.subscribe(&cx.handle(), {
6035                move |this, _, _, _| this.events.push("before emit".into())
6036            })
6037            .detach();
6038            cx.emit("the event".into());
6039            cx.subscribe(&cx.handle(), {
6040                move |this, _, _, _| this.events.push("after emit".into())
6041            })
6042            .detach();
6043            TestView { events: Vec::new() }
6044        });
6045
6046        assert_eq!(view.read(cx).events, ["before emit"]);
6047    }
6048
6049    #[crate::test(self)]
6050    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
6051        #[derive(Default)]
6052        struct Model {
6053            state: String,
6054        }
6055
6056        impl Entity for Model {
6057            type Event = ();
6058        }
6059
6060        let (_, view) = cx.add_window(Default::default(), |_| TestView::default());
6061        let model = cx.add_model(|_| Model {
6062            state: "old-state".into(),
6063        });
6064
6065        view.update(cx, |_, c| {
6066            c.observe(&model, |me, observed, c| {
6067                me.events.push(observed.read(c).state.clone())
6068            })
6069            .detach();
6070        });
6071
6072        model.update(cx, |model, cx| {
6073            model.state = "new-state".into();
6074            cx.notify();
6075        });
6076        assert_eq!(view.read(cx).events, vec!["new-state"]);
6077    }
6078
6079    #[crate::test(self)]
6080    fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
6081        let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
6082            drop(cx.observe(&cx.handle(), {
6083                move |this, _, _| this.events.push("dropped before flush".into())
6084            }));
6085            cx.observe(&cx.handle(), {
6086                move |this, _, _| this.events.push("before notify".into())
6087            })
6088            .detach();
6089            cx.notify();
6090            cx.observe(&cx.handle(), {
6091                move |this, _, _| this.events.push("after notify".into())
6092            })
6093            .detach();
6094            TestView { events: Vec::new() }
6095        });
6096
6097        assert_eq!(view.read(cx).events, ["before notify"]);
6098    }
6099
6100    #[crate::test(self)]
6101    fn test_notify_and_drop_observe_subscription_in_same_update_cycle(cx: &mut MutableAppContext) {
6102        struct Model;
6103        impl Entity for Model {
6104            type Event = ();
6105        }
6106
6107        let model = cx.add_model(|_| Model);
6108        let (_, view) = cx.add_window(Default::default(), |_| TestView::default());
6109
6110        view.update(cx, |_, cx| {
6111            model.update(cx, |_, cx| cx.notify());
6112            drop(cx.observe(&model, move |this, _, _| {
6113                this.events.push("model notified".into());
6114            }));
6115            model.update(cx, |_, cx| cx.notify());
6116        });
6117
6118        for _ in 0..3 {
6119            model.update(cx, |_, cx| cx.notify());
6120        }
6121
6122        assert_eq!(view.read(cx).events, Vec::<String>::new());
6123    }
6124
6125    #[crate::test(self)]
6126    fn test_dropping_observers(cx: &mut MutableAppContext) {
6127        struct Model;
6128
6129        impl Entity for Model {
6130            type Event = ();
6131        }
6132
6133        let (_, root_view) = cx.add_window(Default::default(), |_| TestView::default());
6134        let observing_view = cx.add_view(root_view, |_| TestView::default());
6135        let observing_model = cx.add_model(|_| Model);
6136        let observed_model = cx.add_model(|_| Model);
6137
6138        observing_view.update(cx, |_, cx| {
6139            cx.observe(&observed_model, |_, _, _| {}).detach();
6140        });
6141        observing_model.update(cx, |_, cx| {
6142            cx.observe(&observed_model, |_, _, _| {}).detach();
6143        });
6144
6145        cx.update(|_| {
6146            drop(observing_view);
6147            drop(observing_model);
6148        });
6149
6150        observed_model.update(cx, |_, cx| cx.notify());
6151    }
6152
6153    #[crate::test(self)]
6154    fn test_dropping_subscriptions_during_callback(cx: &mut MutableAppContext) {
6155        struct Model;
6156
6157        impl Entity for Model {
6158            type Event = u64;
6159        }
6160
6161        // Events
6162        let observing_model = cx.add_model(|_| Model);
6163        let observed_model = cx.add_model(|_| Model);
6164
6165        let events = Rc::new(RefCell::new(Vec::new()));
6166
6167        observing_model.update(cx, |_, cx| {
6168            let events = events.clone();
6169            let subscription = Rc::new(RefCell::new(None));
6170            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
6171                let subscription = subscription.clone();
6172                move |_, _, e, _| {
6173                    subscription.borrow_mut().take();
6174                    events.borrow_mut().push(*e);
6175                }
6176            }));
6177        });
6178
6179        observed_model.update(cx, |_, cx| {
6180            cx.emit(1);
6181            cx.emit(2);
6182        });
6183
6184        assert_eq!(*events.borrow(), [1]);
6185
6186        // Global Events
6187        #[derive(Clone, Debug, Eq, PartialEq)]
6188        struct GlobalEvent(u64);
6189
6190        let events = Rc::new(RefCell::new(Vec::new()));
6191
6192        {
6193            let events = events.clone();
6194            let subscription = Rc::new(RefCell::new(None));
6195            *subscription.borrow_mut() = Some(cx.subscribe_global({
6196                let subscription = subscription.clone();
6197                move |e: &GlobalEvent, _| {
6198                    subscription.borrow_mut().take();
6199                    events.borrow_mut().push(e.clone());
6200                }
6201            }));
6202        }
6203
6204        cx.update(|cx| {
6205            cx.emit_global(GlobalEvent(1));
6206            cx.emit_global(GlobalEvent(2));
6207        });
6208
6209        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
6210
6211        // Model Observation
6212        let observing_model = cx.add_model(|_| Model);
6213        let observed_model = cx.add_model(|_| Model);
6214
6215        let observation_count = Rc::new(RefCell::new(0));
6216
6217        observing_model.update(cx, |_, cx| {
6218            let observation_count = observation_count.clone();
6219            let subscription = Rc::new(RefCell::new(None));
6220            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
6221                let subscription = subscription.clone();
6222                move |_, _, _| {
6223                    subscription.borrow_mut().take();
6224                    *observation_count.borrow_mut() += 1;
6225                }
6226            }));
6227        });
6228
6229        observed_model.update(cx, |_, cx| {
6230            cx.notify();
6231        });
6232
6233        observed_model.update(cx, |_, cx| {
6234            cx.notify();
6235        });
6236
6237        assert_eq!(*observation_count.borrow(), 1);
6238
6239        // View Observation
6240        struct View;
6241
6242        impl Entity for View {
6243            type Event = ();
6244        }
6245
6246        impl super::View for View {
6247            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6248                Empty::new().boxed()
6249            }
6250
6251            fn ui_name() -> &'static str {
6252                "View"
6253            }
6254        }
6255
6256        let (_, root_view) = cx.add_window(Default::default(), |_| View);
6257        let observing_view = cx.add_view(&root_view, |_| View);
6258        let observed_view = cx.add_view(&root_view, |_| View);
6259
6260        let observation_count = Rc::new(RefCell::new(0));
6261        observing_view.update(cx, |_, cx| {
6262            let observation_count = observation_count.clone();
6263            let subscription = Rc::new(RefCell::new(None));
6264            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
6265                let subscription = subscription.clone();
6266                move |_, _, _| {
6267                    subscription.borrow_mut().take();
6268                    *observation_count.borrow_mut() += 1;
6269                }
6270            }));
6271        });
6272
6273        observed_view.update(cx, |_, cx| {
6274            cx.notify();
6275        });
6276
6277        observed_view.update(cx, |_, cx| {
6278            cx.notify();
6279        });
6280
6281        assert_eq!(*observation_count.borrow(), 1);
6282
6283        // Global Observation
6284        let observation_count = Rc::new(RefCell::new(0));
6285        let subscription = Rc::new(RefCell::new(None));
6286        *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
6287            let observation_count = observation_count.clone();
6288            let subscription = subscription.clone();
6289            move |_| {
6290                subscription.borrow_mut().take();
6291                *observation_count.borrow_mut() += 1;
6292            }
6293        }));
6294
6295        cx.default_global::<()>();
6296        cx.set_global(());
6297        assert_eq!(*observation_count.borrow(), 1);
6298    }
6299
6300    #[crate::test(self)]
6301    fn test_focus(cx: &mut MutableAppContext) {
6302        struct View {
6303            name: String,
6304            events: Arc<Mutex<Vec<String>>>,
6305        }
6306
6307        impl Entity for View {
6308            type Event = ();
6309        }
6310
6311        impl super::View for View {
6312            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6313                Empty::new().boxed()
6314            }
6315
6316            fn ui_name() -> &'static str {
6317                "View"
6318            }
6319
6320            fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
6321                if cx.handle().id() == focused.id() {
6322                    self.events.lock().push(format!("{} focused", &self.name));
6323                }
6324            }
6325
6326            fn focus_out(&mut self, blurred: AnyViewHandle, cx: &mut ViewContext<Self>) {
6327                if cx.handle().id() == blurred.id() {
6328                    self.events.lock().push(format!("{} blurred", &self.name));
6329                }
6330            }
6331        }
6332
6333        let view_events: Arc<Mutex<Vec<String>>> = Default::default();
6334        let (_, view_1) = cx.add_window(Default::default(), |_| View {
6335            events: view_events.clone(),
6336            name: "view 1".to_string(),
6337        });
6338        let view_2 = cx.add_view(&view_1, |_| View {
6339            events: view_events.clone(),
6340            name: "view 2".to_string(),
6341        });
6342
6343        let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
6344        view_1.update(cx, |_, cx| {
6345            cx.observe_focus(&view_2, {
6346                let observed_events = observed_events.clone();
6347                move |this, view, focused, cx| {
6348                    let label = if focused { "focus" } else { "blur" };
6349                    observed_events.lock().push(format!(
6350                        "{} observed {}'s {}",
6351                        this.name,
6352                        view.read(cx).name,
6353                        label
6354                    ))
6355                }
6356            })
6357            .detach();
6358        });
6359        view_2.update(cx, |_, cx| {
6360            cx.observe_focus(&view_1, {
6361                let observed_events = observed_events.clone();
6362                move |this, view, focused, cx| {
6363                    let label = if focused { "focus" } else { "blur" };
6364                    observed_events.lock().push(format!(
6365                        "{} observed {}'s {}",
6366                        this.name,
6367                        view.read(cx).name,
6368                        label
6369                    ))
6370                }
6371            })
6372            .detach();
6373        });
6374        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6375        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6376
6377        view_1.update(cx, |_, cx| {
6378            // Ensure focus events are sent for all intermediate focuses
6379            cx.focus(&view_2);
6380            cx.focus(&view_1);
6381            cx.focus(&view_2);
6382        });
6383        assert!(cx.is_child_focused(view_1.clone()));
6384        assert!(!cx.is_child_focused(view_2.clone()));
6385        assert_eq!(
6386            mem::take(&mut *view_events.lock()),
6387            [
6388                "view 1 blurred",
6389                "view 2 focused",
6390                "view 2 blurred",
6391                "view 1 focused",
6392                "view 1 blurred",
6393                "view 2 focused"
6394            ],
6395        );
6396        assert_eq!(
6397            mem::take(&mut *observed_events.lock()),
6398            [
6399                "view 2 observed view 1's blur",
6400                "view 1 observed view 2's focus",
6401                "view 1 observed view 2's blur",
6402                "view 2 observed view 1's focus",
6403                "view 2 observed view 1's blur",
6404                "view 1 observed view 2's focus"
6405            ]
6406        );
6407
6408        view_1.update(cx, |_, cx| cx.focus(&view_1));
6409        assert!(!cx.is_child_focused(view_1.clone()));
6410        assert!(!cx.is_child_focused(view_2.clone()));
6411        assert_eq!(
6412            mem::take(&mut *view_events.lock()),
6413            ["view 2 blurred", "view 1 focused"],
6414        );
6415        assert_eq!(
6416            mem::take(&mut *observed_events.lock()),
6417            [
6418                "view 1 observed view 2's blur",
6419                "view 2 observed view 1's focus"
6420            ]
6421        );
6422
6423        view_1.update(cx, |_, cx| cx.focus(&view_2));
6424        assert_eq!(
6425            mem::take(&mut *view_events.lock()),
6426            ["view 1 blurred", "view 2 focused"],
6427        );
6428        assert_eq!(
6429            mem::take(&mut *observed_events.lock()),
6430            [
6431                "view 2 observed view 1's blur",
6432                "view 1 observed view 2's focus"
6433            ]
6434        );
6435
6436        view_1.update(cx, |_, _| drop(view_2));
6437        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6438        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6439    }
6440
6441    #[crate::test(self)]
6442    fn test_deserialize_actions(cx: &mut MutableAppContext) {
6443        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6444        pub struct ComplexAction {
6445            arg: String,
6446            count: usize,
6447        }
6448
6449        actions!(test::something, [SimpleAction]);
6450        impl_actions!(test::something, [ComplexAction]);
6451
6452        cx.add_global_action(move |_: &SimpleAction, _: &mut MutableAppContext| {});
6453        cx.add_global_action(move |_: &ComplexAction, _: &mut MutableAppContext| {});
6454
6455        let action1 = cx
6456            .deserialize_action(
6457                "test::something::ComplexAction",
6458                Some(r#"{"arg": "a", "count": 5}"#),
6459            )
6460            .unwrap();
6461        let action2 = cx
6462            .deserialize_action("test::something::SimpleAction", None)
6463            .unwrap();
6464        assert_eq!(
6465            action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
6466            &ComplexAction {
6467                arg: "a".to_string(),
6468                count: 5,
6469            }
6470        );
6471        assert_eq!(
6472            action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
6473            &SimpleAction
6474        );
6475    }
6476
6477    #[crate::test(self)]
6478    fn test_dispatch_action(cx: &mut MutableAppContext) {
6479        struct ViewA {
6480            id: usize,
6481        }
6482
6483        impl Entity for ViewA {
6484            type Event = ();
6485        }
6486
6487        impl View for ViewA {
6488            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6489                Empty::new().boxed()
6490            }
6491
6492            fn ui_name() -> &'static str {
6493                "View"
6494            }
6495        }
6496
6497        struct ViewB {
6498            id: usize,
6499        }
6500
6501        impl Entity for ViewB {
6502            type Event = ();
6503        }
6504
6505        impl View for ViewB {
6506            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6507                Empty::new().boxed()
6508            }
6509
6510            fn ui_name() -> &'static str {
6511                "View"
6512            }
6513        }
6514
6515        #[derive(Clone, Default, Deserialize, PartialEq)]
6516        pub struct Action(pub String);
6517
6518        impl_actions!(test, [Action]);
6519
6520        let actions = Rc::new(RefCell::new(Vec::new()));
6521
6522        cx.add_global_action({
6523            let actions = actions.clone();
6524            move |_: &Action, _: &mut MutableAppContext| {
6525                actions.borrow_mut().push("global".to_string());
6526            }
6527        });
6528
6529        cx.add_action({
6530            let actions = actions.clone();
6531            move |view: &mut ViewA, action: &Action, cx| {
6532                assert_eq!(action.0, "bar");
6533                cx.propagate_action();
6534                actions.borrow_mut().push(format!("{} a", view.id));
6535            }
6536        });
6537
6538        cx.add_action({
6539            let actions = actions.clone();
6540            move |view: &mut ViewA, _: &Action, cx| {
6541                if view.id != 1 {
6542                    cx.add_view(|cx| {
6543                        cx.propagate_action(); // Still works on a nested ViewContext
6544                        ViewB { id: 5 }
6545                    });
6546                }
6547                actions.borrow_mut().push(format!("{} b", view.id));
6548            }
6549        });
6550
6551        cx.add_action({
6552            let actions = actions.clone();
6553            move |view: &mut ViewB, _: &Action, cx| {
6554                cx.propagate_action();
6555                actions.borrow_mut().push(format!("{} c", view.id));
6556            }
6557        });
6558
6559        cx.add_action({
6560            let actions = actions.clone();
6561            move |view: &mut ViewB, _: &Action, cx| {
6562                cx.propagate_action();
6563                actions.borrow_mut().push(format!("{} d", view.id));
6564            }
6565        });
6566
6567        cx.capture_action({
6568            let actions = actions.clone();
6569            move |view: &mut ViewA, _: &Action, cx| {
6570                cx.propagate_action();
6571                actions.borrow_mut().push(format!("{} capture", view.id));
6572            }
6573        });
6574
6575        let observed_actions = Rc::new(RefCell::new(Vec::new()));
6576        cx.observe_actions({
6577            let observed_actions = observed_actions.clone();
6578            move |action_id, _| observed_actions.borrow_mut().push(action_id)
6579        })
6580        .detach();
6581
6582        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
6583        let view_2 = cx.add_view(&view_1, |_| ViewB { id: 2 });
6584        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
6585        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
6586
6587        cx.handle_dispatch_action_from_effect(
6588            window_id,
6589            Some(view_4.id()),
6590            &Action("bar".to_string()),
6591        );
6592
6593        assert_eq!(
6594            *actions.borrow(),
6595            vec![
6596                "1 capture",
6597                "3 capture",
6598                "4 d",
6599                "4 c",
6600                "3 b",
6601                "3 a",
6602                "2 d",
6603                "2 c",
6604                "1 b"
6605            ]
6606        );
6607        assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
6608
6609        // Remove view_1, which doesn't propagate the action
6610
6611        let (window_id, view_2) = cx.add_window(Default::default(), |_| ViewB { id: 2 });
6612        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
6613        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
6614
6615        actions.borrow_mut().clear();
6616        cx.handle_dispatch_action_from_effect(
6617            window_id,
6618            Some(view_4.id()),
6619            &Action("bar".to_string()),
6620        );
6621
6622        assert_eq!(
6623            *actions.borrow(),
6624            vec![
6625                "3 capture",
6626                "4 d",
6627                "4 c",
6628                "3 b",
6629                "3 a",
6630                "2 d",
6631                "2 c",
6632                "global"
6633            ]
6634        );
6635        assert_eq!(
6636            *observed_actions.borrow(),
6637            [Action::default().id(), Action::default().id()]
6638        );
6639    }
6640
6641    #[crate::test(self)]
6642    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
6643        #[derive(Clone, Deserialize, PartialEq)]
6644        pub struct Action(String);
6645
6646        impl_actions!(test, [Action]);
6647
6648        struct View {
6649            id: usize,
6650            keymap_context: KeymapContext,
6651        }
6652
6653        impl Entity for View {
6654            type Event = ();
6655        }
6656
6657        impl super::View for View {
6658            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6659                Empty::new().boxed()
6660            }
6661
6662            fn ui_name() -> &'static str {
6663                "View"
6664            }
6665
6666            fn keymap_context(&self, _: &AppContext) -> KeymapContext {
6667                self.keymap_context.clone()
6668            }
6669        }
6670
6671        impl View {
6672            fn new(id: usize) -> Self {
6673                View {
6674                    id,
6675                    keymap_context: KeymapContext::default(),
6676                }
6677            }
6678        }
6679
6680        let mut view_1 = View::new(1);
6681        let mut view_2 = View::new(2);
6682        let mut view_3 = View::new(3);
6683        view_1.keymap_context.add_identifier("a");
6684        view_2.keymap_context.add_identifier("a");
6685        view_2.keymap_context.add_identifier("b");
6686        view_3.keymap_context.add_identifier("a");
6687        view_3.keymap_context.add_identifier("b");
6688        view_3.keymap_context.add_identifier("c");
6689
6690        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
6691        let view_2 = cx.add_view(&view_1, |_| view_2);
6692        let _view_3 = cx.add_view(&view_2, |cx| {
6693            cx.focus_self();
6694            view_3
6695        });
6696
6697        // This binding only dispatches an action on view 2 because that view will have
6698        // "a" and "b" in its context, but not "c".
6699        cx.add_bindings(vec![Binding::new(
6700            "a",
6701            Action("a".to_string()),
6702            Some("a && b && !c"),
6703        )]);
6704
6705        cx.add_bindings(vec![Binding::new("b", Action("b".to_string()), None)]);
6706
6707        // This binding only dispatches an action on views 2 and 3, because they have
6708        // a parent view with a in its context
6709        cx.add_bindings(vec![Binding::new(
6710            "c",
6711            Action("c".to_string()),
6712            Some("b > c"),
6713        )]);
6714
6715        // This binding only dispatches an action on view 2, because they have
6716        // a parent view with a in its context
6717        cx.add_bindings(vec![Binding::new(
6718            "d",
6719            Action("d".to_string()),
6720            Some("a && !b > b"),
6721        )]);
6722
6723        let actions = Rc::new(RefCell::new(Vec::new()));
6724        cx.add_action({
6725            let actions = actions.clone();
6726            move |view: &mut View, action: &Action, cx| {
6727                actions
6728                    .borrow_mut()
6729                    .push(format!("{} {}", view.id, action.0));
6730
6731                if action.0 == "b" {
6732                    cx.propagate_action();
6733                }
6734            }
6735        });
6736
6737        cx.add_global_action({
6738            let actions = actions.clone();
6739            move |action: &Action, _| {
6740                actions.borrow_mut().push(format!("global {}", action.0));
6741            }
6742        });
6743
6744        cx.dispatch_keystroke(window_id, &Keystroke::parse("a").unwrap());
6745        assert_eq!(&*actions.borrow(), &["2 a"]);
6746        actions.borrow_mut().clear();
6747
6748        cx.dispatch_keystroke(window_id, &Keystroke::parse("b").unwrap());
6749        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
6750        actions.borrow_mut().clear();
6751
6752        cx.dispatch_keystroke(window_id, &Keystroke::parse("c").unwrap());
6753        assert_eq!(&*actions.borrow(), &["3 c"]);
6754        actions.borrow_mut().clear();
6755
6756        cx.dispatch_keystroke(window_id, &Keystroke::parse("d").unwrap());
6757        assert_eq!(&*actions.borrow(), &["2 d"]);
6758        actions.borrow_mut().clear();
6759    }
6760
6761    #[crate::test(self)]
6762    fn test_keystrokes_for_action(cx: &mut MutableAppContext) {
6763        actions!(test, [Action1, Action2, GlobalAction]);
6764
6765        struct View1 {}
6766        struct View2 {}
6767
6768        impl Entity for View1 {
6769            type Event = ();
6770        }
6771        impl Entity for View2 {
6772            type Event = ();
6773        }
6774
6775        impl super::View for View1 {
6776            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6777                Empty::new().boxed()
6778            }
6779            fn ui_name() -> &'static str {
6780                "View1"
6781            }
6782        }
6783        impl super::View for View2 {
6784            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6785                Empty::new().boxed()
6786            }
6787            fn ui_name() -> &'static str {
6788                "View2"
6789            }
6790        }
6791
6792        let (window_id, view_1) = cx.add_window(Default::default(), |_| View1 {});
6793        let view_2 = cx.add_view(&view_1, |cx| {
6794            cx.focus_self();
6795            View2 {}
6796        });
6797
6798        cx.add_action(|_: &mut View1, _: &Action1, _cx| {});
6799        cx.add_action(|_: &mut View2, _: &Action2, _cx| {});
6800        cx.add_global_action(|_: &GlobalAction, _| {});
6801
6802        cx.add_bindings(vec![
6803            Binding::new("a", Action1, Some("View1")),
6804            Binding::new("b", Action2, Some("View1 > View2")),
6805            Binding::new("c", GlobalAction, Some("View3")), // View 3 does not exist
6806        ]);
6807
6808        // Sanity check
6809        assert_eq!(
6810            cx.keystrokes_for_action(window_id, view_1.id(), &Action1)
6811                .unwrap()
6812                .as_slice(),
6813            &[Keystroke::parse("a").unwrap()]
6814        );
6815        assert_eq!(
6816            cx.keystrokes_for_action(window_id, view_2.id(), &Action2)
6817                .unwrap()
6818                .as_slice(),
6819            &[Keystroke::parse("b").unwrap()]
6820        );
6821
6822        // The 'a' keystroke propagates up the view tree from view_2
6823        // to view_1. The action, Action1, is handled by view_1.
6824        assert_eq!(
6825            cx.keystrokes_for_action(window_id, view_2.id(), &Action1)
6826                .unwrap()
6827                .as_slice(),
6828            &[Keystroke::parse("a").unwrap()]
6829        );
6830
6831        // Actions that are handled below the current view don't have bindings
6832        assert_eq!(
6833            cx.keystrokes_for_action(window_id, view_1.id(), &Action2),
6834            None
6835        );
6836
6837        // Actions that are handled in other branches of the tree should not have a binding
6838        assert_eq!(
6839            cx.keystrokes_for_action(window_id, view_2.id(), &GlobalAction),
6840            None
6841        );
6842
6843        // Produces a list of actions and key bindings
6844        fn available_actions(
6845            window_id: usize,
6846            view_id: usize,
6847            cx: &mut MutableAppContext,
6848        ) -> Vec<(&'static str, Vec<Keystroke>)> {
6849            cx.available_actions(window_id, view_id)
6850                .map(|(action_name, _, bindings)| {
6851                    (
6852                        action_name,
6853                        bindings
6854                            .iter()
6855                            .map(|binding| binding.keystrokes()[0].clone())
6856                            .collect::<Vec<_>>(),
6857                    )
6858                })
6859                .sorted_by(|(name1, _), (name2, _)| name1.cmp(name2))
6860                .collect()
6861        }
6862
6863        // Check that global actions do not have a binding, even if a binding does exist in another view
6864        assert_eq!(
6865            &available_actions(window_id, view_1.id(), cx),
6866            &[
6867                ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
6868                ("test::GlobalAction", vec![])
6869            ],
6870        );
6871
6872        // Check that view 1 actions and bindings are available even when called from view 2
6873        assert_eq!(
6874            &available_actions(window_id, view_2.id(), cx),
6875            &[
6876                ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
6877                ("test::Action2", vec![Keystroke::parse("b").unwrap()]),
6878                ("test::GlobalAction", vec![]),
6879            ],
6880        );
6881    }
6882
6883    #[crate::test(self)]
6884    async fn test_model_condition(cx: &mut TestAppContext) {
6885        struct Counter(usize);
6886
6887        impl super::Entity for Counter {
6888            type Event = ();
6889        }
6890
6891        impl Counter {
6892            fn inc(&mut self, cx: &mut ModelContext<Self>) {
6893                self.0 += 1;
6894                cx.notify();
6895            }
6896        }
6897
6898        let model = cx.add_model(|_| Counter(0));
6899
6900        let condition1 = model.condition(cx, |model, _| model.0 == 2);
6901        let condition2 = model.condition(cx, |model, _| model.0 == 3);
6902        smol::pin!(condition1, condition2);
6903
6904        model.update(cx, |model, cx| model.inc(cx));
6905        assert_eq!(poll_once(&mut condition1).await, None);
6906        assert_eq!(poll_once(&mut condition2).await, None);
6907
6908        model.update(cx, |model, cx| model.inc(cx));
6909        assert_eq!(poll_once(&mut condition1).await, Some(()));
6910        assert_eq!(poll_once(&mut condition2).await, None);
6911
6912        model.update(cx, |model, cx| model.inc(cx));
6913        assert_eq!(poll_once(&mut condition2).await, Some(()));
6914
6915        model.update(cx, |_, cx| cx.notify());
6916    }
6917
6918    #[crate::test(self)]
6919    #[should_panic]
6920    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
6921        struct Model;
6922
6923        impl super::Entity for Model {
6924            type Event = ();
6925        }
6926
6927        let model = cx.add_model(|_| Model);
6928        model.condition(cx, |_, _| false).await;
6929    }
6930
6931    #[crate::test(self)]
6932    #[should_panic(expected = "model dropped with pending condition")]
6933    async fn test_model_condition_panic_on_drop(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        let condition = model.condition(cx, |_, _| false);
6942        cx.update(|_| drop(model));
6943        condition.await;
6944    }
6945
6946    #[crate::test(self)]
6947    async fn test_view_condition(cx: &mut TestAppContext) {
6948        struct Counter(usize);
6949
6950        impl super::Entity for Counter {
6951            type Event = ();
6952        }
6953
6954        impl super::View for Counter {
6955            fn ui_name() -> &'static str {
6956                "test view"
6957            }
6958
6959            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6960                Empty::new().boxed()
6961            }
6962        }
6963
6964        impl Counter {
6965            fn inc(&mut self, cx: &mut ViewContext<Self>) {
6966                self.0 += 1;
6967                cx.notify();
6968            }
6969        }
6970
6971        let (_, view) = cx.add_window(|_| Counter(0));
6972
6973        let condition1 = view.condition(cx, |view, _| view.0 == 2);
6974        let condition2 = view.condition(cx, |view, _| view.0 == 3);
6975        smol::pin!(condition1, condition2);
6976
6977        view.update(cx, |view, cx| view.inc(cx));
6978        assert_eq!(poll_once(&mut condition1).await, None);
6979        assert_eq!(poll_once(&mut condition2).await, None);
6980
6981        view.update(cx, |view, cx| view.inc(cx));
6982        assert_eq!(poll_once(&mut condition1).await, Some(()));
6983        assert_eq!(poll_once(&mut condition2).await, None);
6984
6985        view.update(cx, |view, cx| view.inc(cx));
6986        assert_eq!(poll_once(&mut condition2).await, Some(()));
6987        view.update(cx, |_, cx| cx.notify());
6988    }
6989
6990    #[crate::test(self)]
6991    #[should_panic]
6992    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
6993        let (_, view) = cx.add_window(|_| TestView::default());
6994        view.condition(cx, |_, _| false).await;
6995    }
6996
6997    #[crate::test(self)]
6998    #[should_panic(expected = "view dropped with pending condition")]
6999    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
7000        let (_, root_view) = cx.add_window(|_| TestView::default());
7001        let view = cx.add_view(&root_view, |_| TestView::default());
7002
7003        let condition = view.condition(cx, |_, _| false);
7004        cx.update(|_| drop(view));
7005        condition.await;
7006    }
7007
7008    #[crate::test(self)]
7009    fn test_refresh_windows(cx: &mut MutableAppContext) {
7010        struct View(usize);
7011
7012        impl super::Entity for View {
7013            type Event = ();
7014        }
7015
7016        impl super::View for View {
7017            fn ui_name() -> &'static str {
7018                "test view"
7019            }
7020
7021            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7022                Empty::new().named(format!("render count: {}", post_inc(&mut self.0)))
7023            }
7024        }
7025
7026        let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
7027        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
7028
7029        assert_eq!(
7030            presenter.borrow().rendered_views[&root_view.id()].name(),
7031            Some("render count: 0")
7032        );
7033
7034        let view = cx.add_view(&root_view, |cx| {
7035            cx.refresh_windows();
7036            View(0)
7037        });
7038
7039        assert_eq!(
7040            presenter.borrow().rendered_views[&root_view.id()].name(),
7041            Some("render count: 1")
7042        );
7043        assert_eq!(
7044            presenter.borrow().rendered_views[&view.id()].name(),
7045            Some("render count: 0")
7046        );
7047
7048        cx.update(|cx| cx.refresh_windows());
7049        assert_eq!(
7050            presenter.borrow().rendered_views[&root_view.id()].name(),
7051            Some("render count: 2")
7052        );
7053        assert_eq!(
7054            presenter.borrow().rendered_views[&view.id()].name(),
7055            Some("render count: 1")
7056        );
7057
7058        cx.update(|cx| {
7059            cx.refresh_windows();
7060            drop(view);
7061        });
7062        assert_eq!(
7063            presenter.borrow().rendered_views[&root_view.id()].name(),
7064            Some("render count: 3")
7065        );
7066        assert_eq!(presenter.borrow().rendered_views.len(), 1);
7067    }
7068
7069    #[crate::test(self)]
7070    async fn test_labeled_tasks(cx: &mut TestAppContext) {
7071        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
7072        let (mut sender, mut reciever) = postage::oneshot::channel::<()>();
7073        let task = cx
7074            .update(|cx| cx.spawn_labeled("Test Label", |_| async move { reciever.recv().await }));
7075
7076        assert_eq!(
7077            Some("Test Label"),
7078            cx.update(|cx| cx.active_labeled_tasks().next())
7079        );
7080        sender
7081            .send(())
7082            .await
7083            .expect("Could not send message to complete task");
7084        task.await;
7085
7086        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
7087    }
7088
7089    #[crate::test(self)]
7090    async fn test_window_activation(cx: &mut TestAppContext) {
7091        struct View(&'static str);
7092
7093        impl super::Entity for View {
7094            type Event = ();
7095        }
7096
7097        impl super::View for View {
7098            fn ui_name() -> &'static str {
7099                "test view"
7100            }
7101
7102            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7103                Empty::new().boxed()
7104            }
7105        }
7106
7107        let events = Rc::new(RefCell::new(Vec::new()));
7108        let (window_1, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7109            cx.observe_window_activation({
7110                let events = events.clone();
7111                move |this, active, _| events.borrow_mut().push((this.0, active))
7112            })
7113            .detach();
7114            View("window 1")
7115        });
7116        assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
7117
7118        let (window_2, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7119            cx.observe_window_activation({
7120                let events = events.clone();
7121                move |this, active, _| events.borrow_mut().push((this.0, active))
7122            })
7123            .detach();
7124            View("window 2")
7125        });
7126        assert_eq!(
7127            mem::take(&mut *events.borrow_mut()),
7128            [("window 1", false), ("window 2", true)]
7129        );
7130
7131        let (window_3, _) = 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 3")
7138        });
7139        assert_eq!(
7140            mem::take(&mut *events.borrow_mut()),
7141            [("window 2", false), ("window 3", true)]
7142        );
7143
7144        cx.simulate_window_activation(Some(window_2));
7145        assert_eq!(
7146            mem::take(&mut *events.borrow_mut()),
7147            [("window 3", false), ("window 2", true)]
7148        );
7149
7150        cx.simulate_window_activation(Some(window_1));
7151        assert_eq!(
7152            mem::take(&mut *events.borrow_mut()),
7153            [("window 2", false), ("window 1", true)]
7154        );
7155
7156        cx.simulate_window_activation(Some(window_3));
7157        assert_eq!(
7158            mem::take(&mut *events.borrow_mut()),
7159            [("window 1", false), ("window 3", true)]
7160        );
7161
7162        cx.simulate_window_activation(Some(window_3));
7163        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
7164    }
7165
7166    #[crate::test(self)]
7167    fn test_child_view(cx: &mut MutableAppContext) {
7168        struct Child {
7169            rendered: Rc<Cell<bool>>,
7170            dropped: Rc<Cell<bool>>,
7171        }
7172
7173        impl super::Entity for Child {
7174            type Event = ();
7175        }
7176
7177        impl super::View for Child {
7178            fn ui_name() -> &'static str {
7179                "child view"
7180            }
7181
7182            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7183                self.rendered.set(true);
7184                Empty::new().boxed()
7185            }
7186        }
7187
7188        impl Drop for Child {
7189            fn drop(&mut self) {
7190                self.dropped.set(true);
7191            }
7192        }
7193
7194        struct Parent {
7195            child: Option<ViewHandle<Child>>,
7196        }
7197
7198        impl super::Entity for Parent {
7199            type Event = ();
7200        }
7201
7202        impl super::View for Parent {
7203            fn ui_name() -> &'static str {
7204                "parent view"
7205            }
7206
7207            fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
7208                if let Some(child) = self.child.as_ref() {
7209                    ChildView::new(child, cx).boxed()
7210                } else {
7211                    Empty::new().boxed()
7212                }
7213            }
7214        }
7215
7216        let child_rendered = Rc::new(Cell::new(false));
7217        let child_dropped = Rc::new(Cell::new(false));
7218        let (_, root_view) = cx.add_window(Default::default(), |cx| Parent {
7219            child: Some(cx.add_view(|_| Child {
7220                rendered: child_rendered.clone(),
7221                dropped: child_dropped.clone(),
7222            })),
7223        });
7224        assert!(child_rendered.take());
7225        assert!(!child_dropped.take());
7226
7227        root_view.update(cx, |view, cx| {
7228            view.child.take();
7229            cx.notify();
7230        });
7231        assert!(!child_rendered.take());
7232        assert!(child_dropped.take());
7233    }
7234
7235    #[derive(Default)]
7236    struct TestView {
7237        events: Vec<String>,
7238    }
7239
7240    impl Entity for TestView {
7241        type Event = String;
7242    }
7243
7244    impl View for TestView {
7245        fn ui_name() -> &'static str {
7246            "TestView"
7247        }
7248
7249        fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7250            Empty::new().boxed()
7251        }
7252    }
7253}