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