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