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