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