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