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