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 WindowContext) -> 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 WindowContext) -> 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 WindowContext) -> 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 WindowContext) -> 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
1709                                .emit(entity_id, |callback| callback(payload.as_ref(), self))
1710                        }
1711
1712                        Effect::GlobalSubscription {
1713                            type_id,
1714                            subscription_id,
1715                            callback,
1716                        } => self.global_subscriptions.add_callback(
1717                            type_id,
1718                            subscription_id,
1719                            callback,
1720                        ),
1721
1722                        Effect::GlobalEvent { payload } => self.emit_global_event(payload),
1723
1724                        Effect::Observation {
1725                            entity_id,
1726                            subscription_id,
1727                            callback,
1728                        } => self
1729                            .observations
1730                            .add_callback(entity_id, subscription_id, callback),
1731
1732                        Effect::ModelNotification { model_id } => {
1733                            let mut observations = self.observations.clone();
1734                            observations.emit(model_id, |callback| callback(self));
1735                        }
1736
1737                        Effect::ViewNotification { window_id, view_id } => {
1738                            self.handle_view_notification_effect(window_id, view_id)
1739                        }
1740
1741                        Effect::GlobalNotification { type_id } => {
1742                            let mut subscriptions = self.global_observations.clone();
1743                            subscriptions.emit(type_id, |callback| {
1744                                callback(self);
1745                                true
1746                            });
1747                        }
1748
1749                        Effect::Deferred {
1750                            callback,
1751                            after_window_update,
1752                        } => {
1753                            if after_window_update {
1754                                after_window_update_callbacks.push(callback);
1755                            } else {
1756                                callback(self)
1757                            }
1758                        }
1759
1760                        Effect::ModelRelease { model_id, model } => {
1761                            self.handle_entity_release_effect(model_id, model.as_any())
1762                        }
1763
1764                        Effect::ViewRelease { view_id, view } => {
1765                            self.handle_entity_release_effect(view_id, view.as_any())
1766                        }
1767
1768                        Effect::Focus { window_id, view_id } => {
1769                            self.handle_focus_effect(window_id, view_id);
1770                        }
1771
1772                        Effect::FocusObservation {
1773                            view_id,
1774                            subscription_id,
1775                            callback,
1776                        } => {
1777                            self.focus_observations.add_callback(
1778                                view_id,
1779                                subscription_id,
1780                                callback,
1781                            );
1782                        }
1783
1784                        Effect::ResizeWindow { window_id } => {
1785                            if let Some(window) = self.windows.get_mut(&window_id) {
1786                                window
1787                                    .invalidation
1788                                    .get_or_insert(WindowInvalidation::default());
1789                            }
1790                            self.handle_window_moved(window_id);
1791                        }
1792
1793                        Effect::MoveWindow { window_id } => {
1794                            self.handle_window_moved(window_id);
1795                        }
1796
1797                        Effect::WindowActivationObservation {
1798                            window_id,
1799                            subscription_id,
1800                            callback,
1801                        } => self.window_activation_observations.add_callback(
1802                            window_id,
1803                            subscription_id,
1804                            callback,
1805                        ),
1806
1807                        Effect::ActivateWindow {
1808                            window_id,
1809                            is_active,
1810                        } => self.handle_window_activation_effect(window_id, is_active),
1811
1812                        Effect::WindowFullscreenObservation {
1813                            window_id,
1814                            subscription_id,
1815                            callback,
1816                        } => self.window_fullscreen_observations.add_callback(
1817                            window_id,
1818                            subscription_id,
1819                            callback,
1820                        ),
1821
1822                        Effect::FullscreenWindow {
1823                            window_id,
1824                            is_fullscreen,
1825                        } => self.handle_fullscreen_effect(window_id, is_fullscreen),
1826
1827                        Effect::WindowBoundsObservation {
1828                            window_id,
1829                            subscription_id,
1830                            callback,
1831                        } => self.window_bounds_observations.add_callback(
1832                            window_id,
1833                            subscription_id,
1834                            callback,
1835                        ),
1836
1837                        Effect::RefreshWindows => {
1838                            refreshing = true;
1839                        }
1840                        Effect::DispatchActionFrom {
1841                            window_id,
1842                            view_id,
1843                            action,
1844                        } => {
1845                            self.handle_dispatch_action_from_effect(
1846                                window_id,
1847                                Some(view_id),
1848                                action.as_ref(),
1849                            );
1850                        }
1851                        Effect::ActionDispatchNotification { action_id } => {
1852                            self.handle_action_dispatch_notification_effect(action_id)
1853                        }
1854                        Effect::WindowShouldCloseSubscription {
1855                            window_id,
1856                            callback,
1857                        } => {
1858                            self.handle_window_should_close_subscription_effect(window_id, callback)
1859                        }
1860                        Effect::Keystroke {
1861                            window_id,
1862                            keystroke,
1863                            handled_by,
1864                            result,
1865                        } => self.handle_keystroke_effect(window_id, keystroke, handled_by, result),
1866                        Effect::ActiveLabeledTasksChanged => {
1867                            self.handle_active_labeled_tasks_changed_effect()
1868                        }
1869                        Effect::ActiveLabeledTasksObservation {
1870                            subscription_id,
1871                            callback,
1872                        } => self.active_labeled_task_observations.add_callback(
1873                            (),
1874                            subscription_id,
1875                            callback,
1876                        ),
1877                    }
1878                    self.pending_notifications.clear();
1879                    self.remove_dropped_entities();
1880                } else {
1881                    self.remove_dropped_entities();
1882
1883                    if refreshing {
1884                        self.perform_window_refresh();
1885                    } else {
1886                        self.update_windows();
1887                    }
1888
1889                    if self.pending_effects.is_empty() {
1890                        for callback in after_window_update_callbacks.drain(..) {
1891                            callback(self);
1892                        }
1893
1894                        if self.pending_effects.is_empty() {
1895                            self.flushing_effects = false;
1896                            self.pending_notifications.clear();
1897                            self.pending_global_notifications.clear();
1898                            break;
1899                        }
1900                    }
1901
1902                    refreshing = false;
1903                }
1904            }
1905        }
1906    }
1907
1908    fn update_windows(&mut self) {
1909        let window_ids = self.windows.keys().cloned().collect::<Vec<_>>();
1910        for window_id in window_ids {
1911            self.update_window(window_id, |cx| {
1912                if let Some(mut invalidation) = cx.window.invalidation.take() {
1913                    let appearance = cx.window.platform_window.appearance();
1914                    cx.invalidate(&mut invalidation, appearance);
1915                    let scene = cx.build_scene();
1916                    cx.window.platform_window.present_scene(scene);
1917                }
1918            });
1919        }
1920    }
1921
1922    fn window_was_resized(&mut self, window_id: usize) {
1923        self.pending_effects
1924            .push_back(Effect::ResizeWindow { window_id });
1925    }
1926
1927    fn window_was_moved(&mut self, window_id: usize) {
1928        self.pending_effects
1929            .push_back(Effect::MoveWindow { window_id });
1930    }
1931
1932    fn window_was_fullscreen_changed(&mut self, window_id: usize, is_fullscreen: bool) {
1933        self.pending_effects.push_back(Effect::FullscreenWindow {
1934            window_id,
1935            is_fullscreen,
1936        });
1937    }
1938
1939    fn window_changed_active_status(&mut self, window_id: usize, is_active: bool) {
1940        self.pending_effects.push_back(Effect::ActivateWindow {
1941            window_id,
1942            is_active,
1943        });
1944    }
1945
1946    fn keystroke(
1947        &mut self,
1948        window_id: usize,
1949        keystroke: Keystroke,
1950        handled_by: Option<Box<dyn Action>>,
1951        result: MatchResult,
1952    ) {
1953        self.pending_effects.push_back(Effect::Keystroke {
1954            window_id,
1955            keystroke,
1956            handled_by,
1957            result,
1958        });
1959    }
1960
1961    pub fn refresh_windows(&mut self) {
1962        self.pending_effects.push_back(Effect::RefreshWindows);
1963    }
1964
1965    pub fn dispatch_action_at(&mut self, window_id: usize, view_id: usize, action: impl Action) {
1966        self.dispatch_any_action_at(window_id, view_id, Box::new(action));
1967    }
1968
1969    pub fn dispatch_any_action_at(
1970        &mut self,
1971        window_id: usize,
1972        view_id: usize,
1973        action: Box<dyn Action>,
1974    ) {
1975        self.pending_effects.push_back(Effect::DispatchActionFrom {
1976            window_id,
1977            view_id,
1978            action,
1979        });
1980    }
1981
1982    fn perform_window_refresh(&mut self) {
1983        let window_ids = self.windows.keys().cloned().collect::<Vec<_>>();
1984        for window_id in window_ids {
1985            self.update_window(window_id, |cx| {
1986                let mut invalidation = cx.window.invalidation.take().unwrap_or_default();
1987                invalidation
1988                    .updated
1989                    .extend(cx.window.rendered_views.keys().copied());
1990                cx.invalidate(&mut invalidation, cx.window.platform_window.appearance());
1991                cx.refreshing = true;
1992                let scene = cx.build_scene();
1993                cx.window.platform_window.present_scene(scene);
1994            });
1995        }
1996    }
1997
1998    fn emit_global_event(&mut self, payload: Box<dyn Any>) {
1999        let type_id = (&*payload).type_id();
2000
2001        let mut subscriptions = self.global_subscriptions.clone();
2002        subscriptions.emit(type_id, |callback| {
2003            callback(payload.as_ref(), self);
2004            true //Always alive
2005        });
2006    }
2007
2008    fn handle_view_notification_effect(
2009        &mut self,
2010        observed_window_id: usize,
2011        observed_view_id: usize,
2012    ) {
2013        if self
2014            .views
2015            .contains_key(&(observed_window_id, observed_view_id))
2016        {
2017            if let Some(window) = self.windows.get_mut(&observed_window_id) {
2018                window
2019                    .invalidation
2020                    .get_or_insert_with(Default::default)
2021                    .updated
2022                    .insert(observed_view_id);
2023            }
2024
2025            let mut observations = self.observations.clone();
2026            observations.emit(observed_view_id, |callback| callback(self));
2027        }
2028    }
2029
2030    fn handle_entity_release_effect(&mut self, entity_id: usize, entity: &dyn Any) {
2031        self.release_observations
2032            .clone()
2033            .emit(entity_id, |callback| {
2034                callback(entity, self);
2035                // Release observations happen one time. So clear the callback by returning false
2036                false
2037            })
2038    }
2039
2040    fn handle_fullscreen_effect(&mut self, window_id: usize, is_fullscreen: bool) {
2041        self.update_window(window_id, |cx| {
2042            cx.window.is_fullscreen = is_fullscreen;
2043
2044            let mut fullscreen_observations = cx.window_fullscreen_observations.clone();
2045            fullscreen_observations.emit(window_id, |callback| callback(is_fullscreen, cx));
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.emit(window_id, |callback| callback(bounds, uuid, cx));
2051            }
2052
2053            Some(())
2054        });
2055    }
2056
2057    fn handle_keystroke_effect(
2058        &mut self,
2059        window_id: usize,
2060        keystroke: Keystroke,
2061        handled_by: Option<Box<dyn Action>>,
2062        result: MatchResult,
2063    ) {
2064        self.update(|this| {
2065            let mut observations = this.keystroke_observations.clone();
2066            observations.emit(window_id, move |callback| {
2067                callback(&keystroke, &result, handled_by.as_ref(), this)
2068            });
2069        });
2070    }
2071
2072    fn handle_window_activation_effect(&mut self, window_id: usize, active: bool) {
2073        self.update_window(window_id, |cx| {
2074            if cx.window.is_active == active {
2075                return;
2076            }
2077            cx.window.is_active = active;
2078
2079            if let Some(focused_id) = cx.window.focused_view_id {
2080                for view_id in cx.ancestors(window_id, focused_id).collect::<Vec<_>>() {
2081                    cx.update_any_view(focused_id, |view, cx| {
2082                        if active {
2083                            view.focus_in(focused_id, cx, view_id);
2084                        } else {
2085                            view.focus_out(focused_id, cx, view_id);
2086                        }
2087                    });
2088                }
2089            }
2090
2091            let mut observations = cx.window_activation_observations.clone();
2092            observations.emit(window_id, |callback| callback(active, cx));
2093        });
2094    }
2095
2096    fn handle_focus_effect(&mut self, window_id: usize, mut focused_id: Option<usize>) {
2097        let mut blurred_id = None;
2098        self.update_window(window_id, |cx| {
2099            if cx.window.focused_view_id == focused_id {
2100                focused_id = None;
2101                return;
2102            }
2103            blurred_id = cx.window.focused_view_id;
2104            cx.window.focused_view_id = focused_id;
2105
2106            let blurred_parents = blurred_id
2107                .map(|blurred_id| cx.ancestors(window_id, blurred_id).collect::<Vec<_>>())
2108                .unwrap_or_default();
2109            let focused_parents = focused_id
2110                .map(|focused_id| cx.ancestors(window_id, focused_id).collect::<Vec<_>>())
2111                .unwrap_or_default();
2112
2113            if let Some(blurred_id) = blurred_id {
2114                for view_id in blurred_parents.iter().copied() {
2115                    if let Some(mut view) = cx.views.remove(&(window_id, view_id)) {
2116                        view.focus_out(blurred_id, cx, view_id);
2117                        cx.views.insert((window_id, view_id), view);
2118                    }
2119                }
2120
2121                let mut subscriptions = cx.focus_observations.clone();
2122                subscriptions.emit(blurred_id, |callback| callback(false, cx));
2123            }
2124
2125            if let Some(focused_id) = focused_id {
2126                for view_id in focused_parents {
2127                    if let Some(mut view) = cx.views.remove(&(window_id, view_id)) {
2128                        view.focus_in(focused_id, cx, view_id);
2129                        cx.views.insert((window_id, view_id), view);
2130                    }
2131                }
2132
2133                let mut subscriptions = cx.focus_observations.clone();
2134                subscriptions.emit(focused_id, |callback| callback(true, cx));
2135            }
2136        });
2137    }
2138
2139    fn handle_dispatch_action_from_effect(
2140        &mut self,
2141        window_id: usize,
2142        view_id: Option<usize>,
2143        action: &dyn Action,
2144    ) -> bool {
2145        self.update(|this| {
2146            if let Some(view_id) = view_id {
2147                this.halt_action_dispatch = false;
2148                this.visit_dispatch_path(window_id, view_id, |view_id, capture_phase, this| {
2149                    this.update_window(window_id, |cx| {
2150                        cx.update_any_view(view_id, |view, cx| {
2151                            let type_id = view.as_any().type_id();
2152                            if let Some((name, mut handlers)) = cx
2153                                .actions_mut(capture_phase)
2154                                .get_mut(&type_id)
2155                                .and_then(|h| h.remove_entry(&action.id()))
2156                            {
2157                                for handler in handlers.iter_mut().rev() {
2158                                    cx.halt_action_dispatch = true;
2159                                    handler(view, action, cx, view_id);
2160                                    if cx.halt_action_dispatch {
2161                                        break;
2162                                    }
2163                                }
2164                                cx.actions_mut(capture_phase)
2165                                    .get_mut(&type_id)
2166                                    .unwrap()
2167                                    .insert(name, handlers);
2168                            }
2169                        })
2170                    });
2171
2172                    !this.halt_action_dispatch
2173                });
2174            }
2175
2176            if !this.halt_action_dispatch {
2177                this.halt_action_dispatch = this.dispatch_global_action_any(action);
2178            }
2179
2180            this.pending_effects
2181                .push_back(Effect::ActionDispatchNotification {
2182                    action_id: action.id(),
2183                });
2184            this.halt_action_dispatch
2185        })
2186    }
2187
2188    fn handle_action_dispatch_notification_effect(&mut self, action_id: TypeId) {
2189        self.action_dispatch_observations
2190            .clone()
2191            .emit((), |callback| {
2192                callback(action_id, self);
2193                true
2194            });
2195    }
2196
2197    fn handle_window_should_close_subscription_effect(
2198        &mut self,
2199        window_id: usize,
2200        mut callback: WindowShouldCloseSubscriptionCallback,
2201    ) {
2202        let mut app = self.upgrade();
2203        if let Some(window) = self.windows.get_mut(&window_id) {
2204            window
2205                .platform_window
2206                .on_should_close(Box::new(move || app.update(|cx| callback(cx))))
2207        }
2208    }
2209
2210    fn handle_window_moved(&mut self, window_id: usize) {
2211        self.update_window(window_id, |cx| {
2212            if let Some(display) = cx.window_display_uuid() {
2213                let bounds = cx.window_bounds();
2214                cx.window_bounds_observations
2215                    .clone()
2216                    .emit(window_id, move |callback| {
2217                        callback(bounds, display, cx);
2218                        true
2219                    });
2220            }
2221        });
2222    }
2223
2224    fn handle_active_labeled_tasks_changed_effect(&mut self) {
2225        self.active_labeled_task_observations
2226            .clone()
2227            .emit((), move |callback| {
2228                callback(self);
2229                true
2230            });
2231    }
2232
2233    pub fn focus(&mut self, window_id: usize, view_id: Option<usize>) {
2234        self.pending_effects
2235            .push_back(Effect::Focus { window_id, view_id });
2236    }
2237
2238    fn spawn_internal<F, Fut, T>(&mut self, task_name: Option<&'static str>, f: F) -> Task<T>
2239    where
2240        F: FnOnce(AsyncAppContext) -> Fut,
2241        Fut: 'static + Future<Output = T>,
2242        T: 'static,
2243    {
2244        let label_id = task_name.map(|task_name| {
2245            let id = post_inc(&mut self.next_labeled_task_id);
2246            self.active_labeled_tasks.insert(id, task_name);
2247            self.pending_effects
2248                .push_back(Effect::ActiveLabeledTasksChanged);
2249            id
2250        });
2251
2252        let future = f(self.to_async());
2253        let cx = self.to_async();
2254        self.foreground.spawn(async move {
2255            let result = future.await;
2256            let mut cx = cx.0.borrow_mut();
2257
2258            if let Some(completed_label_id) = label_id {
2259                cx.active_labeled_tasks.remove(&completed_label_id);
2260                cx.pending_effects
2261                    .push_back(Effect::ActiveLabeledTasksChanged);
2262            }
2263            cx.flush_effects();
2264            result
2265        })
2266    }
2267
2268    pub fn spawn_labeled<F, Fut, T>(&mut self, task_name: &'static str, f: F) -> Task<T>
2269    where
2270        F: FnOnce(AsyncAppContext) -> Fut,
2271        Fut: 'static + Future<Output = T>,
2272        T: 'static,
2273    {
2274        self.spawn_internal(Some(task_name), f)
2275    }
2276
2277    pub fn spawn<F, Fut, T>(&mut self, f: F) -> Task<T>
2278    where
2279        F: FnOnce(AsyncAppContext) -> Fut,
2280        Fut: 'static + Future<Output = T>,
2281        T: 'static,
2282    {
2283        self.spawn_internal(None, f)
2284    }
2285
2286    pub fn to_async(&self) -> AsyncAppContext {
2287        AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
2288    }
2289
2290    pub fn write_to_clipboard(&self, item: ClipboardItem) {
2291        self.platform.write_to_clipboard(item);
2292    }
2293
2294    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
2295        self.platform.read_from_clipboard()
2296    }
2297
2298    #[cfg(any(test, feature = "test-support"))]
2299    pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
2300        self.ref_counts.lock().leak_detector.clone()
2301    }
2302}
2303
2304impl ReadModel for AppContext {
2305    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2306        if let Some(model) = self.models.get(&handle.model_id) {
2307            model
2308                .as_any()
2309                .downcast_ref()
2310                .expect("downcast is type safe")
2311        } else {
2312            panic!("circular model reference");
2313        }
2314    }
2315}
2316
2317impl UpdateModel for AppContext {
2318    fn update_model<T: Entity, V>(
2319        &mut self,
2320        handle: &ModelHandle<T>,
2321        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
2322    ) -> V {
2323        if let Some(mut model) = self.models.remove(&handle.model_id) {
2324            self.update(|this| {
2325                let mut cx = ModelContext::new(this, handle.model_id);
2326                let result = update(
2327                    model
2328                        .as_any_mut()
2329                        .downcast_mut()
2330                        .expect("downcast is type safe"),
2331                    &mut cx,
2332                );
2333                this.models.insert(handle.model_id, model);
2334                result
2335            })
2336        } else {
2337            panic!("circular model update");
2338        }
2339    }
2340}
2341
2342impl UpgradeModelHandle for AppContext {
2343    fn upgrade_model_handle<T: Entity>(
2344        &self,
2345        handle: &WeakModelHandle<T>,
2346    ) -> Option<ModelHandle<T>> {
2347        if self.models.contains_key(&handle.model_id) {
2348            Some(ModelHandle::new(handle.model_id, &self.ref_counts))
2349        } else {
2350            None
2351        }
2352    }
2353
2354    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2355        self.models.contains_key(&handle.model_id)
2356    }
2357
2358    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2359        if self.models.contains_key(&handle.model_id) {
2360            Some(AnyModelHandle::new(
2361                handle.model_id,
2362                handle.model_type,
2363                self.ref_counts.clone(),
2364            ))
2365        } else {
2366            None
2367        }
2368    }
2369}
2370
2371impl UpgradeViewHandle for AppContext {
2372    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2373        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2374            Some(ViewHandle::new(
2375                handle.window_id,
2376                handle.view_id,
2377                &self.ref_counts,
2378            ))
2379        } else {
2380            None
2381        }
2382    }
2383
2384    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
2385        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2386            Some(AnyViewHandle::new(
2387                handle.window_id,
2388                handle.view_id,
2389                handle.view_type,
2390                self.ref_counts.clone(),
2391            ))
2392        } else {
2393            None
2394        }
2395    }
2396}
2397
2398impl ReadView for AppContext {
2399    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2400        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
2401            view.as_any().downcast_ref().expect("downcast is type safe")
2402        } else {
2403            panic!("circular view reference for type {}", type_name::<T>());
2404        }
2405    }
2406}
2407
2408impl UpdateView for AppContext {
2409    fn update_view<T, S>(
2410        &mut self,
2411        handle: &ViewHandle<T>,
2412        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
2413    ) -> S
2414    where
2415        T: View,
2416    {
2417        self.update_window(handle.window_id, |cx| cx.update_view(handle, update))
2418            .unwrap() // TODO: Is this unwrap safe?
2419    }
2420}
2421
2422#[derive(Debug)]
2423pub enum ParentId {
2424    View(usize),
2425    Root,
2426}
2427
2428#[derive(Default, Clone)]
2429pub struct WindowInvalidation {
2430    pub updated: HashSet<usize>,
2431    pub removed: Vec<usize>,
2432}
2433
2434pub enum Effect {
2435    Subscription {
2436        entity_id: usize,
2437        subscription_id: usize,
2438        callback: SubscriptionCallback,
2439    },
2440    Event {
2441        entity_id: usize,
2442        payload: Box<dyn Any>,
2443    },
2444    GlobalSubscription {
2445        type_id: TypeId,
2446        subscription_id: usize,
2447        callback: GlobalSubscriptionCallback,
2448    },
2449    GlobalEvent {
2450        payload: Box<dyn Any>,
2451    },
2452    Observation {
2453        entity_id: usize,
2454        subscription_id: usize,
2455        callback: ObservationCallback,
2456    },
2457    ModelNotification {
2458        model_id: usize,
2459    },
2460    ViewNotification {
2461        window_id: usize,
2462        view_id: usize,
2463    },
2464    Deferred {
2465        callback: Box<dyn FnOnce(&mut AppContext)>,
2466        after_window_update: bool,
2467    },
2468    GlobalNotification {
2469        type_id: TypeId,
2470    },
2471    ModelRelease {
2472        model_id: usize,
2473        model: Box<dyn AnyModel>,
2474    },
2475    ViewRelease {
2476        view_id: usize,
2477        view: Box<dyn AnyView>,
2478    },
2479    Focus {
2480        window_id: usize,
2481        view_id: Option<usize>,
2482    },
2483    FocusObservation {
2484        view_id: usize,
2485        subscription_id: usize,
2486        callback: FocusObservationCallback,
2487    },
2488    ResizeWindow {
2489        window_id: usize,
2490    },
2491    MoveWindow {
2492        window_id: usize,
2493    },
2494    ActivateWindow {
2495        window_id: usize,
2496        is_active: bool,
2497    },
2498    WindowActivationObservation {
2499        window_id: usize,
2500        subscription_id: usize,
2501        callback: WindowActivationCallback,
2502    },
2503    FullscreenWindow {
2504        window_id: usize,
2505        is_fullscreen: bool,
2506    },
2507    WindowFullscreenObservation {
2508        window_id: usize,
2509        subscription_id: usize,
2510        callback: WindowFullscreenCallback,
2511    },
2512    WindowBoundsObservation {
2513        window_id: usize,
2514        subscription_id: usize,
2515        callback: WindowBoundsCallback,
2516    },
2517    Keystroke {
2518        window_id: usize,
2519        keystroke: Keystroke,
2520        handled_by: Option<Box<dyn Action>>,
2521        result: MatchResult,
2522    },
2523    RefreshWindows,
2524    DispatchActionFrom {
2525        window_id: usize,
2526        view_id: usize,
2527        action: Box<dyn Action>,
2528    },
2529    ActionDispatchNotification {
2530        action_id: TypeId,
2531    },
2532    WindowShouldCloseSubscription {
2533        window_id: usize,
2534        callback: WindowShouldCloseSubscriptionCallback,
2535    },
2536    ActiveLabeledTasksChanged,
2537    ActiveLabeledTasksObservation {
2538        subscription_id: usize,
2539        callback: ActiveLabeledTasksCallback,
2540    },
2541}
2542
2543impl Debug for Effect {
2544    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2545        match self {
2546            Effect::Subscription {
2547                entity_id,
2548                subscription_id,
2549                ..
2550            } => f
2551                .debug_struct("Effect::Subscribe")
2552                .field("entity_id", entity_id)
2553                .field("subscription_id", subscription_id)
2554                .finish(),
2555            Effect::Event { entity_id, .. } => f
2556                .debug_struct("Effect::Event")
2557                .field("entity_id", entity_id)
2558                .finish(),
2559            Effect::GlobalSubscription {
2560                type_id,
2561                subscription_id,
2562                ..
2563            } => f
2564                .debug_struct("Effect::Subscribe")
2565                .field("type_id", type_id)
2566                .field("subscription_id", subscription_id)
2567                .finish(),
2568            Effect::GlobalEvent { payload, .. } => f
2569                .debug_struct("Effect::GlobalEvent")
2570                .field("type_id", &(&*payload).type_id())
2571                .finish(),
2572            Effect::Observation {
2573                entity_id,
2574                subscription_id,
2575                ..
2576            } => f
2577                .debug_struct("Effect::Observation")
2578                .field("entity_id", entity_id)
2579                .field("subscription_id", subscription_id)
2580                .finish(),
2581            Effect::ModelNotification { model_id } => f
2582                .debug_struct("Effect::ModelNotification")
2583                .field("model_id", model_id)
2584                .finish(),
2585            Effect::ViewNotification { window_id, view_id } => f
2586                .debug_struct("Effect::ViewNotification")
2587                .field("window_id", window_id)
2588                .field("view_id", view_id)
2589                .finish(),
2590            Effect::GlobalNotification { type_id } => f
2591                .debug_struct("Effect::GlobalNotification")
2592                .field("type_id", type_id)
2593                .finish(),
2594            Effect::Deferred { .. } => f.debug_struct("Effect::Deferred").finish(),
2595            Effect::ModelRelease { model_id, .. } => f
2596                .debug_struct("Effect::ModelRelease")
2597                .field("model_id", model_id)
2598                .finish(),
2599            Effect::ViewRelease { view_id, .. } => f
2600                .debug_struct("Effect::ViewRelease")
2601                .field("view_id", view_id)
2602                .finish(),
2603            Effect::Focus { window_id, view_id } => f
2604                .debug_struct("Effect::Focus")
2605                .field("window_id", window_id)
2606                .field("view_id", view_id)
2607                .finish(),
2608            Effect::FocusObservation {
2609                view_id,
2610                subscription_id,
2611                ..
2612            } => f
2613                .debug_struct("Effect::FocusObservation")
2614                .field("view_id", view_id)
2615                .field("subscription_id", subscription_id)
2616                .finish(),
2617            Effect::DispatchActionFrom {
2618                window_id, view_id, ..
2619            } => f
2620                .debug_struct("Effect::DispatchActionFrom")
2621                .field("window_id", window_id)
2622                .field("view_id", view_id)
2623                .finish(),
2624            Effect::ActionDispatchNotification { action_id, .. } => f
2625                .debug_struct("Effect::ActionDispatchNotification")
2626                .field("action_id", action_id)
2627                .finish(),
2628            Effect::ResizeWindow { window_id } => f
2629                .debug_struct("Effect::RefreshWindow")
2630                .field("window_id", window_id)
2631                .finish(),
2632            Effect::MoveWindow { window_id } => f
2633                .debug_struct("Effect::MoveWindow")
2634                .field("window_id", window_id)
2635                .finish(),
2636            Effect::WindowActivationObservation {
2637                window_id,
2638                subscription_id,
2639                ..
2640            } => f
2641                .debug_struct("Effect::WindowActivationObservation")
2642                .field("window_id", window_id)
2643                .field("subscription_id", subscription_id)
2644                .finish(),
2645            Effect::ActivateWindow {
2646                window_id,
2647                is_active,
2648            } => f
2649                .debug_struct("Effect::ActivateWindow")
2650                .field("window_id", window_id)
2651                .field("is_active", is_active)
2652                .finish(),
2653            Effect::FullscreenWindow {
2654                window_id,
2655                is_fullscreen,
2656            } => f
2657                .debug_struct("Effect::FullscreenWindow")
2658                .field("window_id", window_id)
2659                .field("is_fullscreen", is_fullscreen)
2660                .finish(),
2661            Effect::WindowFullscreenObservation {
2662                window_id,
2663                subscription_id,
2664                callback: _,
2665            } => f
2666                .debug_struct("Effect::WindowFullscreenObservation")
2667                .field("window_id", window_id)
2668                .field("subscription_id", subscription_id)
2669                .finish(),
2670
2671            Effect::WindowBoundsObservation {
2672                window_id,
2673                subscription_id,
2674                callback: _,
2675            } => f
2676                .debug_struct("Effect::WindowBoundsObservation")
2677                .field("window_id", window_id)
2678                .field("subscription_id", subscription_id)
2679                .finish(),
2680            Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
2681            Effect::WindowShouldCloseSubscription { window_id, .. } => f
2682                .debug_struct("Effect::WindowShouldCloseSubscription")
2683                .field("window_id", window_id)
2684                .finish(),
2685            Effect::Keystroke {
2686                window_id,
2687                keystroke,
2688                handled_by,
2689                result,
2690            } => f
2691                .debug_struct("Effect::Keystroke")
2692                .field("window_id", window_id)
2693                .field("keystroke", keystroke)
2694                .field(
2695                    "keystroke",
2696                    &handled_by.as_ref().map(|handled_by| handled_by.name()),
2697                )
2698                .field("result", result)
2699                .finish(),
2700            Effect::ActiveLabeledTasksChanged => {
2701                f.debug_struct("Effect::ActiveLabeledTasksChanged").finish()
2702            }
2703            Effect::ActiveLabeledTasksObservation {
2704                subscription_id,
2705                callback: _,
2706            } => f
2707                .debug_struct("Effect::ActiveLabeledTasksObservation")
2708                .field("subscription_id", subscription_id)
2709                .finish(),
2710        }
2711    }
2712}
2713
2714pub trait AnyModel {
2715    fn as_any(&self) -> &dyn Any;
2716    fn as_any_mut(&mut self) -> &mut dyn Any;
2717    fn release(&mut self, cx: &mut AppContext);
2718    fn app_will_quit(
2719        &mut self,
2720        cx: &mut AppContext,
2721    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2722}
2723
2724impl<T> AnyModel for T
2725where
2726    T: Entity,
2727{
2728    fn as_any(&self) -> &dyn Any {
2729        self
2730    }
2731
2732    fn as_any_mut(&mut self) -> &mut dyn Any {
2733        self
2734    }
2735
2736    fn release(&mut self, cx: &mut AppContext) {
2737        self.release(cx);
2738    }
2739
2740    fn app_will_quit(
2741        &mut self,
2742        cx: &mut AppContext,
2743    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2744        self.app_will_quit(cx)
2745    }
2746}
2747
2748pub trait AnyView {
2749    fn as_any(&self) -> &dyn Any;
2750    fn as_any_mut(&mut self) -> &mut dyn Any;
2751    fn release(&mut self, cx: &mut AppContext);
2752    fn app_will_quit(
2753        &mut self,
2754        cx: &mut AppContext,
2755    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2756    fn ui_name(&self) -> &'static str;
2757    fn render(&mut self, cx: &mut WindowContext, view_id: usize) -> Box<dyn AnyRootElement>;
2758    fn focus_in<'a, 'b>(
2759        &mut self,
2760        focused_id: usize,
2761        cx: &mut WindowContext<'a, 'b>,
2762        view_id: usize,
2763    );
2764    fn focus_out(&mut self, focused_id: usize, cx: &mut WindowContext, view_id: usize);
2765    fn key_down(&mut self, event: &KeyDownEvent, cx: &mut WindowContext, view_id: usize) -> bool;
2766    fn key_up(&mut self, event: &KeyUpEvent, cx: &mut WindowContext, view_id: usize) -> bool;
2767    fn modifiers_changed(
2768        &mut self,
2769        event: &ModifiersChangedEvent,
2770        cx: &mut WindowContext,
2771        view_id: usize,
2772    ) -> bool;
2773    fn keymap_context(&self, cx: &AppContext) -> KeymapContext;
2774    fn debug_json(&self, cx: &WindowContext) -> serde_json::Value;
2775
2776    fn text_for_range(&self, range: Range<usize>, cx: &WindowContext) -> Option<String>;
2777    fn selected_text_range(&self, cx: &WindowContext) -> Option<Range<usize>>;
2778    fn marked_text_range(&self, cx: &WindowContext) -> Option<Range<usize>>;
2779    fn unmark_text(&mut self, cx: &mut WindowContext, view_id: usize);
2780    fn replace_text_in_range(
2781        &mut self,
2782        range: Option<Range<usize>>,
2783        text: &str,
2784        cx: &mut WindowContext,
2785        view_id: usize,
2786    );
2787    fn replace_and_mark_text_in_range(
2788        &mut self,
2789        range: Option<Range<usize>>,
2790        new_text: &str,
2791        new_selected_range: Option<Range<usize>>,
2792        cx: &mut WindowContext,
2793        view_id: usize,
2794    );
2795    fn any_handle(&self, window_id: usize, view_id: usize, cx: &AppContext) -> AnyViewHandle {
2796        AnyViewHandle::new(
2797            window_id,
2798            view_id,
2799            self.as_any().type_id(),
2800            cx.ref_counts.clone(),
2801        )
2802    }
2803}
2804
2805impl<V> AnyView for V
2806where
2807    V: View,
2808{
2809    fn as_any(&self) -> &dyn Any {
2810        self
2811    }
2812
2813    fn as_any_mut(&mut self) -> &mut dyn Any {
2814        self
2815    }
2816
2817    fn release(&mut self, cx: &mut AppContext) {
2818        self.release(cx);
2819    }
2820
2821    fn app_will_quit(
2822        &mut self,
2823        cx: &mut AppContext,
2824    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2825        self.app_will_quit(cx)
2826    }
2827
2828    fn ui_name(&self) -> &'static str {
2829        V::ui_name()
2830    }
2831
2832    fn render(&mut self, cx: &mut WindowContext, view_id: usize) -> Box<dyn AnyRootElement> {
2833        let mut view_context = ViewContext::mutable(cx, view_id);
2834        let element = V::render(self, &mut view_context);
2835        let view = WeakViewHandle::new(cx.window_id, view_id);
2836        Box::new(RootElement::new(element, view))
2837    }
2838
2839    fn focus_in(&mut self, focused_id: usize, cx: &mut WindowContext, view_id: usize) {
2840        let mut cx = ViewContext::mutable(cx, view_id);
2841        let focused_view_handle: AnyViewHandle = if view_id == focused_id {
2842            cx.handle().into_any()
2843        } else {
2844            let focused_type = cx
2845                .views
2846                .get(&(cx.window_id, focused_id))
2847                .unwrap()
2848                .as_any()
2849                .type_id();
2850            AnyViewHandle::new(
2851                cx.window_id,
2852                focused_id,
2853                focused_type,
2854                cx.ref_counts.clone(),
2855            )
2856        };
2857        View::focus_in(self, focused_view_handle, &mut cx);
2858    }
2859
2860    fn focus_out(&mut self, blurred_id: usize, cx: &mut WindowContext, view_id: usize) {
2861        let mut cx = ViewContext::mutable(cx, view_id);
2862        let blurred_view_handle: AnyViewHandle = if view_id == blurred_id {
2863            cx.handle().into_any()
2864        } else {
2865            let blurred_type = cx
2866                .views
2867                .get(&(cx.window_id, blurred_id))
2868                .unwrap()
2869                .as_any()
2870                .type_id();
2871            AnyViewHandle::new(
2872                cx.window_id,
2873                blurred_id,
2874                blurred_type,
2875                cx.ref_counts.clone(),
2876            )
2877        };
2878        View::focus_out(self, blurred_view_handle, &mut cx);
2879    }
2880
2881    fn key_down(&mut self, event: &KeyDownEvent, cx: &mut WindowContext, view_id: usize) -> bool {
2882        let mut cx = ViewContext::mutable(cx, view_id);
2883        View::key_down(self, event, &mut cx)
2884    }
2885
2886    fn key_up(&mut self, event: &KeyUpEvent, cx: &mut WindowContext, view_id: usize) -> bool {
2887        let mut cx = ViewContext::mutable(cx, view_id);
2888        View::key_up(self, event, &mut cx)
2889    }
2890
2891    fn modifiers_changed(
2892        &mut self,
2893        event: &ModifiersChangedEvent,
2894        cx: &mut WindowContext,
2895        view_id: usize,
2896    ) -> bool {
2897        let mut cx = ViewContext::mutable(cx, view_id);
2898        View::modifiers_changed(self, event, &mut cx)
2899    }
2900
2901    fn keymap_context(&self, cx: &AppContext) -> KeymapContext {
2902        View::keymap_context(self, cx)
2903    }
2904
2905    fn debug_json(&self, cx: &WindowContext) -> serde_json::Value {
2906        View::debug_json(self, cx)
2907    }
2908
2909    fn text_for_range(&self, range: Range<usize>, cx: &WindowContext) -> Option<String> {
2910        View::text_for_range(self, range, cx)
2911    }
2912
2913    fn selected_text_range(&self, cx: &WindowContext) -> Option<Range<usize>> {
2914        View::selected_text_range(self, cx)
2915    }
2916
2917    fn marked_text_range(&self, cx: &WindowContext) -> Option<Range<usize>> {
2918        View::marked_text_range(self, cx)
2919    }
2920
2921    fn unmark_text(&mut self, cx: &mut WindowContext, view_id: usize) {
2922        let mut cx = ViewContext::mutable(cx, view_id);
2923        View::unmark_text(self, &mut cx)
2924    }
2925
2926    fn replace_text_in_range(
2927        &mut self,
2928        range: Option<Range<usize>>,
2929        text: &str,
2930        cx: &mut WindowContext,
2931        view_id: usize,
2932    ) {
2933        let mut cx = ViewContext::mutable(cx, view_id);
2934        View::replace_text_in_range(self, range, text, &mut cx)
2935    }
2936
2937    fn replace_and_mark_text_in_range(
2938        &mut self,
2939        range: Option<Range<usize>>,
2940        new_text: &str,
2941        new_selected_range: Option<Range<usize>>,
2942        cx: &mut WindowContext,
2943        view_id: usize,
2944    ) {
2945        let mut cx = ViewContext::mutable(cx, view_id);
2946        View::replace_and_mark_text_in_range(self, range, new_text, new_selected_range, &mut cx)
2947    }
2948}
2949
2950pub struct ModelContext<'a, T: ?Sized> {
2951    app: &'a mut AppContext,
2952    model_id: usize,
2953    model_type: PhantomData<T>,
2954    halt_stream: bool,
2955}
2956
2957impl<'a, T: Entity> ModelContext<'a, T> {
2958    fn new(app: &'a mut AppContext, model_id: usize) -> Self {
2959        Self {
2960            app,
2961            model_id,
2962            model_type: PhantomData,
2963            halt_stream: false,
2964        }
2965    }
2966
2967    pub fn background(&self) -> &Arc<executor::Background> {
2968        &self.app.background
2969    }
2970
2971    pub fn halt_stream(&mut self) {
2972        self.halt_stream = true;
2973    }
2974
2975    pub fn model_id(&self) -> usize {
2976        self.model_id
2977    }
2978
2979    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2980    where
2981        S: Entity,
2982        F: FnOnce(&mut ModelContext<S>) -> S,
2983    {
2984        self.app.add_model(build_model)
2985    }
2986
2987    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ModelContext<T>)) {
2988        let handle = self.handle();
2989        self.app.defer(move |cx| {
2990            handle.update(cx, |model, cx| {
2991                callback(model, cx);
2992            })
2993        })
2994    }
2995
2996    pub fn emit(&mut self, payload: T::Event) {
2997        self.app.pending_effects.push_back(Effect::Event {
2998            entity_id: self.model_id,
2999            payload: Box::new(payload),
3000        });
3001    }
3002
3003    pub fn notify(&mut self) {
3004        self.app.notify_model(self.model_id);
3005    }
3006
3007    pub fn subscribe<S: Entity, F>(
3008        &mut self,
3009        handle: &ModelHandle<S>,
3010        mut callback: F,
3011    ) -> Subscription
3012    where
3013        S::Event: 'static,
3014        F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
3015    {
3016        let subscriber = self.weak_handle();
3017        self.app
3018            .subscribe_internal(handle, move |emitter, event, cx| {
3019                if let Some(subscriber) = subscriber.upgrade(cx) {
3020                    subscriber.update(cx, |subscriber, cx| {
3021                        callback(subscriber, emitter, event, cx);
3022                    });
3023                    true
3024                } else {
3025                    false
3026                }
3027            })
3028    }
3029
3030    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
3031    where
3032        S: Entity,
3033        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
3034    {
3035        let observer = self.weak_handle();
3036        self.app.observe_internal(handle, move |observed, cx| {
3037            if let Some(observer) = observer.upgrade(cx) {
3038                observer.update(cx, |observer, cx| {
3039                    callback(observer, observed, cx);
3040                });
3041                true
3042            } else {
3043                false
3044            }
3045        })
3046    }
3047
3048    pub fn observe_global<G, F>(&mut self, mut callback: F) -> Subscription
3049    where
3050        G: Any,
3051        F: 'static + FnMut(&mut T, &mut ModelContext<T>),
3052    {
3053        let observer = self.weak_handle();
3054        self.app.observe_global::<G, _>(move |cx| {
3055            if let Some(observer) = observer.upgrade(cx) {
3056                observer.update(cx, |observer, cx| callback(observer, cx));
3057            }
3058        })
3059    }
3060
3061    pub fn observe_release<S, F>(
3062        &mut self,
3063        handle: &ModelHandle<S>,
3064        mut callback: F,
3065    ) -> Subscription
3066    where
3067        S: Entity,
3068        F: 'static + FnMut(&mut T, &S, &mut ModelContext<T>),
3069    {
3070        let observer = self.weak_handle();
3071        self.app.observe_release(handle, move |released, cx| {
3072            if let Some(observer) = observer.upgrade(cx) {
3073                observer.update(cx, |observer, cx| {
3074                    callback(observer, released, cx);
3075                });
3076            }
3077        })
3078    }
3079
3080    pub fn handle(&self) -> ModelHandle<T> {
3081        ModelHandle::new(self.model_id, &self.app.ref_counts)
3082    }
3083
3084    pub fn weak_handle(&self) -> WeakModelHandle<T> {
3085        WeakModelHandle::new(self.model_id)
3086    }
3087
3088    pub fn spawn<F, Fut, S>(&mut self, f: F) -> Task<S>
3089    where
3090        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
3091        Fut: 'static + Future<Output = S>,
3092        S: 'static,
3093    {
3094        let handle = self.handle();
3095        self.app.spawn(|cx| f(handle, cx))
3096    }
3097
3098    pub fn spawn_weak<F, Fut, S>(&mut self, f: F) -> Task<S>
3099    where
3100        F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
3101        Fut: 'static + Future<Output = S>,
3102        S: 'static,
3103    {
3104        let handle = self.weak_handle();
3105        self.app.spawn(|cx| f(handle, cx))
3106    }
3107}
3108
3109impl<M> AsRef<AppContext> for ModelContext<'_, M> {
3110    fn as_ref(&self) -> &AppContext {
3111        &self.app
3112    }
3113}
3114
3115impl<M> AsMut<AppContext> for ModelContext<'_, M> {
3116    fn as_mut(&mut self) -> &mut AppContext {
3117        self.app
3118    }
3119}
3120
3121impl<M> ReadModel for ModelContext<'_, M> {
3122    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
3123        self.app.read_model(handle)
3124    }
3125}
3126
3127impl<M> UpdateModel for ModelContext<'_, M> {
3128    fn update_model<T: Entity, V>(
3129        &mut self,
3130        handle: &ModelHandle<T>,
3131        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
3132    ) -> V {
3133        self.app.update_model(handle, update)
3134    }
3135}
3136
3137impl<M> UpgradeModelHandle for ModelContext<'_, M> {
3138    fn upgrade_model_handle<T: Entity>(
3139        &self,
3140        handle: &WeakModelHandle<T>,
3141    ) -> Option<ModelHandle<T>> {
3142        self.app.upgrade_model_handle(handle)
3143    }
3144
3145    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
3146        self.app.model_handle_is_upgradable(handle)
3147    }
3148
3149    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
3150        self.app.upgrade_any_model_handle(handle)
3151    }
3152}
3153
3154impl<M> Deref for ModelContext<'_, M> {
3155    type Target = AppContext;
3156
3157    fn deref(&self) -> &Self::Target {
3158        self.app
3159    }
3160}
3161
3162impl<M> DerefMut for ModelContext<'_, M> {
3163    fn deref_mut(&mut self) -> &mut Self::Target {
3164        &mut self.app
3165    }
3166}
3167
3168pub struct ViewContext<'a, 'b, 'c, T: ?Sized> {
3169    window_context: Reference<'c, WindowContext<'a, 'b>>,
3170    view_id: usize,
3171    view_type: PhantomData<T>,
3172}
3173
3174impl<'a, 'b, 'c, T: View> Deref for ViewContext<'a, 'b, 'c, T> {
3175    type Target = WindowContext<'a, 'b>;
3176
3177    fn deref(&self) -> &Self::Target {
3178        &self.window_context
3179    }
3180}
3181
3182impl<T: View> DerefMut for ViewContext<'_, '_, '_, T> {
3183    fn deref_mut(&mut self) -> &mut Self::Target {
3184        &mut self.window_context
3185    }
3186}
3187
3188impl<'a, 'b, 'c, V: View> ViewContext<'a, 'b, 'c, V> {
3189    pub(crate) fn mutable(window_context: &'c mut WindowContext<'a, 'b>, view_id: usize) -> Self {
3190        Self {
3191            window_context: Reference::Mutable(window_context),
3192            view_id,
3193            view_type: PhantomData,
3194        }
3195    }
3196
3197    pub(crate) fn immutable(window_context: &'c WindowContext<'a, 'b>, view_id: usize) -> Self {
3198        Self {
3199            window_context: Reference::Immutable(window_context),
3200            view_id,
3201            view_type: PhantomData,
3202        }
3203    }
3204
3205    pub fn handle(&self) -> ViewHandle<V> {
3206        ViewHandle::new(
3207            self.window_id,
3208            self.view_id,
3209            &self.window_context.ref_counts,
3210        )
3211    }
3212
3213    pub fn weak_handle(&self) -> WeakViewHandle<V> {
3214        WeakViewHandle::new(self.window_id, self.view_id)
3215    }
3216
3217    pub fn parent(&self) -> Option<usize> {
3218        self.window_context.parent(self.window_id, self.view_id)
3219    }
3220
3221    pub fn window_id(&self) -> usize {
3222        self.window_id
3223    }
3224
3225    pub fn view_id(&self) -> usize {
3226        self.view_id
3227    }
3228
3229    pub fn foreground(&self) -> &Rc<executor::Foreground> {
3230        self.window_context.foreground()
3231    }
3232
3233    pub fn background_executor(&self) -> &Arc<executor::Background> {
3234        &self.window_context.background
3235    }
3236
3237    pub fn platform(&self) -> &Arc<dyn Platform> {
3238        self.window_context.platform()
3239    }
3240
3241    pub fn prompt_for_paths(
3242        &self,
3243        options: PathPromptOptions,
3244    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
3245        self.window_context.prompt_for_paths(options)
3246    }
3247
3248    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
3249        self.window_context.prompt_for_new_path(directory)
3250    }
3251
3252    pub fn reveal_path(&self, path: &Path) {
3253        self.window_context.reveal_path(path)
3254    }
3255
3256    pub fn focus(&mut self, handle: &AnyViewHandle) {
3257        self.window_context
3258            .focus(handle.window_id, Some(handle.view_id));
3259    }
3260
3261    pub fn focus_self(&mut self) {
3262        let window_id = self.window_id;
3263        let view_id = self.view_id;
3264        self.window_context.focus(window_id, Some(view_id));
3265    }
3266
3267    pub fn is_self_focused(&self) -> bool {
3268        self.window.focused_view_id == Some(self.view_id)
3269    }
3270
3271    pub fn is_parent_view_focused(&self) -> bool {
3272        if let Some(parent_view_id) = self.ancestors(self.window_id, self.view_id).next().clone() {
3273            self.focused_view_id() == Some(parent_view_id)
3274        } else {
3275            false
3276        }
3277    }
3278
3279    pub fn focus_parent_view(&mut self) {
3280        let next = self.ancestors(self.window_id, self.view_id).next().clone();
3281        if let Some(parent_view_id) = next {
3282            let window_id = self.window_id;
3283            self.window_context.focus(window_id, Some(parent_view_id));
3284        }
3285    }
3286
3287    pub fn is_child(&self, view: impl Into<AnyViewHandle>) -> bool {
3288        let view = view.into();
3289        if self.window_id != view.window_id {
3290            return false;
3291        }
3292        self.ancestors(view.window_id, view.view_id)
3293            .skip(1) // Skip self id
3294            .any(|parent| parent == self.view_id)
3295    }
3296
3297    pub fn blur(&mut self) {
3298        let window_id = self.window_id;
3299        self.window_context.focus(window_id, None);
3300    }
3301
3302    pub fn on_window_should_close<F>(&mut self, mut callback: F)
3303    where
3304        F: 'static + FnMut(&mut V, &mut ViewContext<V>) -> bool,
3305    {
3306        let window_id = self.window_id();
3307        let view = self.weak_handle();
3308        self.pending_effects
3309            .push_back(Effect::WindowShouldCloseSubscription {
3310                window_id,
3311                callback: Box::new(move |cx| {
3312                    if let Some(view) = view.upgrade(cx) {
3313                        view.update(cx, |view, cx| callback(view, cx))
3314                    } else {
3315                        true
3316                    }
3317                }),
3318            });
3319    }
3320
3321    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
3322    where
3323        S: View,
3324        F: FnOnce(&mut ViewContext<S>) -> S,
3325    {
3326        self.window_context
3327            .build_and_insert_view(ParentId::View(self.view_id), |cx| Some(build_view(cx)))
3328            .unwrap()
3329    }
3330
3331    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
3332    where
3333        S: View,
3334        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
3335    {
3336        self.window_context
3337            .build_and_insert_view(ParentId::View(self.view_id), build_view)
3338    }
3339
3340    pub fn reparent(&mut self, view_handle: &AnyViewHandle) {
3341        if self.window_id != view_handle.window_id {
3342            panic!("Can't reparent view to a view from a different window");
3343        }
3344        self.parents
3345            .remove(&(view_handle.window_id, view_handle.view_id));
3346        let new_parent_id = self.view_id;
3347        self.parents.insert(
3348            (view_handle.window_id, view_handle.view_id),
3349            ParentId::View(new_parent_id),
3350        );
3351    }
3352
3353    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
3354    where
3355        E: Entity,
3356        E::Event: 'static,
3357        H: Handle<E>,
3358        F: 'static + FnMut(&mut V, H, &E::Event, &mut ViewContext<V>),
3359    {
3360        let subscriber = self.weak_handle();
3361        self.window_context
3362            .subscribe_internal(handle, move |emitter, event, cx| {
3363                if let Some(subscriber) = subscriber.upgrade(cx) {
3364                    subscriber.update(cx, |subscriber, cx| {
3365                        callback(subscriber, emitter, event, cx);
3366                    });
3367                    true
3368                } else {
3369                    false
3370                }
3371            })
3372    }
3373
3374    pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3375    where
3376        E: Entity,
3377        H: Handle<E>,
3378        F: 'static + FnMut(&mut V, H, &mut ViewContext<V>),
3379    {
3380        let observer = self.weak_handle();
3381        self.window_context
3382            .observe_internal(handle, move |observed, cx| {
3383                if let Some(observer) = observer.upgrade(cx) {
3384                    observer.update(cx, |observer, cx| {
3385                        callback(observer, observed, cx);
3386                    });
3387                    true
3388                } else {
3389                    false
3390                }
3391            })
3392    }
3393
3394    pub fn observe_global<G, F>(&mut self, mut callback: F) -> Subscription
3395    where
3396        G: Any,
3397        F: 'static + FnMut(&mut V, &mut ViewContext<V>),
3398    {
3399        let observer = self.weak_handle();
3400        self.window_context.observe_global::<G, _>(move |cx| {
3401            if let Some(observer) = observer.upgrade(cx) {
3402                observer.update(cx, |observer, cx| callback(observer, cx));
3403            }
3404        })
3405    }
3406
3407    pub fn observe_focus<F, W>(&mut self, handle: &ViewHandle<W>, mut callback: F) -> Subscription
3408    where
3409        F: 'static + FnMut(&mut V, ViewHandle<W>, bool, &mut ViewContext<V>),
3410        W: View,
3411    {
3412        let observer = self.weak_handle();
3413        self.window_context
3414            .observe_focus(handle, move |observed, focused, cx| {
3415                if let Some(observer) = observer.upgrade(cx) {
3416                    observer.update(cx, |observer, cx| {
3417                        callback(observer, observed, focused, cx);
3418                    });
3419                    true
3420                } else {
3421                    false
3422                }
3423            })
3424    }
3425
3426    pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3427    where
3428        E: Entity,
3429        H: Handle<E>,
3430        F: 'static + FnMut(&mut V, &E, &mut ViewContext<V>),
3431    {
3432        let observer = self.weak_handle();
3433        self.window_context
3434            .observe_release(handle, move |released, cx| {
3435                if let Some(observer) = observer.upgrade(cx) {
3436                    observer.update(cx, |observer, cx| {
3437                        callback(observer, released, cx);
3438                    });
3439                }
3440            })
3441    }
3442
3443    pub fn observe_actions<F>(&mut self, mut callback: F) -> Subscription
3444    where
3445        F: 'static + FnMut(&mut V, TypeId, &mut ViewContext<V>),
3446    {
3447        let observer = self.weak_handle();
3448        self.window_context.observe_actions(move |action_id, cx| {
3449            if let Some(observer) = observer.upgrade(cx) {
3450                observer.update(cx, |observer, cx| {
3451                    callback(observer, action_id, cx);
3452                });
3453            }
3454        })
3455    }
3456
3457    pub fn observe_window_activation<F>(&mut self, mut callback: F) -> Subscription
3458    where
3459        F: 'static + FnMut(&mut V, bool, &mut ViewContext<V>),
3460    {
3461        let observer = self.weak_handle();
3462        let window_id = self.window_id;
3463        self.window_context
3464            .observe_window_activation(window_id, move |active, cx| {
3465                if let Some(observer) = observer.upgrade(cx) {
3466                    observer.update(cx, |observer, cx| {
3467                        callback(observer, active, cx);
3468                    });
3469                    true
3470                } else {
3471                    false
3472                }
3473            })
3474    }
3475
3476    pub fn observe_fullscreen<F>(&mut self, mut callback: F) -> Subscription
3477    where
3478        F: 'static + FnMut(&mut V, bool, &mut ViewContext<V>),
3479    {
3480        let observer = self.weak_handle();
3481        let window_id = self.window_id;
3482        self.window_context
3483            .observe_fullscreen(window_id, move |active, cx| {
3484                if let Some(observer) = observer.upgrade(cx) {
3485                    observer.update(cx, |observer, cx| {
3486                        callback(observer, active, cx);
3487                    });
3488                    true
3489                } else {
3490                    false
3491                }
3492            })
3493    }
3494
3495    pub fn observe_keystrokes<F>(&mut self, mut callback: F) -> Subscription
3496    where
3497        F: 'static
3498            + FnMut(
3499                &mut V,
3500                &Keystroke,
3501                Option<&Box<dyn Action>>,
3502                &MatchResult,
3503                &mut ViewContext<V>,
3504            ) -> bool,
3505    {
3506        let observer = self.weak_handle();
3507        let window_id = self.window_id;
3508        self.window_context.observe_keystrokes(
3509            window_id,
3510            move |keystroke, result, handled_by, cx| {
3511                if let Some(observer) = observer.upgrade(cx) {
3512                    observer.update(cx, |observer, cx| {
3513                        callback(observer, keystroke, handled_by, result, cx);
3514                    });
3515                    true
3516                } else {
3517                    false
3518                }
3519            },
3520        )
3521    }
3522
3523    pub fn observe_window_bounds<F>(&mut self, mut callback: F) -> Subscription
3524    where
3525        F: 'static + FnMut(&mut V, WindowBounds, Uuid, &mut ViewContext<V>),
3526    {
3527        let observer = self.weak_handle();
3528        let window_id = self.window_id;
3529        self.window_context
3530            .observe_window_bounds(window_id, move |bounds, display, cx| {
3531                if let Some(observer) = observer.upgrade(cx) {
3532                    observer.update(cx, |observer, cx| {
3533                        callback(observer, bounds, display, cx);
3534                    });
3535                    true
3536                } else {
3537                    false
3538                }
3539            })
3540    }
3541
3542    pub fn observe_active_labeled_tasks<F>(&mut self, mut callback: F) -> Subscription
3543    where
3544        F: 'static + FnMut(&mut V, &mut ViewContext<V>),
3545    {
3546        let observer = self.weak_handle();
3547        self.window_context.observe_active_labeled_tasks(move |cx| {
3548            if let Some(observer) = observer.upgrade(cx) {
3549                observer.update(cx, |observer, cx| {
3550                    callback(observer, cx);
3551                });
3552                true
3553            } else {
3554                false
3555            }
3556        })
3557    }
3558
3559    pub fn emit(&mut self, payload: V::Event) {
3560        self.window_context
3561            .pending_effects
3562            .push_back(Effect::Event {
3563                entity_id: self.view_id,
3564                payload: Box::new(payload),
3565            });
3566    }
3567
3568    pub fn notify(&mut self) {
3569        let window_id = self.window_id;
3570        let view_id = self.view_id;
3571        self.window_context.notify_view(window_id, view_id);
3572    }
3573
3574    pub fn dispatch_action(&mut self, action: impl Action) {
3575        let window_id = self.window_id;
3576        let view_id = self.view_id;
3577        self.window_context
3578            .dispatch_action_at(window_id, view_id, action)
3579    }
3580
3581    pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
3582        let window_id = self.window_id;
3583        let view_id = self.view_id;
3584        self.window_context
3585            .dispatch_any_action_at(window_id, view_id, action)
3586    }
3587
3588    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut V, &mut ViewContext<V>)) {
3589        let handle = self.handle();
3590        self.window_context.defer(move |cx| {
3591            handle.update(cx, |view, cx| {
3592                callback(view, cx);
3593            })
3594        })
3595    }
3596
3597    pub fn after_window_update(
3598        &mut self,
3599        callback: impl 'static + FnOnce(&mut V, &mut ViewContext<V>),
3600    ) {
3601        let handle = self.handle();
3602        self.window_context.after_window_update(move |cx| {
3603            handle.update(cx, |view, cx| {
3604                callback(view, cx);
3605            })
3606        })
3607    }
3608
3609    pub fn propagate_action(&mut self) {
3610        self.window_context.halt_action_dispatch = false;
3611    }
3612
3613    pub fn spawn_labeled<F, Fut, S>(&mut self, task_label: &'static str, f: F) -> Task<S>
3614    where
3615        F: FnOnce(ViewHandle<V>, AsyncAppContext) -> Fut,
3616        Fut: 'static + Future<Output = S>,
3617        S: 'static,
3618    {
3619        let handle = self.handle();
3620        self.window_context
3621            .spawn_labeled(task_label, |cx| f(handle, cx))
3622    }
3623
3624    pub fn spawn<F, Fut, S>(&mut self, f: F) -> Task<S>
3625    where
3626        F: FnOnce(ViewHandle<V>, AsyncAppContext) -> Fut,
3627        Fut: 'static + Future<Output = S>,
3628        S: 'static,
3629    {
3630        let handle = self.handle();
3631        self.window_context.spawn(|cx| f(handle, cx))
3632    }
3633
3634    pub fn spawn_weak<F, Fut, S>(&mut self, f: F) -> Task<S>
3635    where
3636        F: FnOnce(WeakViewHandle<V>, AsyncAppContext) -> Fut,
3637        Fut: 'static + Future<Output = S>,
3638        S: 'static,
3639    {
3640        let handle = self.weak_handle();
3641        self.window_context.spawn(|cx| f(handle, cx))
3642    }
3643
3644    pub fn mouse_state<Tag: 'static>(&self, region_id: usize) -> MouseState {
3645        let region_id = MouseRegionId::new::<Tag>(self.view_id, region_id);
3646        MouseState {
3647            hovered: self.window.hovered_region_ids.contains(&region_id),
3648            clicked: self
3649                .window
3650                .clicked_region_ids
3651                .get(&region_id)
3652                .and_then(|_| self.window.clicked_button),
3653            accessed_hovered: false,
3654            accessed_clicked: false,
3655        }
3656    }
3657
3658    pub fn element_state<Tag: 'static, T: 'static>(
3659        &mut self,
3660        element_id: usize,
3661        initial: T,
3662    ) -> ElementStateHandle<T> {
3663        let id = ElementStateId {
3664            view_id: self.view_id(),
3665            element_id,
3666            tag: TypeId::of::<Tag>(),
3667        };
3668        self.element_states
3669            .entry(id)
3670            .or_insert_with(|| Box::new(initial));
3671        ElementStateHandle::new(id, self.frame_count, &self.ref_counts)
3672    }
3673
3674    pub fn default_element_state<Tag: 'static, T: 'static + Default>(
3675        &mut self,
3676        element_id: usize,
3677    ) -> ElementStateHandle<T> {
3678        self.element_state::<Tag, T>(element_id, T::default())
3679    }
3680}
3681
3682impl<V> UpgradeModelHandle for ViewContext<'_, '_, '_, V> {
3683    fn upgrade_model_handle<T: Entity>(
3684        &self,
3685        handle: &WeakModelHandle<T>,
3686    ) -> Option<ModelHandle<T>> {
3687        self.window_context.upgrade_model_handle(handle)
3688    }
3689
3690    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
3691        self.window_context.model_handle_is_upgradable(handle)
3692    }
3693
3694    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
3695        self.window_context.upgrade_any_model_handle(handle)
3696    }
3697}
3698
3699impl<V> UpgradeViewHandle for ViewContext<'_, '_, '_, V> {
3700    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
3701        self.window_context.upgrade_view_handle(handle)
3702    }
3703
3704    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
3705        self.window_context.upgrade_any_view_handle(handle)
3706    }
3707}
3708
3709impl<V: View> ReadModel for ViewContext<'_, '_, '_, V> {
3710    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
3711        self.window_context.read_model(handle)
3712    }
3713}
3714
3715impl<V: View> UpdateModel for ViewContext<'_, '_, '_, V> {
3716    fn update_model<T: Entity, O>(
3717        &mut self,
3718        handle: &ModelHandle<T>,
3719        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
3720    ) -> O {
3721        self.window_context.update_model(handle, update)
3722    }
3723}
3724
3725impl<V: View> ReadView for ViewContext<'_, '_, '_, V> {
3726    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
3727        self.window_context.read_view(handle)
3728    }
3729}
3730
3731impl<V: View> UpdateView for ViewContext<'_, '_, '_, V> {
3732    fn update_view<T, S>(
3733        &mut self,
3734        handle: &ViewHandle<T>,
3735        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
3736    ) -> S
3737    where
3738        T: View,
3739    {
3740        self.window_context.update_view(handle, update)
3741    }
3742}
3743
3744pub struct EventContext<'a, 'b, 'c, 'd, V: View> {
3745    view_context: &'d mut ViewContext<'a, 'b, 'c, V>,
3746    pub(crate) handled: bool,
3747}
3748
3749impl<'a, 'b, 'c, 'd, V: View> EventContext<'a, 'b, 'c, 'd, V> {
3750    pub(crate) fn new(view_context: &'d mut ViewContext<'a, 'b, 'c, V>) -> Self {
3751        EventContext {
3752            view_context,
3753            handled: true,
3754        }
3755    }
3756
3757    pub fn propagate_event(&mut self) {
3758        self.handled = false;
3759    }
3760}
3761
3762impl<'a, 'b, 'c, 'd, V: View> Deref for EventContext<'a, 'b, 'c, 'd, V> {
3763    type Target = ViewContext<'a, 'b, 'c, V>;
3764
3765    fn deref(&self) -> &Self::Target {
3766        &self.view_context
3767    }
3768}
3769
3770impl<V: View> DerefMut for EventContext<'_, '_, '_, '_, V> {
3771    fn deref_mut(&mut self) -> &mut Self::Target {
3772        &mut self.view_context
3773    }
3774}
3775
3776impl<V: View> UpdateModel for EventContext<'_, '_, '_, '_, V> {
3777    fn update_model<T: Entity, O>(
3778        &mut self,
3779        handle: &ModelHandle<T>,
3780        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
3781    ) -> O {
3782        self.view_context.update_model(handle, update)
3783    }
3784}
3785
3786impl<V: View> ReadView for EventContext<'_, '_, '_, '_, V> {
3787    fn read_view<W: View>(&self, handle: &crate::ViewHandle<W>) -> &W {
3788        self.view_context.read_view(handle)
3789    }
3790}
3791
3792impl<V: View> UpdateView for EventContext<'_, '_, '_, '_, V> {
3793    fn update_view<T, S>(
3794        &mut self,
3795        handle: &ViewHandle<T>,
3796        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
3797    ) -> S
3798    where
3799        T: View,
3800    {
3801        self.view_context.update_view(handle, update)
3802    }
3803}
3804
3805impl<V: View> UpgradeModelHandle for EventContext<'_, '_, '_, '_, V> {
3806    fn upgrade_model_handle<T: Entity>(
3807        &self,
3808        handle: &WeakModelHandle<T>,
3809    ) -> Option<ModelHandle<T>> {
3810        self.view_context.upgrade_model_handle(handle)
3811    }
3812
3813    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
3814        self.view_context.model_handle_is_upgradable(handle)
3815    }
3816
3817    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
3818        self.view_context.upgrade_any_model_handle(handle)
3819    }
3820}
3821
3822impl<V: View> UpgradeViewHandle for EventContext<'_, '_, '_, '_, V> {
3823    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
3824        self.view_context.upgrade_view_handle(handle)
3825    }
3826
3827    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
3828        self.view_context.upgrade_any_view_handle(handle)
3829    }
3830}
3831
3832pub(crate) enum Reference<'a, T> {
3833    Immutable(&'a T),
3834    Mutable(&'a mut T),
3835}
3836
3837impl<'a, T> Deref for Reference<'a, T> {
3838    type Target = T;
3839
3840    fn deref(&self) -> &Self::Target {
3841        match self {
3842            Reference::Immutable(target) => target,
3843            Reference::Mutable(target) => target,
3844        }
3845    }
3846}
3847
3848impl<'a, T> DerefMut for Reference<'a, T> {
3849    fn deref_mut(&mut self) -> &mut Self::Target {
3850        match self {
3851            Reference::Immutable(_) => {
3852                panic!("cannot mutably deref an immutable reference. this is a bug in GPUI.");
3853            }
3854            Reference::Mutable(target) => target,
3855        }
3856    }
3857}
3858
3859#[derive(Debug, Clone, Default)]
3860pub struct MouseState {
3861    pub(crate) hovered: bool,
3862    pub(crate) clicked: Option<MouseButton>,
3863    pub(crate) accessed_hovered: bool,
3864    pub(crate) accessed_clicked: bool,
3865}
3866
3867impl MouseState {
3868    pub fn hovered(&mut self) -> bool {
3869        self.accessed_hovered = true;
3870        self.hovered
3871    }
3872
3873    pub fn clicked(&mut self) -> Option<MouseButton> {
3874        self.accessed_clicked = true;
3875        self.clicked
3876    }
3877
3878    pub fn accessed_hovered(&self) -> bool {
3879        self.accessed_hovered
3880    }
3881
3882    pub fn accessed_clicked(&self) -> bool {
3883        self.accessed_clicked
3884    }
3885}
3886
3887pub trait Handle<T> {
3888    type Weak: 'static;
3889    fn id(&self) -> usize;
3890    fn location(&self) -> EntityLocation;
3891    fn downgrade(&self) -> Self::Weak;
3892    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3893    where
3894        Self: Sized;
3895}
3896
3897pub trait WeakHandle {
3898    fn id(&self) -> usize;
3899}
3900
3901#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
3902pub enum EntityLocation {
3903    Model(usize),
3904    View(usize, usize),
3905}
3906
3907pub struct ModelHandle<T: Entity> {
3908    any_handle: AnyModelHandle,
3909    model_type: PhantomData<T>,
3910}
3911
3912impl<T: Entity> Deref for ModelHandle<T> {
3913    type Target = AnyModelHandle;
3914
3915    fn deref(&self) -> &Self::Target {
3916        &self.any_handle
3917    }
3918}
3919
3920impl<T: Entity> ModelHandle<T> {
3921    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3922        Self {
3923            any_handle: AnyModelHandle::new(model_id, TypeId::of::<T>(), ref_counts.clone()),
3924            model_type: PhantomData,
3925        }
3926    }
3927
3928    pub fn downgrade(&self) -> WeakModelHandle<T> {
3929        WeakModelHandle::new(self.model_id)
3930    }
3931
3932    pub fn id(&self) -> usize {
3933        self.model_id
3934    }
3935
3936    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
3937        cx.read_model(self)
3938    }
3939
3940    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3941    where
3942        C: ReadModelWith,
3943        F: FnOnce(&T, &AppContext) -> S,
3944    {
3945        let mut read = Some(read);
3946        cx.read_model_with(self, &mut |model, cx| {
3947            let read = read.take().unwrap();
3948            read(model, cx)
3949        })
3950    }
3951
3952    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3953    where
3954        C: UpdateModel,
3955        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
3956    {
3957        let mut update = Some(update);
3958        cx.update_model(self, &mut |model, cx| {
3959            let update = update.take().unwrap();
3960            update(model, cx)
3961        })
3962    }
3963}
3964
3965impl<T: Entity> Clone for ModelHandle<T> {
3966    fn clone(&self) -> Self {
3967        Self::new(self.model_id, &self.ref_counts)
3968    }
3969}
3970
3971impl<T: Entity> PartialEq for ModelHandle<T> {
3972    fn eq(&self, other: &Self) -> bool {
3973        self.model_id == other.model_id
3974    }
3975}
3976
3977impl<T: Entity> Eq for ModelHandle<T> {}
3978
3979impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
3980    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
3981        self.model_id == other.model_id
3982    }
3983}
3984
3985impl<T: Entity> Hash for ModelHandle<T> {
3986    fn hash<H: Hasher>(&self, state: &mut H) {
3987        self.model_id.hash(state);
3988    }
3989}
3990
3991impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
3992    fn borrow(&self) -> &usize {
3993        &self.model_id
3994    }
3995}
3996
3997impl<T: Entity> Debug for ModelHandle<T> {
3998    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3999        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
4000            .field(&self.model_id)
4001            .finish()
4002    }
4003}
4004
4005unsafe impl<T: Entity> Send for ModelHandle<T> {}
4006unsafe impl<T: Entity> Sync for ModelHandle<T> {}
4007
4008impl<T: Entity> Handle<T> for ModelHandle<T> {
4009    type Weak = WeakModelHandle<T>;
4010
4011    fn id(&self) -> usize {
4012        self.model_id
4013    }
4014
4015    fn location(&self) -> EntityLocation {
4016        EntityLocation::Model(self.model_id)
4017    }
4018
4019    fn downgrade(&self) -> Self::Weak {
4020        self.downgrade()
4021    }
4022
4023    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4024    where
4025        Self: Sized,
4026    {
4027        weak.upgrade(cx)
4028    }
4029}
4030
4031pub struct WeakModelHandle<T> {
4032    any_handle: AnyWeakModelHandle,
4033    model_type: PhantomData<T>,
4034}
4035
4036impl<T> WeakModelHandle<T> {
4037    pub fn into_any(self) -> AnyWeakModelHandle {
4038        self.any_handle
4039    }
4040}
4041
4042impl<T> Deref for WeakModelHandle<T> {
4043    type Target = AnyWeakModelHandle;
4044
4045    fn deref(&self) -> &Self::Target {
4046        &self.any_handle
4047    }
4048}
4049
4050impl<T> WeakHandle for WeakModelHandle<T> {
4051    fn id(&self) -> usize {
4052        self.model_id
4053    }
4054}
4055
4056unsafe impl<T> Send for WeakModelHandle<T> {}
4057unsafe impl<T> Sync for WeakModelHandle<T> {}
4058
4059impl<T: Entity> WeakModelHandle<T> {
4060    fn new(model_id: usize) -> Self {
4061        Self {
4062            any_handle: AnyWeakModelHandle {
4063                model_id,
4064                model_type: TypeId::of::<T>(),
4065            },
4066            model_type: PhantomData,
4067        }
4068    }
4069
4070    pub fn id(&self) -> usize {
4071        self.model_id
4072    }
4073
4074    pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
4075        cx.model_handle_is_upgradable(self)
4076    }
4077
4078    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
4079        cx.upgrade_model_handle(self)
4080    }
4081}
4082
4083impl<T> Hash for WeakModelHandle<T> {
4084    fn hash<H: Hasher>(&self, state: &mut H) {
4085        self.model_id.hash(state)
4086    }
4087}
4088
4089impl<T> PartialEq for WeakModelHandle<T> {
4090    fn eq(&self, other: &Self) -> bool {
4091        self.model_id == other.model_id
4092    }
4093}
4094
4095impl<T> Eq for WeakModelHandle<T> {}
4096
4097impl<T: Entity> PartialEq<ModelHandle<T>> for WeakModelHandle<T> {
4098    fn eq(&self, other: &ModelHandle<T>) -> bool {
4099        self.model_id == other.model_id
4100    }
4101}
4102
4103impl<T> Clone for WeakModelHandle<T> {
4104    fn clone(&self) -> Self {
4105        Self {
4106            any_handle: self.any_handle.clone(),
4107            model_type: PhantomData,
4108        }
4109    }
4110}
4111
4112impl<T> Copy for WeakModelHandle<T> {}
4113
4114#[repr(transparent)]
4115pub struct ViewHandle<T> {
4116    any_handle: AnyViewHandle,
4117    view_type: PhantomData<T>,
4118}
4119
4120impl<T> Deref for ViewHandle<T> {
4121    type Target = AnyViewHandle;
4122
4123    fn deref(&self) -> &Self::Target {
4124        &self.any_handle
4125    }
4126}
4127
4128impl<T: View> ViewHandle<T> {
4129    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4130        Self {
4131            any_handle: AnyViewHandle::new(
4132                window_id,
4133                view_id,
4134                TypeId::of::<T>(),
4135                ref_counts.clone(),
4136            ),
4137            view_type: PhantomData,
4138        }
4139    }
4140
4141    pub fn downgrade(&self) -> WeakViewHandle<T> {
4142        WeakViewHandle::new(self.window_id, self.view_id)
4143    }
4144
4145    pub fn into_any(self) -> AnyViewHandle {
4146        self.any_handle
4147    }
4148
4149    pub fn window_id(&self) -> usize {
4150        self.window_id
4151    }
4152
4153    pub fn id(&self) -> usize {
4154        self.view_id
4155    }
4156
4157    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
4158        cx.read_view(self)
4159    }
4160
4161    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
4162    where
4163        C: ReadViewWith,
4164        F: FnOnce(&T, &AppContext) -> S,
4165    {
4166        let mut read = Some(read);
4167        cx.read_view_with(self, &mut |view, cx| {
4168            let read = read.take().unwrap();
4169            read(view, cx)
4170        })
4171    }
4172
4173    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
4174    where
4175        C: UpdateView,
4176        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
4177    {
4178        let mut update = Some(update);
4179        cx.update_view(self, &mut |view, cx| {
4180            let update = update.take().unwrap();
4181            update(view, cx)
4182        })
4183    }
4184
4185    pub fn defer<C, F>(&self, cx: &mut C, update: F)
4186    where
4187        C: AsMut<AppContext>,
4188        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
4189    {
4190        let this = self.clone();
4191        cx.as_mut().defer(move |cx| {
4192            this.update(cx, |view, cx| update(view, cx));
4193        });
4194    }
4195
4196    pub fn is_focused(&self, cx: &AppContext) -> bool {
4197        cx.focused_view_id(self.window_id)
4198            .map_or(false, |focused_id| focused_id == self.view_id)
4199    }
4200}
4201
4202impl<T: View> Clone for ViewHandle<T> {
4203    fn clone(&self) -> Self {
4204        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
4205    }
4206}
4207
4208impl<T> PartialEq for ViewHandle<T> {
4209    fn eq(&self, other: &Self) -> bool {
4210        self.window_id == other.window_id && self.view_id == other.view_id
4211    }
4212}
4213
4214impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
4215    fn eq(&self, other: &WeakViewHandle<T>) -> bool {
4216        self.window_id == other.window_id && self.view_id == other.view_id
4217    }
4218}
4219
4220impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
4221    fn eq(&self, other: &ViewHandle<T>) -> bool {
4222        self.window_id == other.window_id && self.view_id == other.view_id
4223    }
4224}
4225
4226impl<T> Eq for ViewHandle<T> {}
4227
4228impl<T> Hash for ViewHandle<T> {
4229    fn hash<H: Hasher>(&self, state: &mut H) {
4230        self.window_id.hash(state);
4231        self.view_id.hash(state);
4232    }
4233}
4234
4235impl<T> Debug for ViewHandle<T> {
4236    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4237        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
4238            .field("window_id", &self.window_id)
4239            .field("view_id", &self.view_id)
4240            .finish()
4241    }
4242}
4243
4244impl<T: View> Handle<T> for ViewHandle<T> {
4245    type Weak = WeakViewHandle<T>;
4246
4247    fn id(&self) -> usize {
4248        self.view_id
4249    }
4250
4251    fn location(&self) -> EntityLocation {
4252        EntityLocation::View(self.window_id, self.view_id)
4253    }
4254
4255    fn downgrade(&self) -> Self::Weak {
4256        self.downgrade()
4257    }
4258
4259    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4260    where
4261        Self: Sized,
4262    {
4263        weak.upgrade(cx)
4264    }
4265}
4266
4267pub struct AnyViewHandle {
4268    window_id: usize,
4269    view_id: usize,
4270    view_type: TypeId,
4271    ref_counts: Arc<Mutex<RefCounts>>,
4272
4273    #[cfg(any(test, feature = "test-support"))]
4274    handle_id: usize,
4275}
4276
4277impl AnyViewHandle {
4278    fn new(
4279        window_id: usize,
4280        view_id: usize,
4281        view_type: TypeId,
4282        ref_counts: Arc<Mutex<RefCounts>>,
4283    ) -> Self {
4284        ref_counts.lock().inc_view(window_id, view_id);
4285
4286        #[cfg(any(test, feature = "test-support"))]
4287        let handle_id = ref_counts
4288            .lock()
4289            .leak_detector
4290            .lock()
4291            .handle_created(None, view_id);
4292
4293        Self {
4294            window_id,
4295            view_id,
4296            view_type,
4297            ref_counts,
4298            #[cfg(any(test, feature = "test-support"))]
4299            handle_id,
4300        }
4301    }
4302
4303    pub fn window_id(&self) -> usize {
4304        self.window_id
4305    }
4306
4307    pub fn id(&self) -> usize {
4308        self.view_id
4309    }
4310
4311    pub fn is<T: 'static>(&self) -> bool {
4312        TypeId::of::<T>() == self.view_type
4313    }
4314
4315    pub fn is_focused(&self, cx: &AppContext) -> bool {
4316        cx.focused_view_id(self.window_id)
4317            .map_or(false, |focused_id| focused_id == self.view_id)
4318    }
4319
4320    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
4321        if self.is::<T>() {
4322            Some(ViewHandle {
4323                any_handle: self,
4324                view_type: PhantomData,
4325            })
4326        } else {
4327            None
4328        }
4329    }
4330
4331    pub fn downcast_ref<T: View>(&self) -> Option<&ViewHandle<T>> {
4332        if self.is::<T>() {
4333            Some(unsafe { mem::transmute(self) })
4334        } else {
4335            None
4336        }
4337    }
4338
4339    pub fn downgrade(&self) -> AnyWeakViewHandle {
4340        AnyWeakViewHandle {
4341            window_id: self.window_id,
4342            view_id: self.view_id,
4343            view_type: self.view_type,
4344        }
4345    }
4346
4347    pub fn view_type(&self) -> TypeId {
4348        self.view_type
4349    }
4350
4351    pub fn debug_json<'a, 'b>(&self, cx: &'b WindowContext<'a, 'b>) -> serde_json::Value {
4352        cx.views
4353            .get(&(self.window_id, self.view_id))
4354            .map_or_else(|| serde_json::Value::Null, |view| view.debug_json(cx))
4355    }
4356}
4357
4358impl Clone for AnyViewHandle {
4359    fn clone(&self) -> Self {
4360        Self::new(
4361            self.window_id,
4362            self.view_id,
4363            self.view_type,
4364            self.ref_counts.clone(),
4365        )
4366    }
4367}
4368
4369impl<T> PartialEq<ViewHandle<T>> for AnyViewHandle {
4370    fn eq(&self, other: &ViewHandle<T>) -> bool {
4371        self.window_id == other.window_id && self.view_id == other.view_id
4372    }
4373}
4374
4375impl Drop for AnyViewHandle {
4376    fn drop(&mut self) {
4377        self.ref_counts
4378            .lock()
4379            .dec_view(self.window_id, self.view_id);
4380        #[cfg(any(test, feature = "test-support"))]
4381        self.ref_counts
4382            .lock()
4383            .leak_detector
4384            .lock()
4385            .handle_dropped(self.view_id, self.handle_id);
4386    }
4387}
4388
4389pub struct AnyModelHandle {
4390    model_id: usize,
4391    model_type: TypeId,
4392    ref_counts: Arc<Mutex<RefCounts>>,
4393
4394    #[cfg(any(test, feature = "test-support"))]
4395    handle_id: usize,
4396}
4397
4398impl AnyModelHandle {
4399    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
4400        ref_counts.lock().inc_model(model_id);
4401
4402        #[cfg(any(test, feature = "test-support"))]
4403        let handle_id = ref_counts
4404            .lock()
4405            .leak_detector
4406            .lock()
4407            .handle_created(None, model_id);
4408
4409        Self {
4410            model_id,
4411            model_type,
4412            ref_counts,
4413
4414            #[cfg(any(test, feature = "test-support"))]
4415            handle_id,
4416        }
4417    }
4418
4419    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
4420        if self.is::<T>() {
4421            Some(ModelHandle {
4422                any_handle: self,
4423                model_type: PhantomData,
4424            })
4425        } else {
4426            None
4427        }
4428    }
4429
4430    pub fn downgrade(&self) -> AnyWeakModelHandle {
4431        AnyWeakModelHandle {
4432            model_id: self.model_id,
4433            model_type: self.model_type,
4434        }
4435    }
4436
4437    pub fn is<T: Entity>(&self) -> bool {
4438        self.model_type == TypeId::of::<T>()
4439    }
4440
4441    pub fn model_type(&self) -> TypeId {
4442        self.model_type
4443    }
4444}
4445
4446impl Clone for AnyModelHandle {
4447    fn clone(&self) -> Self {
4448        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
4449    }
4450}
4451
4452impl Drop for AnyModelHandle {
4453    fn drop(&mut self) {
4454        let mut ref_counts = self.ref_counts.lock();
4455        ref_counts.dec_model(self.model_id);
4456
4457        #[cfg(any(test, feature = "test-support"))]
4458        ref_counts
4459            .leak_detector
4460            .lock()
4461            .handle_dropped(self.model_id, self.handle_id);
4462    }
4463}
4464
4465#[derive(Hash, PartialEq, Eq, Debug, Clone, Copy)]
4466pub struct AnyWeakModelHandle {
4467    model_id: usize,
4468    model_type: TypeId,
4469}
4470
4471impl AnyWeakModelHandle {
4472    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
4473        cx.upgrade_any_model_handle(self)
4474    }
4475    pub fn model_type(&self) -> TypeId {
4476        self.model_type
4477    }
4478
4479    fn is<T: 'static>(&self) -> bool {
4480        TypeId::of::<T>() == self.model_type
4481    }
4482
4483    pub fn downcast<T: Entity>(self) -> Option<WeakModelHandle<T>> {
4484        if self.is::<T>() {
4485            let result = Some(WeakModelHandle {
4486                any_handle: self,
4487                model_type: PhantomData,
4488            });
4489
4490            result
4491        } else {
4492            None
4493        }
4494    }
4495}
4496
4497#[derive(Debug, Copy)]
4498pub struct WeakViewHandle<T> {
4499    any_handle: AnyWeakViewHandle,
4500    view_type: PhantomData<T>,
4501}
4502
4503impl<T> WeakHandle for WeakViewHandle<T> {
4504    fn id(&self) -> usize {
4505        self.view_id
4506    }
4507}
4508
4509impl<T: View> WeakViewHandle<T> {
4510    fn new(window_id: usize, view_id: usize) -> Self {
4511        Self {
4512            any_handle: AnyWeakViewHandle {
4513                window_id,
4514                view_id,
4515                view_type: TypeId::of::<T>(),
4516            },
4517            view_type: PhantomData,
4518        }
4519    }
4520
4521    pub fn id(&self) -> usize {
4522        self.view_id
4523    }
4524
4525    pub fn window_id(&self) -> usize {
4526        self.window_id
4527    }
4528
4529    pub fn into_any(self) -> AnyWeakViewHandle {
4530        self.any_handle
4531    }
4532
4533    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
4534        cx.upgrade_view_handle(self)
4535    }
4536}
4537
4538impl<T> Deref for WeakViewHandle<T> {
4539    type Target = AnyWeakViewHandle;
4540
4541    fn deref(&self) -> &Self::Target {
4542        &self.any_handle
4543    }
4544}
4545
4546impl<T> Clone for WeakViewHandle<T> {
4547    fn clone(&self) -> Self {
4548        Self {
4549            any_handle: self.any_handle.clone(),
4550            view_type: PhantomData,
4551        }
4552    }
4553}
4554
4555impl<T> PartialEq for WeakViewHandle<T> {
4556    fn eq(&self, other: &Self) -> bool {
4557        self.window_id == other.window_id && self.view_id == other.view_id
4558    }
4559}
4560
4561impl<T> Eq for WeakViewHandle<T> {}
4562
4563impl<T> Hash for WeakViewHandle<T> {
4564    fn hash<H: Hasher>(&self, state: &mut H) {
4565        self.any_handle.hash(state);
4566    }
4567}
4568
4569#[derive(Debug, Clone, Copy)]
4570pub struct AnyWeakViewHandle {
4571    window_id: usize,
4572    view_id: usize,
4573    view_type: TypeId,
4574}
4575
4576impl AnyWeakViewHandle {
4577    pub fn id(&self) -> usize {
4578        self.view_id
4579    }
4580
4581    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<AnyViewHandle> {
4582        cx.upgrade_any_view_handle(self)
4583    }
4584}
4585
4586impl Hash for AnyWeakViewHandle {
4587    fn hash<H: Hasher>(&self, state: &mut H) {
4588        self.window_id.hash(state);
4589        self.view_id.hash(state);
4590        self.view_type.hash(state);
4591    }
4592}
4593
4594#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4595pub struct ElementStateId {
4596    view_id: usize,
4597    element_id: usize,
4598    tag: TypeId,
4599}
4600
4601pub struct ElementStateHandle<T> {
4602    value_type: PhantomData<T>,
4603    id: ElementStateId,
4604    ref_counts: Weak<Mutex<RefCounts>>,
4605}
4606
4607impl<T: 'static> ElementStateHandle<T> {
4608    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4609        ref_counts.lock().inc_element_state(id, frame_id);
4610        Self {
4611            value_type: PhantomData,
4612            id,
4613            ref_counts: Arc::downgrade(ref_counts),
4614        }
4615    }
4616
4617    pub fn id(&self) -> ElementStateId {
4618        self.id
4619    }
4620
4621    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
4622        cx.element_states
4623            .get(&self.id)
4624            .unwrap()
4625            .downcast_ref()
4626            .unwrap()
4627    }
4628
4629    pub fn update<C, D, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
4630    where
4631        C: DerefMut<Target = D>,
4632        D: DerefMut<Target = AppContext>,
4633    {
4634        let mut element_state = cx.deref_mut().element_states.remove(&self.id).unwrap();
4635        let result = f(element_state.downcast_mut().unwrap(), cx);
4636        cx.deref_mut().element_states.insert(self.id, element_state);
4637        result
4638    }
4639}
4640
4641impl<T> Drop for ElementStateHandle<T> {
4642    fn drop(&mut self) {
4643        if let Some(ref_counts) = self.ref_counts.upgrade() {
4644            ref_counts.lock().dec_element_state(self.id);
4645        }
4646    }
4647}
4648
4649#[must_use]
4650pub enum Subscription {
4651    Subscription(callback_collection::Subscription<usize, SubscriptionCallback>),
4652    Observation(callback_collection::Subscription<usize, ObservationCallback>),
4653    GlobalSubscription(callback_collection::Subscription<TypeId, GlobalSubscriptionCallback>),
4654    GlobalObservation(callback_collection::Subscription<TypeId, GlobalObservationCallback>),
4655    FocusObservation(callback_collection::Subscription<usize, FocusObservationCallback>),
4656    WindowActivationObservation(callback_collection::Subscription<usize, WindowActivationCallback>),
4657    WindowFullscreenObservation(callback_collection::Subscription<usize, WindowFullscreenCallback>),
4658    WindowBoundsObservation(callback_collection::Subscription<usize, WindowBoundsCallback>),
4659    KeystrokeObservation(callback_collection::Subscription<usize, KeystrokeCallback>),
4660    ReleaseObservation(callback_collection::Subscription<usize, ReleaseObservationCallback>),
4661    ActionObservation(callback_collection::Subscription<(), ActionObservationCallback>),
4662    ActiveLabeledTasksObservation(
4663        callback_collection::Subscription<(), ActiveLabeledTasksCallback>,
4664    ),
4665}
4666
4667impl Subscription {
4668    pub fn id(&self) -> usize {
4669        match self {
4670            Subscription::Subscription(subscription) => subscription.id(),
4671            Subscription::Observation(subscription) => subscription.id(),
4672            Subscription::GlobalSubscription(subscription) => subscription.id(),
4673            Subscription::GlobalObservation(subscription) => subscription.id(),
4674            Subscription::FocusObservation(subscription) => subscription.id(),
4675            Subscription::WindowActivationObservation(subscription) => subscription.id(),
4676            Subscription::WindowFullscreenObservation(subscription) => subscription.id(),
4677            Subscription::WindowBoundsObservation(subscription) => subscription.id(),
4678            Subscription::KeystrokeObservation(subscription) => subscription.id(),
4679            Subscription::ReleaseObservation(subscription) => subscription.id(),
4680            Subscription::ActionObservation(subscription) => subscription.id(),
4681            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.id(),
4682        }
4683    }
4684
4685    pub fn detach(&mut self) {
4686        match self {
4687            Subscription::Subscription(subscription) => subscription.detach(),
4688            Subscription::GlobalSubscription(subscription) => subscription.detach(),
4689            Subscription::Observation(subscription) => subscription.detach(),
4690            Subscription::GlobalObservation(subscription) => subscription.detach(),
4691            Subscription::FocusObservation(subscription) => subscription.detach(),
4692            Subscription::KeystrokeObservation(subscription) => subscription.detach(),
4693            Subscription::WindowActivationObservation(subscription) => subscription.detach(),
4694            Subscription::WindowFullscreenObservation(subscription) => subscription.detach(),
4695            Subscription::WindowBoundsObservation(subscription) => subscription.detach(),
4696            Subscription::ReleaseObservation(subscription) => subscription.detach(),
4697            Subscription::ActionObservation(subscription) => subscription.detach(),
4698            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.detach(),
4699        }
4700    }
4701}
4702
4703#[cfg(test)]
4704mod tests {
4705    use super::*;
4706    use crate::{
4707        actions,
4708        elements::*,
4709        impl_actions,
4710        platform::{MouseButton, MouseButtonEvent},
4711        window::ChildView,
4712    };
4713    use itertools::Itertools;
4714    use postage::{sink::Sink, stream::Stream};
4715    use serde::Deserialize;
4716    use smol::future::poll_once;
4717    use std::{
4718        cell::Cell,
4719        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
4720    };
4721
4722    #[crate::test(self)]
4723    fn test_model_handles(cx: &mut AppContext) {
4724        struct Model {
4725            other: Option<ModelHandle<Model>>,
4726            events: Vec<String>,
4727        }
4728
4729        impl Entity for Model {
4730            type Event = usize;
4731        }
4732
4733        impl Model {
4734            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
4735                if let Some(other) = other.as_ref() {
4736                    cx.observe(other, |me, _, _| {
4737                        me.events.push("notified".into());
4738                    })
4739                    .detach();
4740                    cx.subscribe(other, |me, _, event, _| {
4741                        me.events.push(format!("observed event {}", event));
4742                    })
4743                    .detach();
4744                }
4745
4746                Self {
4747                    other,
4748                    events: Vec::new(),
4749                }
4750            }
4751        }
4752
4753        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
4754        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
4755        assert_eq!(cx.models.len(), 2);
4756
4757        handle_1.update(cx, |model, cx| {
4758            model.events.push("updated".into());
4759            cx.emit(1);
4760            cx.notify();
4761            cx.emit(2);
4762        });
4763        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4764        assert_eq!(
4765            handle_2.read(cx).events,
4766            vec![
4767                "observed event 1".to_string(),
4768                "notified".to_string(),
4769                "observed event 2".to_string(),
4770            ]
4771        );
4772
4773        handle_2.update(cx, |model, _| {
4774            drop(handle_1);
4775            model.other.take();
4776        });
4777
4778        assert_eq!(cx.models.len(), 1);
4779        assert!(cx.subscriptions.is_empty());
4780        assert!(cx.observations.is_empty());
4781    }
4782
4783    #[crate::test(self)]
4784    fn test_model_events(cx: &mut AppContext) {
4785        #[derive(Default)]
4786        struct Model {
4787            events: Vec<usize>,
4788        }
4789
4790        impl Entity for Model {
4791            type Event = usize;
4792        }
4793
4794        let handle_1 = cx.add_model(|_| Model::default());
4795        let handle_2 = cx.add_model(|_| Model::default());
4796
4797        handle_1.update(cx, |_, cx| {
4798            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
4799                model.events.push(*event);
4800
4801                cx.subscribe(&emitter, |model, _, event, _| {
4802                    model.events.push(*event * 2);
4803                })
4804                .detach();
4805            })
4806            .detach();
4807        });
4808
4809        handle_2.update(cx, |_, c| c.emit(7));
4810        assert_eq!(handle_1.read(cx).events, vec![7]);
4811
4812        handle_2.update(cx, |_, c| c.emit(5));
4813        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4814    }
4815
4816    #[crate::test(self)]
4817    fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
4818        #[derive(Default)]
4819        struct Model;
4820
4821        impl Entity for Model {
4822            type Event = ();
4823        }
4824
4825        let events = Rc::new(RefCell::new(Vec::new()));
4826        cx.add_model(|cx| {
4827            drop(cx.subscribe(&cx.handle(), {
4828                let events = events.clone();
4829                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
4830            }));
4831            cx.subscribe(&cx.handle(), {
4832                let events = events.clone();
4833                move |_, _, _, _| events.borrow_mut().push("before emit")
4834            })
4835            .detach();
4836            cx.emit(());
4837            cx.subscribe(&cx.handle(), {
4838                let events = events.clone();
4839                move |_, _, _, _| events.borrow_mut().push("after emit")
4840            })
4841            .detach();
4842            Model
4843        });
4844        assert_eq!(*events.borrow(), ["before emit"]);
4845    }
4846
4847    #[crate::test(self)]
4848    fn test_observe_and_notify_from_model(cx: &mut AppContext) {
4849        #[derive(Default)]
4850        struct Model {
4851            count: usize,
4852            events: Vec<usize>,
4853        }
4854
4855        impl Entity for Model {
4856            type Event = ();
4857        }
4858
4859        let handle_1 = cx.add_model(|_| Model::default());
4860        let handle_2 = cx.add_model(|_| Model::default());
4861
4862        handle_1.update(cx, |_, c| {
4863            c.observe(&handle_2, move |model, observed, c| {
4864                model.events.push(observed.read(c).count);
4865                c.observe(&observed, |model, observed, c| {
4866                    model.events.push(observed.read(c).count * 2);
4867                })
4868                .detach();
4869            })
4870            .detach();
4871        });
4872
4873        handle_2.update(cx, |model, c| {
4874            model.count = 7;
4875            c.notify()
4876        });
4877        assert_eq!(handle_1.read(cx).events, vec![7]);
4878
4879        handle_2.update(cx, |model, c| {
4880            model.count = 5;
4881            c.notify()
4882        });
4883        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
4884    }
4885
4886    #[crate::test(self)]
4887    fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
4888        #[derive(Default)]
4889        struct Model;
4890
4891        impl Entity for Model {
4892            type Event = ();
4893        }
4894
4895        let events = Rc::new(RefCell::new(Vec::new()));
4896        cx.add_model(|cx| {
4897            drop(cx.observe(&cx.handle(), {
4898                let events = events.clone();
4899                move |_, _, _| events.borrow_mut().push("dropped before flush")
4900            }));
4901            cx.observe(&cx.handle(), {
4902                let events = events.clone();
4903                move |_, _, _| events.borrow_mut().push("before notify")
4904            })
4905            .detach();
4906            cx.notify();
4907            cx.observe(&cx.handle(), {
4908                let events = events.clone();
4909                move |_, _, _| events.borrow_mut().push("after notify")
4910            })
4911            .detach();
4912            Model
4913        });
4914        assert_eq!(*events.borrow(), ["before notify"]);
4915    }
4916
4917    #[crate::test(self)]
4918    fn test_defer_and_after_window_update(cx: &mut AppContext) {
4919        struct View {
4920            render_count: usize,
4921        }
4922
4923        impl Entity for View {
4924            type Event = usize;
4925        }
4926
4927        impl super::View for View {
4928            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
4929                post_inc(&mut self.render_count);
4930                Empty::new().boxed()
4931            }
4932
4933            fn ui_name() -> &'static str {
4934                "View"
4935            }
4936        }
4937
4938        let (_, view) = cx.add_window(Default::default(), |_| View { render_count: 0 });
4939        let called_defer = Rc::new(AtomicBool::new(false));
4940        let called_after_window_update = Rc::new(AtomicBool::new(false));
4941
4942        view.update(cx, |this, cx| {
4943            assert_eq!(this.render_count, 1);
4944            cx.defer({
4945                let called_defer = called_defer.clone();
4946                move |this, _| {
4947                    assert_eq!(this.render_count, 1);
4948                    called_defer.store(true, SeqCst);
4949                }
4950            });
4951            cx.after_window_update({
4952                let called_after_window_update = called_after_window_update.clone();
4953                move |this, cx| {
4954                    assert_eq!(this.render_count, 2);
4955                    called_after_window_update.store(true, SeqCst);
4956                    cx.notify();
4957                }
4958            });
4959            assert!(!called_defer.load(SeqCst));
4960            assert!(!called_after_window_update.load(SeqCst));
4961            cx.notify();
4962        });
4963
4964        assert!(called_defer.load(SeqCst));
4965        assert!(called_after_window_update.load(SeqCst));
4966        assert_eq!(view.read(cx).render_count, 3);
4967    }
4968
4969    #[crate::test(self)]
4970    fn test_view_handles(cx: &mut AppContext) {
4971        struct View {
4972            other: Option<ViewHandle<View>>,
4973            events: Vec<String>,
4974        }
4975
4976        impl Entity for View {
4977            type Event = usize;
4978        }
4979
4980        impl super::View for View {
4981            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
4982                Empty::new().boxed()
4983            }
4984
4985            fn ui_name() -> &'static str {
4986                "View"
4987            }
4988        }
4989
4990        impl View {
4991            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
4992                if let Some(other) = other.as_ref() {
4993                    cx.subscribe(other, |me, _, event, _| {
4994                        me.events.push(format!("observed event {}", event));
4995                    })
4996                    .detach();
4997                }
4998                Self {
4999                    other,
5000                    events: Vec::new(),
5001                }
5002            }
5003        }
5004
5005        let (_, root_view) = cx.add_window(Default::default(), |cx| View::new(None, cx));
5006        let handle_1 = cx.add_view(&root_view, |cx| View::new(None, cx));
5007        let handle_2 = cx.add_view(&root_view, |cx| View::new(Some(handle_1.clone()), cx));
5008        assert_eq!(cx.views.len(), 3);
5009
5010        handle_1.update(cx, |view, cx| {
5011            view.events.push("updated".into());
5012            cx.emit(1);
5013            cx.emit(2);
5014        });
5015        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5016        assert_eq!(
5017            handle_2.read(cx).events,
5018            vec![
5019                "observed event 1".to_string(),
5020                "observed event 2".to_string(),
5021            ]
5022        );
5023
5024        handle_2.update(cx, |view, _| {
5025            drop(handle_1);
5026            view.other.take();
5027        });
5028
5029        assert_eq!(cx.views.len(), 2);
5030        assert!(cx.subscriptions.is_empty());
5031        assert!(cx.observations.is_empty());
5032    }
5033
5034    #[crate::test(self)]
5035    fn test_add_window(cx: &mut AppContext) {
5036        struct View {
5037            mouse_down_count: Arc<AtomicUsize>,
5038        }
5039
5040        impl Entity for View {
5041            type Event = ();
5042        }
5043
5044        impl super::View for View {
5045            fn render(&mut self, cx: &mut ViewContext<Self>) -> Element<Self> {
5046                enum Handler {}
5047                let mouse_down_count = self.mouse_down_count.clone();
5048                MouseEventHandler::<Handler, _>::new(0, cx, |_, _| Empty::new().boxed())
5049                    .on_down(MouseButton::Left, move |_, _, _| {
5050                        mouse_down_count.fetch_add(1, SeqCst);
5051                    })
5052                    .boxed()
5053            }
5054
5055            fn ui_name() -> &'static str {
5056                "View"
5057            }
5058        }
5059
5060        let mouse_down_count = Arc::new(AtomicUsize::new(0));
5061        let (window_id, _) = cx.add_window(Default::default(), |_| View {
5062            mouse_down_count: mouse_down_count.clone(),
5063        });
5064
5065        cx.update_window(window_id, |cx| {
5066            // Ensure window's root element is in a valid lifecycle state.
5067            cx.dispatch_event(
5068                Event::MouseDown(MouseButtonEvent {
5069                    position: Default::default(),
5070                    button: MouseButton::Left,
5071                    modifiers: Default::default(),
5072                    click_count: 1,
5073                }),
5074                false,
5075            );
5076            assert_eq!(mouse_down_count.load(SeqCst), 1);
5077        });
5078    }
5079
5080    #[crate::test(self)]
5081    fn test_entity_release_hooks(cx: &mut AppContext) {
5082        struct Model {
5083            released: Rc<Cell<bool>>,
5084        }
5085
5086        struct View {
5087            released: Rc<Cell<bool>>,
5088        }
5089
5090        impl Entity for Model {
5091            type Event = ();
5092
5093            fn release(&mut self, _: &mut AppContext) {
5094                self.released.set(true);
5095            }
5096        }
5097
5098        impl Entity for View {
5099            type Event = ();
5100
5101            fn release(&mut self, _: &mut AppContext) {
5102                self.released.set(true);
5103            }
5104        }
5105
5106        impl super::View for View {
5107            fn ui_name() -> &'static str {
5108                "View"
5109            }
5110
5111            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5112                Empty::new().boxed()
5113            }
5114        }
5115
5116        let model_released = Rc::new(Cell::new(false));
5117        let model_release_observed = Rc::new(Cell::new(false));
5118        let view_released = Rc::new(Cell::new(false));
5119        let view_release_observed = Rc::new(Cell::new(false));
5120
5121        let model = cx.add_model(|_| Model {
5122            released: model_released.clone(),
5123        });
5124        let (window_id, view) = cx.add_window(Default::default(), |_| View {
5125            released: view_released.clone(),
5126        });
5127        assert!(!model_released.get());
5128        assert!(!view_released.get());
5129
5130        cx.observe_release(&model, {
5131            let model_release_observed = model_release_observed.clone();
5132            move |_, _| model_release_observed.set(true)
5133        })
5134        .detach();
5135        cx.observe_release(&view, {
5136            let view_release_observed = view_release_observed.clone();
5137            move |_, _| view_release_observed.set(true)
5138        })
5139        .detach();
5140
5141        cx.update(move |_| {
5142            drop(model);
5143        });
5144        assert!(model_released.get());
5145        assert!(model_release_observed.get());
5146
5147        drop(view);
5148        cx.remove_window(window_id);
5149        assert!(view_released.get());
5150        assert!(view_release_observed.get());
5151    }
5152
5153    #[crate::test(self)]
5154    fn test_view_events(cx: &mut AppContext) {
5155        struct Model;
5156
5157        impl Entity for Model {
5158            type Event = String;
5159        }
5160
5161        let (_, handle_1) = cx.add_window(Default::default(), |_| TestView::default());
5162        let handle_2 = cx.add_view(&handle_1, |_| TestView::default());
5163        let handle_3 = cx.add_model(|_| Model);
5164
5165        handle_1.update(cx, |_, cx| {
5166            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
5167                me.events.push(event.clone());
5168
5169                cx.subscribe(&emitter, |me, _, event, _| {
5170                    me.events.push(format!("{event} from inner"));
5171                })
5172                .detach();
5173            })
5174            .detach();
5175
5176            cx.subscribe(&handle_3, |me, _, event, _| {
5177                me.events.push(event.clone());
5178            })
5179            .detach();
5180        });
5181
5182        handle_2.update(cx, |_, c| c.emit("7".into()));
5183        assert_eq!(handle_1.read(cx).events, vec!["7"]);
5184
5185        handle_2.update(cx, |_, c| c.emit("5".into()));
5186        assert_eq!(handle_1.read(cx).events, vec!["7", "5", "5 from inner"]);
5187
5188        handle_3.update(cx, |_, c| c.emit("9".into()));
5189        assert_eq!(
5190            handle_1.read(cx).events,
5191            vec!["7", "5", "5 from inner", "9"]
5192        );
5193    }
5194
5195    #[crate::test(self)]
5196    fn test_global_events(cx: &mut AppContext) {
5197        #[derive(Clone, Debug, Eq, PartialEq)]
5198        struct GlobalEvent(u64);
5199
5200        let events = Rc::new(RefCell::new(Vec::new()));
5201        let first_subscription;
5202        let second_subscription;
5203
5204        {
5205            let events = events.clone();
5206            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5207                events.borrow_mut().push(("First", e.clone()));
5208            });
5209        }
5210
5211        {
5212            let events = events.clone();
5213            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5214                events.borrow_mut().push(("Second", e.clone()));
5215            });
5216        }
5217
5218        cx.update(|cx| {
5219            cx.emit_global(GlobalEvent(1));
5220            cx.emit_global(GlobalEvent(2));
5221        });
5222
5223        drop(first_subscription);
5224
5225        cx.update(|cx| {
5226            cx.emit_global(GlobalEvent(3));
5227        });
5228
5229        drop(second_subscription);
5230
5231        cx.update(|cx| {
5232            cx.emit_global(GlobalEvent(4));
5233        });
5234
5235        assert_eq!(
5236            &*events.borrow(),
5237            &[
5238                ("First", GlobalEvent(1)),
5239                ("Second", GlobalEvent(1)),
5240                ("First", GlobalEvent(2)),
5241                ("Second", GlobalEvent(2)),
5242                ("Second", GlobalEvent(3)),
5243            ]
5244        );
5245    }
5246
5247    #[crate::test(self)]
5248    fn test_global_events_emitted_before_subscription_in_same_update_cycle(cx: &mut AppContext) {
5249        let events = Rc::new(RefCell::new(Vec::new()));
5250        cx.update(|cx| {
5251            {
5252                let events = events.clone();
5253                drop(cx.subscribe_global(move |_: &(), _| {
5254                    events.borrow_mut().push("dropped before emit");
5255                }));
5256            }
5257
5258            {
5259                let events = events.clone();
5260                cx.subscribe_global(move |_: &(), _| {
5261                    events.borrow_mut().push("before emit");
5262                })
5263                .detach();
5264            }
5265
5266            cx.emit_global(());
5267
5268            {
5269                let events = events.clone();
5270                cx.subscribe_global(move |_: &(), _| {
5271                    events.borrow_mut().push("after emit");
5272                })
5273                .detach();
5274            }
5275        });
5276
5277        assert_eq!(*events.borrow(), ["before emit"]);
5278    }
5279
5280    #[crate::test(self)]
5281    fn test_global_nested_events(cx: &mut AppContext) {
5282        #[derive(Clone, Debug, Eq, PartialEq)]
5283        struct GlobalEvent(u64);
5284
5285        let events = Rc::new(RefCell::new(Vec::new()));
5286
5287        {
5288            let events = events.clone();
5289            cx.subscribe_global(move |e: &GlobalEvent, cx| {
5290                events.borrow_mut().push(("Outer", e.clone()));
5291
5292                if e.0 == 1 {
5293                    let events = events.clone();
5294                    cx.subscribe_global(move |e: &GlobalEvent, _| {
5295                        events.borrow_mut().push(("Inner", e.clone()));
5296                    })
5297                    .detach();
5298                }
5299            })
5300            .detach();
5301        }
5302
5303        cx.update(|cx| {
5304            cx.emit_global(GlobalEvent(1));
5305            cx.emit_global(GlobalEvent(2));
5306            cx.emit_global(GlobalEvent(3));
5307        });
5308        cx.update(|cx| {
5309            cx.emit_global(GlobalEvent(4));
5310        });
5311
5312        assert_eq!(
5313            &*events.borrow(),
5314            &[
5315                ("Outer", GlobalEvent(1)),
5316                ("Outer", GlobalEvent(2)),
5317                ("Outer", GlobalEvent(3)),
5318                ("Outer", GlobalEvent(4)),
5319                ("Inner", GlobalEvent(4)),
5320            ]
5321        );
5322    }
5323
5324    #[crate::test(self)]
5325    fn test_global(cx: &mut AppContext) {
5326        type Global = usize;
5327
5328        let observation_count = Rc::new(RefCell::new(0));
5329        let subscription = cx.observe_global::<Global, _>({
5330            let observation_count = observation_count.clone();
5331            move |_| {
5332                *observation_count.borrow_mut() += 1;
5333            }
5334        });
5335
5336        assert!(!cx.has_global::<Global>());
5337        assert_eq!(cx.default_global::<Global>(), &0);
5338        assert_eq!(*observation_count.borrow(), 1);
5339        assert!(cx.has_global::<Global>());
5340        assert_eq!(
5341            cx.update_global::<Global, _, _>(|global, _| {
5342                *global = 1;
5343                "Update Result"
5344            }),
5345            "Update Result"
5346        );
5347        assert_eq!(*observation_count.borrow(), 2);
5348        assert_eq!(cx.global::<Global>(), &1);
5349
5350        drop(subscription);
5351        cx.update_global::<Global, _, _>(|global, _| {
5352            *global = 2;
5353        });
5354        assert_eq!(*observation_count.borrow(), 2);
5355
5356        type OtherGlobal = f32;
5357
5358        let observation_count = Rc::new(RefCell::new(0));
5359        cx.observe_global::<OtherGlobal, _>({
5360            let observation_count = observation_count.clone();
5361            move |_| {
5362                *observation_count.borrow_mut() += 1;
5363            }
5364        })
5365        .detach();
5366
5367        assert_eq!(
5368            cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
5369                assert_eq!(global, &0.0);
5370                *global = 2.0;
5371                "Default update result"
5372            }),
5373            "Default update result"
5374        );
5375        assert_eq!(cx.global::<OtherGlobal>(), &2.0);
5376        assert_eq!(*observation_count.borrow(), 1);
5377    }
5378
5379    #[crate::test(self)]
5380    fn test_dropping_subscribers(cx: &mut AppContext) {
5381        struct Model;
5382
5383        impl Entity for Model {
5384            type Event = ();
5385        }
5386
5387        let (_, root_view) = cx.add_window(Default::default(), |_| TestView::default());
5388        let observing_view = cx.add_view(&root_view, |_| TestView::default());
5389        let emitting_view = cx.add_view(&root_view, |_| TestView::default());
5390        let observing_model = cx.add_model(|_| Model);
5391        let observed_model = cx.add_model(|_| Model);
5392
5393        observing_view.update(cx, |_, cx| {
5394            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
5395            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5396        });
5397        observing_model.update(cx, |_, cx| {
5398            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5399        });
5400
5401        cx.update(|_| {
5402            drop(observing_view);
5403            drop(observing_model);
5404        });
5405
5406        emitting_view.update(cx, |_, cx| cx.emit(Default::default()));
5407        observed_model.update(cx, |_, cx| cx.emit(()));
5408    }
5409
5410    #[crate::test(self)]
5411    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
5412        let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
5413            drop(cx.subscribe(&cx.handle(), {
5414                move |this, _, _, _| this.events.push("dropped before flush".into())
5415            }));
5416            cx.subscribe(&cx.handle(), {
5417                move |this, _, _, _| this.events.push("before emit".into())
5418            })
5419            .detach();
5420            cx.emit("the event".into());
5421            cx.subscribe(&cx.handle(), {
5422                move |this, _, _, _| this.events.push("after emit".into())
5423            })
5424            .detach();
5425            TestView { events: Vec::new() }
5426        });
5427
5428        assert_eq!(view.read(cx).events, ["before emit"]);
5429    }
5430
5431    #[crate::test(self)]
5432    fn test_observe_and_notify_from_view(cx: &mut AppContext) {
5433        #[derive(Default)]
5434        struct Model {
5435            state: String,
5436        }
5437
5438        impl Entity for Model {
5439            type Event = ();
5440        }
5441
5442        let (_, view) = cx.add_window(Default::default(), |_| TestView::default());
5443        let model = cx.add_model(|_| Model {
5444            state: "old-state".into(),
5445        });
5446
5447        view.update(cx, |_, c| {
5448            c.observe(&model, |me, observed, cx| {
5449                me.events.push(observed.read(cx).state.clone())
5450            })
5451            .detach();
5452        });
5453
5454        model.update(cx, |model, cx| {
5455            model.state = "new-state".into();
5456            cx.notify();
5457        });
5458        assert_eq!(view.read(cx).events, vec!["new-state"]);
5459    }
5460
5461    #[crate::test(self)]
5462    fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
5463        let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
5464            drop(cx.observe(&cx.handle(), {
5465                move |this, _, _| this.events.push("dropped before flush".into())
5466            }));
5467            cx.observe(&cx.handle(), {
5468                move |this, _, _| this.events.push("before notify".into())
5469            })
5470            .detach();
5471            cx.notify();
5472            cx.observe(&cx.handle(), {
5473                move |this, _, _| this.events.push("after notify".into())
5474            })
5475            .detach();
5476            TestView { events: Vec::new() }
5477        });
5478
5479        assert_eq!(view.read(cx).events, ["before notify"]);
5480    }
5481
5482    #[crate::test(self)]
5483    fn test_notify_and_drop_observe_subscription_in_same_update_cycle(cx: &mut AppContext) {
5484        struct Model;
5485        impl Entity for Model {
5486            type Event = ();
5487        }
5488
5489        let model = cx.add_model(|_| Model);
5490        let (_, view) = cx.add_window(Default::default(), |_| TestView::default());
5491
5492        view.update(cx, |_, cx| {
5493            model.update(cx, |_, cx| cx.notify());
5494            drop(cx.observe(&model, move |this, _, _| {
5495                this.events.push("model notified".into());
5496            }));
5497            model.update(cx, |_, cx| cx.notify());
5498        });
5499
5500        for _ in 0..3 {
5501            model.update(cx, |_, cx| cx.notify());
5502        }
5503
5504        assert_eq!(view.read(cx).events, Vec::<String>::new());
5505    }
5506
5507    #[crate::test(self)]
5508    fn test_dropping_observers(cx: &mut AppContext) {
5509        struct Model;
5510
5511        impl Entity for Model {
5512            type Event = ();
5513        }
5514
5515        let (_, root_view) = cx.add_window(Default::default(), |_| TestView::default());
5516        let observing_view = cx.add_view(&root_view, |_| TestView::default());
5517        let observing_model = cx.add_model(|_| Model);
5518        let observed_model = cx.add_model(|_| Model);
5519
5520        observing_view.update(cx, |_, cx| {
5521            cx.observe(&observed_model, |_, _, _| {}).detach();
5522        });
5523        observing_model.update(cx, |_, cx| {
5524            cx.observe(&observed_model, |_, _, _| {}).detach();
5525        });
5526
5527        cx.update(|_| {
5528            drop(observing_view);
5529            drop(observing_model);
5530        });
5531
5532        observed_model.update(cx, |_, cx| cx.notify());
5533    }
5534
5535    #[crate::test(self)]
5536    fn test_dropping_subscriptions_during_callback(cx: &mut AppContext) {
5537        struct Model;
5538
5539        impl Entity for Model {
5540            type Event = u64;
5541        }
5542
5543        // Events
5544        let observing_model = cx.add_model(|_| Model);
5545        let observed_model = cx.add_model(|_| Model);
5546
5547        let events = Rc::new(RefCell::new(Vec::new()));
5548
5549        observing_model.update(cx, |_, cx| {
5550            let events = events.clone();
5551            let subscription = Rc::new(RefCell::new(None));
5552            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
5553                let subscription = subscription.clone();
5554                move |_, _, e, _| {
5555                    subscription.borrow_mut().take();
5556                    events.borrow_mut().push(*e);
5557                }
5558            }));
5559        });
5560
5561        observed_model.update(cx, |_, cx| {
5562            cx.emit(1);
5563            cx.emit(2);
5564        });
5565
5566        assert_eq!(*events.borrow(), [1]);
5567
5568        // Global Events
5569        #[derive(Clone, Debug, Eq, PartialEq)]
5570        struct GlobalEvent(u64);
5571
5572        let events = Rc::new(RefCell::new(Vec::new()));
5573
5574        {
5575            let events = events.clone();
5576            let subscription = Rc::new(RefCell::new(None));
5577            *subscription.borrow_mut() = Some(cx.subscribe_global({
5578                let subscription = subscription.clone();
5579                move |e: &GlobalEvent, _| {
5580                    subscription.borrow_mut().take();
5581                    events.borrow_mut().push(e.clone());
5582                }
5583            }));
5584        }
5585
5586        cx.update(|cx| {
5587            cx.emit_global(GlobalEvent(1));
5588            cx.emit_global(GlobalEvent(2));
5589        });
5590
5591        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
5592
5593        // Model Observation
5594        let observing_model = cx.add_model(|_| Model);
5595        let observed_model = cx.add_model(|_| Model);
5596
5597        let observation_count = Rc::new(RefCell::new(0));
5598
5599        observing_model.update(cx, |_, cx| {
5600            let observation_count = observation_count.clone();
5601            let subscription = Rc::new(RefCell::new(None));
5602            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
5603                let subscription = subscription.clone();
5604                move |_, _, _| {
5605                    subscription.borrow_mut().take();
5606                    *observation_count.borrow_mut() += 1;
5607                }
5608            }));
5609        });
5610
5611        observed_model.update(cx, |_, cx| {
5612            cx.notify();
5613        });
5614
5615        observed_model.update(cx, |_, cx| {
5616            cx.notify();
5617        });
5618
5619        assert_eq!(*observation_count.borrow(), 1);
5620
5621        // View Observation
5622        struct View;
5623
5624        impl Entity for View {
5625            type Event = ();
5626        }
5627
5628        impl super::View for View {
5629            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5630                Empty::new().boxed()
5631            }
5632
5633            fn ui_name() -> &'static str {
5634                "View"
5635            }
5636        }
5637
5638        let (_, root_view) = cx.add_window(Default::default(), |_| View);
5639        let observing_view = cx.add_view(&root_view, |_| View);
5640        let observed_view = cx.add_view(&root_view, |_| View);
5641
5642        let observation_count = Rc::new(RefCell::new(0));
5643        observing_view.update(cx, |_, cx| {
5644            let observation_count = observation_count.clone();
5645            let subscription = Rc::new(RefCell::new(None));
5646            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
5647                let subscription = subscription.clone();
5648                move |_, _, _| {
5649                    subscription.borrow_mut().take();
5650                    *observation_count.borrow_mut() += 1;
5651                }
5652            }));
5653        });
5654
5655        observed_view.update(cx, |_, cx| {
5656            cx.notify();
5657        });
5658
5659        observed_view.update(cx, |_, cx| {
5660            cx.notify();
5661        });
5662
5663        assert_eq!(*observation_count.borrow(), 1);
5664
5665        // Global Observation
5666        let observation_count = Rc::new(RefCell::new(0));
5667        let subscription = Rc::new(RefCell::new(None));
5668        *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
5669            let observation_count = observation_count.clone();
5670            let subscription = subscription.clone();
5671            move |_| {
5672                subscription.borrow_mut().take();
5673                *observation_count.borrow_mut() += 1;
5674            }
5675        }));
5676
5677        cx.default_global::<()>();
5678        cx.set_global(());
5679        assert_eq!(*observation_count.borrow(), 1);
5680    }
5681
5682    #[crate::test(self)]
5683    fn test_focus(cx: &mut AppContext) {
5684        struct View {
5685            name: String,
5686            events: Arc<Mutex<Vec<String>>>,
5687        }
5688
5689        impl Entity for View {
5690            type Event = ();
5691        }
5692
5693        impl super::View for View {
5694            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5695                Empty::new().boxed()
5696            }
5697
5698            fn ui_name() -> &'static str {
5699                "View"
5700            }
5701
5702            fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
5703                if cx.handle().id() == focused.id() {
5704                    self.events.lock().push(format!("{} focused", &self.name));
5705                }
5706            }
5707
5708            fn focus_out(&mut self, blurred: AnyViewHandle, cx: &mut ViewContext<Self>) {
5709                if cx.handle().id() == blurred.id() {
5710                    self.events.lock().push(format!("{} blurred", &self.name));
5711                }
5712            }
5713        }
5714
5715        let view_events: Arc<Mutex<Vec<String>>> = Default::default();
5716        let (_, view_1) = cx.add_window(Default::default(), |_| View {
5717            events: view_events.clone(),
5718            name: "view 1".to_string(),
5719        });
5720        let view_2 = cx.add_view(&view_1, |_| View {
5721            events: view_events.clone(),
5722            name: "view 2".to_string(),
5723        });
5724
5725        let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
5726        view_1.update(cx, |_, cx| {
5727            cx.observe_focus(&view_2, {
5728                let observed_events = observed_events.clone();
5729                move |this, view, focused, cx| {
5730                    let label = if focused { "focus" } else { "blur" };
5731                    observed_events.lock().push(format!(
5732                        "{} observed {}'s {}",
5733                        this.name,
5734                        view.read(cx).name,
5735                        label
5736                    ))
5737                }
5738            })
5739            .detach();
5740        });
5741        view_2.update(cx, |_, cx| {
5742            cx.observe_focus(&view_1, {
5743                let observed_events = observed_events.clone();
5744                move |this, view, focused, cx| {
5745                    let label = if focused { "focus" } else { "blur" };
5746                    observed_events.lock().push(format!(
5747                        "{} observed {}'s {}",
5748                        this.name,
5749                        view.read(cx).name,
5750                        label
5751                    ))
5752                }
5753            })
5754            .detach();
5755        });
5756        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
5757        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
5758
5759        view_1.update(cx, |_, cx| {
5760            // Ensure focus events are sent for all intermediate focuses
5761            cx.focus(&view_2);
5762            cx.focus(&view_1);
5763            cx.focus(&view_2);
5764        });
5765
5766        assert!(cx.is_child_focused(&view_1));
5767        assert!(!cx.is_child_focused(&view_2));
5768        assert_eq!(
5769            mem::take(&mut *view_events.lock()),
5770            [
5771                "view 1 blurred",
5772                "view 2 focused",
5773                "view 2 blurred",
5774                "view 1 focused",
5775                "view 1 blurred",
5776                "view 2 focused"
5777            ],
5778        );
5779        assert_eq!(
5780            mem::take(&mut *observed_events.lock()),
5781            [
5782                "view 2 observed view 1's blur",
5783                "view 1 observed view 2's focus",
5784                "view 1 observed view 2's blur",
5785                "view 2 observed view 1's focus",
5786                "view 2 observed view 1's blur",
5787                "view 1 observed view 2's focus"
5788            ]
5789        );
5790
5791        view_1.update(cx, |_, cx| cx.focus(&view_1));
5792        assert!(!cx.is_child_focused(&view_1));
5793        assert!(!cx.is_child_focused(&view_2));
5794        assert_eq!(
5795            mem::take(&mut *view_events.lock()),
5796            ["view 2 blurred", "view 1 focused"],
5797        );
5798        assert_eq!(
5799            mem::take(&mut *observed_events.lock()),
5800            [
5801                "view 1 observed view 2's blur",
5802                "view 2 observed view 1's focus"
5803            ]
5804        );
5805
5806        view_1.update(cx, |_, cx| cx.focus(&view_2));
5807        assert_eq!(
5808            mem::take(&mut *view_events.lock()),
5809            ["view 1 blurred", "view 2 focused"],
5810        );
5811        assert_eq!(
5812            mem::take(&mut *observed_events.lock()),
5813            [
5814                "view 2 observed view 1's blur",
5815                "view 1 observed view 2's focus"
5816            ]
5817        );
5818
5819        view_1.update(cx, |_, _| drop(view_2));
5820        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
5821        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
5822    }
5823
5824    #[crate::test(self)]
5825    fn test_deserialize_actions(cx: &mut AppContext) {
5826        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
5827        pub struct ComplexAction {
5828            arg: String,
5829            count: usize,
5830        }
5831
5832        actions!(test::something, [SimpleAction]);
5833        impl_actions!(test::something, [ComplexAction]);
5834
5835        cx.add_global_action(move |_: &SimpleAction, _: &mut AppContext| {});
5836        cx.add_global_action(move |_: &ComplexAction, _: &mut AppContext| {});
5837
5838        let action1 = cx
5839            .deserialize_action(
5840                "test::something::ComplexAction",
5841                Some(r#"{"arg": "a", "count": 5}"#),
5842            )
5843            .unwrap();
5844        let action2 = cx
5845            .deserialize_action("test::something::SimpleAction", None)
5846            .unwrap();
5847        assert_eq!(
5848            action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
5849            &ComplexAction {
5850                arg: "a".to_string(),
5851                count: 5,
5852            }
5853        );
5854        assert_eq!(
5855            action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
5856            &SimpleAction
5857        );
5858    }
5859
5860    #[crate::test(self)]
5861    fn test_dispatch_action(cx: &mut AppContext) {
5862        struct ViewA {
5863            id: usize,
5864        }
5865
5866        impl Entity for ViewA {
5867            type Event = ();
5868        }
5869
5870        impl View for ViewA {
5871            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5872                Empty::new().boxed()
5873            }
5874
5875            fn ui_name() -> &'static str {
5876                "View"
5877            }
5878        }
5879
5880        struct ViewB {
5881            id: usize,
5882        }
5883
5884        impl Entity for ViewB {
5885            type Event = ();
5886        }
5887
5888        impl View for ViewB {
5889            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5890                Empty::new().boxed()
5891            }
5892
5893            fn ui_name() -> &'static str {
5894                "View"
5895            }
5896        }
5897
5898        #[derive(Clone, Default, Deserialize, PartialEq)]
5899        pub struct Action(pub String);
5900
5901        impl_actions!(test, [Action]);
5902
5903        let actions = Rc::new(RefCell::new(Vec::new()));
5904
5905        cx.add_global_action({
5906            let actions = actions.clone();
5907            move |_: &Action, _: &mut AppContext| {
5908                actions.borrow_mut().push("global".to_string());
5909            }
5910        });
5911
5912        cx.add_action({
5913            let actions = actions.clone();
5914            move |view: &mut ViewA, action: &Action, cx| {
5915                assert_eq!(action.0, "bar");
5916                cx.propagate_action();
5917                actions.borrow_mut().push(format!("{} a", view.id));
5918            }
5919        });
5920
5921        cx.add_action({
5922            let actions = actions.clone();
5923            move |view: &mut ViewA, _: &Action, cx| {
5924                if view.id != 1 {
5925                    cx.add_view(|cx| {
5926                        cx.propagate_action(); // Still works on a nested ViewContext
5927                        ViewB { id: 5 }
5928                    });
5929                }
5930                actions.borrow_mut().push(format!("{} b", view.id));
5931            }
5932        });
5933
5934        cx.add_action({
5935            let actions = actions.clone();
5936            move |view: &mut ViewB, _: &Action, cx| {
5937                cx.propagate_action();
5938                actions.borrow_mut().push(format!("{} c", view.id));
5939            }
5940        });
5941
5942        cx.add_action({
5943            let actions = actions.clone();
5944            move |view: &mut ViewB, _: &Action, cx| {
5945                cx.propagate_action();
5946                actions.borrow_mut().push(format!("{} d", view.id));
5947            }
5948        });
5949
5950        cx.capture_action({
5951            let actions = actions.clone();
5952            move |view: &mut ViewA, _: &Action, cx| {
5953                cx.propagate_action();
5954                actions.borrow_mut().push(format!("{} capture", view.id));
5955            }
5956        });
5957
5958        let observed_actions = Rc::new(RefCell::new(Vec::new()));
5959        cx.observe_actions({
5960            let observed_actions = observed_actions.clone();
5961            move |action_id, _| observed_actions.borrow_mut().push(action_id)
5962        })
5963        .detach();
5964
5965        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
5966        let view_2 = cx.add_view(&view_1, |_| ViewB { id: 2 });
5967        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
5968        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
5969
5970        cx.handle_dispatch_action_from_effect(
5971            window_id,
5972            Some(view_4.id()),
5973            &Action("bar".to_string()),
5974        );
5975
5976        assert_eq!(
5977            *actions.borrow(),
5978            vec![
5979                "1 capture",
5980                "3 capture",
5981                "4 d",
5982                "4 c",
5983                "3 b",
5984                "3 a",
5985                "2 d",
5986                "2 c",
5987                "1 b"
5988            ]
5989        );
5990        assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
5991
5992        // Remove view_1, which doesn't propagate the action
5993
5994        let (window_id, view_2) = cx.add_window(Default::default(), |_| ViewB { id: 2 });
5995        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
5996        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
5997
5998        actions.borrow_mut().clear();
5999        cx.handle_dispatch_action_from_effect(
6000            window_id,
6001            Some(view_4.id()),
6002            &Action("bar".to_string()),
6003        );
6004
6005        assert_eq!(
6006            *actions.borrow(),
6007            vec![
6008                "3 capture",
6009                "4 d",
6010                "4 c",
6011                "3 b",
6012                "3 a",
6013                "2 d",
6014                "2 c",
6015                "global"
6016            ]
6017        );
6018        assert_eq!(
6019            *observed_actions.borrow(),
6020            [Action::default().id(), Action::default().id()]
6021        );
6022    }
6023
6024    #[crate::test(self)]
6025    fn test_dispatch_keystroke(cx: &mut AppContext) {
6026        #[derive(Clone, Deserialize, PartialEq)]
6027        pub struct Action(String);
6028
6029        impl_actions!(test, [Action]);
6030
6031        struct View {
6032            id: usize,
6033            keymap_context: KeymapContext,
6034        }
6035
6036        impl Entity for View {
6037            type Event = ();
6038        }
6039
6040        impl super::View for View {
6041            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6042                Empty::new().boxed()
6043            }
6044
6045            fn ui_name() -> &'static str {
6046                "View"
6047            }
6048
6049            fn keymap_context(&self, _: &AppContext) -> KeymapContext {
6050                self.keymap_context.clone()
6051            }
6052        }
6053
6054        impl View {
6055            fn new(id: usize) -> Self {
6056                View {
6057                    id,
6058                    keymap_context: KeymapContext::default(),
6059                }
6060            }
6061        }
6062
6063        let mut view_1 = View::new(1);
6064        let mut view_2 = View::new(2);
6065        let mut view_3 = View::new(3);
6066        view_1.keymap_context.add_identifier("a");
6067        view_2.keymap_context.add_identifier("a");
6068        view_2.keymap_context.add_identifier("b");
6069        view_3.keymap_context.add_identifier("a");
6070        view_3.keymap_context.add_identifier("b");
6071        view_3.keymap_context.add_identifier("c");
6072
6073        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
6074        let view_2 = cx.add_view(&view_1, |_| view_2);
6075        let _view_3 = cx.add_view(&view_2, |cx| {
6076            cx.focus_self();
6077            view_3
6078        });
6079
6080        // This binding only dispatches an action on view 2 because that view will have
6081        // "a" and "b" in its context, but not "c".
6082        cx.add_bindings(vec![Binding::new(
6083            "a",
6084            Action("a".to_string()),
6085            Some("a && b && !c"),
6086        )]);
6087
6088        cx.add_bindings(vec![Binding::new("b", Action("b".to_string()), None)]);
6089
6090        // This binding only dispatches an action on views 2 and 3, because they have
6091        // a parent view with a in its context
6092        cx.add_bindings(vec![Binding::new(
6093            "c",
6094            Action("c".to_string()),
6095            Some("b > c"),
6096        )]);
6097
6098        // This binding only dispatches an action on view 2, because they have
6099        // a parent view with a in its context
6100        cx.add_bindings(vec![Binding::new(
6101            "d",
6102            Action("d".to_string()),
6103            Some("a && !b > b"),
6104        )]);
6105
6106        let actions = Rc::new(RefCell::new(Vec::new()));
6107        cx.add_action({
6108            let actions = actions.clone();
6109            move |view: &mut View, action: &Action, cx| {
6110                actions
6111                    .borrow_mut()
6112                    .push(format!("{} {}", view.id, action.0));
6113
6114                if action.0 == "b" {
6115                    cx.propagate_action();
6116                }
6117            }
6118        });
6119
6120        cx.add_global_action({
6121            let actions = actions.clone();
6122            move |action: &Action, _| {
6123                actions.borrow_mut().push(format!("global {}", action.0));
6124            }
6125        });
6126
6127        cx.update_window(window_id, |cx| {
6128            cx.dispatch_keystroke(&Keystroke::parse("a").unwrap())
6129        });
6130        assert_eq!(&*actions.borrow(), &["2 a"]);
6131        actions.borrow_mut().clear();
6132
6133        cx.update_window(window_id, |cx| {
6134            cx.dispatch_keystroke(&Keystroke::parse("b").unwrap());
6135        });
6136
6137        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
6138        actions.borrow_mut().clear();
6139
6140        cx.update_window(window_id, |cx| {
6141            cx.dispatch_keystroke(&Keystroke::parse("c").unwrap());
6142        });
6143        assert_eq!(&*actions.borrow(), &["3 c"]);
6144        actions.borrow_mut().clear();
6145
6146        cx.update_window(window_id, |cx| {
6147            cx.dispatch_keystroke(&Keystroke::parse("d").unwrap());
6148        });
6149        assert_eq!(&*actions.borrow(), &["2 d"]);
6150        actions.borrow_mut().clear();
6151    }
6152
6153    #[crate::test(self)]
6154    fn test_keystrokes_for_action(cx: &mut AppContext) {
6155        actions!(test, [Action1, Action2, GlobalAction]);
6156
6157        struct View1 {}
6158        struct View2 {}
6159
6160        impl Entity for View1 {
6161            type Event = ();
6162        }
6163        impl Entity for View2 {
6164            type Event = ();
6165        }
6166
6167        impl super::View for View1 {
6168            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6169                Empty::new().boxed()
6170            }
6171            fn ui_name() -> &'static str {
6172                "View1"
6173            }
6174        }
6175        impl super::View for View2 {
6176            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6177                Empty::new().boxed()
6178            }
6179            fn ui_name() -> &'static str {
6180                "View2"
6181            }
6182        }
6183
6184        let (window_id, view_1) = cx.add_window(Default::default(), |_| View1 {});
6185        let view_2 = cx.add_view(&view_1, |cx| {
6186            cx.focus_self();
6187            View2 {}
6188        });
6189
6190        cx.add_action(|_: &mut View1, _: &Action1, _cx| {});
6191        cx.add_action(|_: &mut View2, _: &Action2, _cx| {});
6192        cx.add_global_action(|_: &GlobalAction, _| {});
6193
6194        cx.add_bindings(vec![
6195            Binding::new("a", Action1, Some("View1")),
6196            Binding::new("b", Action2, Some("View1 > View2")),
6197            Binding::new("c", GlobalAction, Some("View3")), // View 3 does not exist
6198        ]);
6199
6200        // Sanity check
6201        assert_eq!(
6202            cx.keystrokes_for_action(window_id, view_1.id(), &Action1)
6203                .unwrap()
6204                .as_slice(),
6205            &[Keystroke::parse("a").unwrap()]
6206        );
6207        assert_eq!(
6208            cx.keystrokes_for_action(window_id, view_2.id(), &Action2)
6209                .unwrap()
6210                .as_slice(),
6211            &[Keystroke::parse("b").unwrap()]
6212        );
6213
6214        // The 'a' keystroke propagates up the view tree from view_2
6215        // to view_1. The action, Action1, is handled by view_1.
6216        assert_eq!(
6217            cx.keystrokes_for_action(window_id, view_2.id(), &Action1)
6218                .unwrap()
6219                .as_slice(),
6220            &[Keystroke::parse("a").unwrap()]
6221        );
6222
6223        // Actions that are handled below the current view don't have bindings
6224        assert_eq!(
6225            cx.keystrokes_for_action(window_id, view_1.id(), &Action2),
6226            None
6227        );
6228
6229        // Actions that are handled in other branches of the tree should not have a binding
6230        assert_eq!(
6231            cx.keystrokes_for_action(window_id, view_2.id(), &GlobalAction),
6232            None
6233        );
6234
6235        // Produces a list of actions and key bindings
6236        fn available_actions(
6237            window_id: usize,
6238            view_id: usize,
6239            cx: &mut AppContext,
6240        ) -> Vec<(&'static str, Vec<Keystroke>)> {
6241            cx.available_actions(window_id, view_id)
6242                .map(|(action_name, _, bindings)| {
6243                    (
6244                        action_name,
6245                        bindings
6246                            .iter()
6247                            .map(|binding| binding.keystrokes()[0].clone())
6248                            .collect::<Vec<_>>(),
6249                    )
6250                })
6251                .sorted_by(|(name1, _), (name2, _)| name1.cmp(name2))
6252                .collect()
6253        }
6254
6255        // Check that global actions do not have a binding, even if a binding does exist in another view
6256        assert_eq!(
6257            &available_actions(window_id, view_1.id(), cx),
6258            &[
6259                ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
6260                ("test::GlobalAction", vec![])
6261            ],
6262        );
6263
6264        // Check that view 1 actions and bindings are available even when called from view 2
6265        assert_eq!(
6266            &available_actions(window_id, view_2.id(), cx),
6267            &[
6268                ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
6269                ("test::Action2", vec![Keystroke::parse("b").unwrap()]),
6270                ("test::GlobalAction", vec![]),
6271            ],
6272        );
6273    }
6274
6275    #[crate::test(self)]
6276    async fn test_model_condition(cx: &mut TestAppContext) {
6277        struct Counter(usize);
6278
6279        impl super::Entity for Counter {
6280            type Event = ();
6281        }
6282
6283        impl Counter {
6284            fn inc(&mut self, cx: &mut ModelContext<Self>) {
6285                self.0 += 1;
6286                cx.notify();
6287            }
6288        }
6289
6290        let model = cx.add_model(|_| Counter(0));
6291
6292        let condition1 = model.condition(cx, |model, _| model.0 == 2);
6293        let condition2 = model.condition(cx, |model, _| model.0 == 3);
6294        smol::pin!(condition1, condition2);
6295
6296        model.update(cx, |model, cx| model.inc(cx));
6297        assert_eq!(poll_once(&mut condition1).await, None);
6298        assert_eq!(poll_once(&mut condition2).await, None);
6299
6300        model.update(cx, |model, cx| model.inc(cx));
6301        assert_eq!(poll_once(&mut condition1).await, Some(()));
6302        assert_eq!(poll_once(&mut condition2).await, None);
6303
6304        model.update(cx, |model, cx| model.inc(cx));
6305        assert_eq!(poll_once(&mut condition2).await, Some(()));
6306
6307        model.update(cx, |_, cx| cx.notify());
6308    }
6309
6310    #[crate::test(self)]
6311    #[should_panic]
6312    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
6313        struct Model;
6314
6315        impl super::Entity for Model {
6316            type Event = ();
6317        }
6318
6319        let model = cx.add_model(|_| Model);
6320        model.condition(cx, |_, _| false).await;
6321    }
6322
6323    #[crate::test(self)]
6324    #[should_panic(expected = "model dropped with pending condition")]
6325    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
6326        struct Model;
6327
6328        impl super::Entity for Model {
6329            type Event = ();
6330        }
6331
6332        let model = cx.add_model(|_| Model);
6333        let condition = model.condition(cx, |_, _| false);
6334        cx.update(|_| drop(model));
6335        condition.await;
6336    }
6337
6338    #[crate::test(self)]
6339    async fn test_view_condition(cx: &mut TestAppContext) {
6340        struct Counter(usize);
6341
6342        impl super::Entity for Counter {
6343            type Event = ();
6344        }
6345
6346        impl super::View for Counter {
6347            fn ui_name() -> &'static str {
6348                "test view"
6349            }
6350
6351            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6352                Empty::new().boxed()
6353            }
6354        }
6355
6356        impl Counter {
6357            fn inc(&mut self, cx: &mut ViewContext<Self>) {
6358                self.0 += 1;
6359                cx.notify();
6360            }
6361        }
6362
6363        let (_, view) = cx.add_window(|_| Counter(0));
6364
6365        let condition1 = view.condition(cx, |view, _| view.0 == 2);
6366        let condition2 = view.condition(cx, |view, _| view.0 == 3);
6367        smol::pin!(condition1, condition2);
6368
6369        view.update(cx, |view, cx| view.inc(cx));
6370        assert_eq!(poll_once(&mut condition1).await, None);
6371        assert_eq!(poll_once(&mut condition2).await, None);
6372
6373        view.update(cx, |view, cx| view.inc(cx));
6374        assert_eq!(poll_once(&mut condition1).await, Some(()));
6375        assert_eq!(poll_once(&mut condition2).await, None);
6376
6377        view.update(cx, |view, cx| view.inc(cx));
6378        assert_eq!(poll_once(&mut condition2).await, Some(()));
6379        view.update(cx, |_, cx| cx.notify());
6380    }
6381
6382    #[crate::test(self)]
6383    #[should_panic]
6384    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
6385        let (_, view) = cx.add_window(|_| TestView::default());
6386        view.condition(cx, |_, _| false).await;
6387    }
6388
6389    #[crate::test(self)]
6390    #[should_panic(expected = "view dropped with pending condition")]
6391    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
6392        let (_, root_view) = cx.add_window(|_| TestView::default());
6393        let view = cx.add_view(&root_view, |_| TestView::default());
6394
6395        let condition = view.condition(cx, |_, _| false);
6396        cx.update(|_| drop(view));
6397        condition.await;
6398    }
6399
6400    #[crate::test(self)]
6401    fn test_refresh_windows(cx: &mut AppContext) {
6402        struct View(usize);
6403
6404        impl super::Entity for View {
6405            type Event = ();
6406        }
6407
6408        impl super::View for View {
6409            fn ui_name() -> &'static str {
6410                "test view"
6411            }
6412
6413            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6414                Empty::new().named(format!("render count: {}", post_inc(&mut self.0)))
6415            }
6416        }
6417
6418        let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
6419        cx.update_window(window_id, |cx| {
6420            assert_eq!(
6421                cx.window.rendered_views[&root_view.id()].name(),
6422                Some("render count: 0")
6423            );
6424        });
6425
6426        let view = cx.add_view(&root_view, |cx| {
6427            cx.refresh_windows();
6428            View(0)
6429        });
6430
6431        cx.update_window(window_id, |cx| {
6432            assert_eq!(
6433                cx.window.rendered_views[&root_view.id()].name(),
6434                Some("render count: 1")
6435            );
6436            assert_eq!(
6437                cx.window.rendered_views[&view.id()].name(),
6438                Some("render count: 0")
6439            );
6440        });
6441
6442        cx.update(|cx| cx.refresh_windows());
6443
6444        cx.update_window(window_id, |cx| {
6445            assert_eq!(
6446                cx.window.rendered_views[&root_view.id()].name(),
6447                Some("render count: 2")
6448            );
6449            assert_eq!(
6450                cx.window.rendered_views[&view.id()].name(),
6451                Some("render count: 1")
6452            );
6453        });
6454
6455        cx.update(|cx| {
6456            cx.refresh_windows();
6457            drop(view);
6458        });
6459
6460        cx.update_window(window_id, |cx| {
6461            assert_eq!(
6462                cx.window.rendered_views[&root_view.id()].name(),
6463                Some("render count: 3")
6464            );
6465            assert_eq!(cx.window.rendered_views.len(), 1);
6466        });
6467    }
6468
6469    #[crate::test(self)]
6470    async fn test_labeled_tasks(cx: &mut TestAppContext) {
6471        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6472        let (mut sender, mut reciever) = postage::oneshot::channel::<()>();
6473        let task = cx
6474            .update(|cx| cx.spawn_labeled("Test Label", |_| async move { reciever.recv().await }));
6475
6476        assert_eq!(
6477            Some("Test Label"),
6478            cx.update(|cx| cx.active_labeled_tasks().next())
6479        );
6480        sender
6481            .send(())
6482            .await
6483            .expect("Could not send message to complete task");
6484        task.await;
6485
6486        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6487    }
6488
6489    #[crate::test(self)]
6490    async fn test_window_activation(cx: &mut TestAppContext) {
6491        struct View(&'static str);
6492
6493        impl super::Entity for View {
6494            type Event = ();
6495        }
6496
6497        impl super::View for View {
6498            fn ui_name() -> &'static str {
6499                "test view"
6500            }
6501
6502            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6503                Empty::new().boxed()
6504            }
6505        }
6506
6507        let events = Rc::new(RefCell::new(Vec::new()));
6508        let (window_1, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6509            cx.observe_window_activation({
6510                let events = events.clone();
6511                move |this, active, _| events.borrow_mut().push((this.0, active))
6512            })
6513            .detach();
6514            View("window 1")
6515        });
6516        assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
6517
6518        let (window_2, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6519            cx.observe_window_activation({
6520                let events = events.clone();
6521                move |this, active, _| events.borrow_mut().push((this.0, active))
6522            })
6523            .detach();
6524            View("window 2")
6525        });
6526        assert_eq!(
6527            mem::take(&mut *events.borrow_mut()),
6528            [("window 1", false), ("window 2", true)]
6529        );
6530
6531        let (window_3, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6532            cx.observe_window_activation({
6533                let events = events.clone();
6534                move |this, active, _| events.borrow_mut().push((this.0, active))
6535            })
6536            .detach();
6537            View("window 3")
6538        });
6539        assert_eq!(
6540            mem::take(&mut *events.borrow_mut()),
6541            [("window 2", false), ("window 3", true)]
6542        );
6543
6544        cx.simulate_window_activation(Some(window_2));
6545        assert_eq!(
6546            mem::take(&mut *events.borrow_mut()),
6547            [("window 3", false), ("window 2", true)]
6548        );
6549
6550        cx.simulate_window_activation(Some(window_1));
6551        assert_eq!(
6552            mem::take(&mut *events.borrow_mut()),
6553            [("window 2", false), ("window 1", true)]
6554        );
6555
6556        cx.simulate_window_activation(Some(window_3));
6557        assert_eq!(
6558            mem::take(&mut *events.borrow_mut()),
6559            [("window 1", false), ("window 3", true)]
6560        );
6561
6562        cx.simulate_window_activation(Some(window_3));
6563        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6564    }
6565
6566    #[crate::test(self)]
6567    fn test_child_view(cx: &mut AppContext) {
6568        struct Child {
6569            rendered: Rc<Cell<bool>>,
6570            dropped: Rc<Cell<bool>>,
6571        }
6572
6573        impl super::Entity for Child {
6574            type Event = ();
6575        }
6576
6577        impl super::View for Child {
6578            fn ui_name() -> &'static str {
6579                "child view"
6580            }
6581
6582            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6583                self.rendered.set(true);
6584                Empty::new().boxed()
6585            }
6586        }
6587
6588        impl Drop for Child {
6589            fn drop(&mut self) {
6590                self.dropped.set(true);
6591            }
6592        }
6593
6594        struct Parent {
6595            child: Option<ViewHandle<Child>>,
6596        }
6597
6598        impl super::Entity for Parent {
6599            type Event = ();
6600        }
6601
6602        impl super::View for Parent {
6603            fn ui_name() -> &'static str {
6604                "parent view"
6605            }
6606
6607            fn render(&mut self, cx: &mut ViewContext<Self>) -> Element<Self> {
6608                if let Some(child) = self.child.as_ref() {
6609                    ChildView::new(child, cx).boxed()
6610                } else {
6611                    Empty::new().boxed()
6612                }
6613            }
6614        }
6615
6616        let child_rendered = Rc::new(Cell::new(false));
6617        let child_dropped = Rc::new(Cell::new(false));
6618        let (_, root_view) = cx.add_window(Default::default(), |cx| Parent {
6619            child: Some(cx.add_view(|_| Child {
6620                rendered: child_rendered.clone(),
6621                dropped: child_dropped.clone(),
6622            })),
6623        });
6624        assert!(child_rendered.take());
6625        assert!(!child_dropped.take());
6626
6627        root_view.update(cx, |view, cx| {
6628            view.child.take();
6629            cx.notify();
6630        });
6631        assert!(!child_rendered.take());
6632        assert!(child_dropped.take());
6633    }
6634
6635    #[derive(Default)]
6636    struct TestView {
6637        events: Vec<String>,
6638    }
6639
6640    impl Entity for TestView {
6641        type Event = String;
6642    }
6643
6644    impl View for TestView {
6645        fn ui_name() -> &'static str {
6646            "TestView"
6647        }
6648
6649        fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6650            Empty::new().boxed()
6651        }
6652    }
6653}