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