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