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