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