app.rs

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