app.rs

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