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