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        self.mouse_state_dynamic(TypeTag::new::<Tag>(), region_id)
3284    }
3285
3286    pub fn mouse_state_dynamic(&self, tag: TypeTag, region_id: usize) -> MouseState {
3287        let region_id = MouseRegionId::new(tag, self.view_id, region_id);
3288        MouseState {
3289            hovered: self.window.hovered_region_ids.contains(&region_id),
3290            clicked: if let Some((clicked_region_id, button)) = self.window.clicked_region {
3291                if region_id == clicked_region_id {
3292                    Some(button)
3293                } else {
3294                    None
3295                }
3296            } else {
3297                None
3298            },
3299            accessed_hovered: false,
3300            accessed_clicked: false,
3301        }
3302    }
3303
3304    pub fn element_state<Tag: 'static, T: 'static>(
3305        &mut self,
3306        element_id: usize,
3307        initial: T,
3308    ) -> ElementStateHandle<T> {
3309        let id = ElementStateId {
3310            view_id: self.view_id(),
3311            element_id,
3312            tag: TypeId::of::<Tag>(),
3313        };
3314        self.element_states
3315            .entry(id)
3316            .or_insert_with(|| Box::new(initial));
3317        ElementStateHandle::new(id, self.frame_count, &self.ref_counts)
3318    }
3319
3320    pub fn default_element_state<Tag: 'static, T: 'static + Default>(
3321        &mut self,
3322        element_id: usize,
3323    ) -> ElementStateHandle<T> {
3324        self.element_state::<Tag, T>(element_id, T::default())
3325    }
3326}
3327
3328#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
3329pub struct TypeTag {
3330    tag: TypeId,
3331    #[cfg(debug_assertions)]
3332    tag_type_name: &'static str,
3333}
3334
3335impl TypeTag {
3336    pub fn new<Tag: 'static>() -> Self {
3337        Self {
3338            tag: TypeId::of::<Tag>(),
3339            #[cfg(debug_assertions)]
3340            tag_type_name: std::any::type_name::<Tag>(),
3341        }
3342    }
3343
3344    pub fn dynamic(tag: TypeId, #[cfg(debug_assertions)] type_name: &'static str) -> Self {
3345        Self {
3346            tag,
3347            #[cfg(debug_assertions)]
3348            tag_type_name: type_name,
3349        }
3350    }
3351
3352    #[cfg(debug_assertions)]
3353    pub(crate) fn type_name(&self) -> &'static str {
3354        self.tag_type_name
3355    }
3356}
3357
3358impl<V> BorrowAppContext for ViewContext<'_, '_, V> {
3359    fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
3360        BorrowAppContext::read_with(&*self.window_context, f)
3361    }
3362
3363    fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
3364        BorrowAppContext::update(&mut *self.window_context, f)
3365    }
3366}
3367
3368impl<V> BorrowWindowContext for ViewContext<'_, '_, V> {
3369    type Result<T> = T;
3370
3371    fn read_window<T, F: FnOnce(&WindowContext) -> T>(&self, window: AnyWindowHandle, f: F) -> T {
3372        BorrowWindowContext::read_window(&*self.window_context, window, f)
3373    }
3374
3375    fn read_window_optional<T, F>(&self, window: AnyWindowHandle, f: F) -> Option<T>
3376    where
3377        F: FnOnce(&WindowContext) -> Option<T>,
3378    {
3379        BorrowWindowContext::read_window_optional(&*self.window_context, window, f)
3380    }
3381
3382    fn update_window<T, F: FnOnce(&mut WindowContext) -> T>(
3383        &mut self,
3384        window: AnyWindowHandle,
3385        f: F,
3386    ) -> T {
3387        BorrowWindowContext::update_window(&mut *self.window_context, window, f)
3388    }
3389
3390    fn update_window_optional<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Option<T>
3391    where
3392        F: FnOnce(&mut WindowContext) -> Option<T>,
3393    {
3394        BorrowWindowContext::update_window_optional(&mut *self.window_context, window, f)
3395    }
3396}
3397
3398pub struct LayoutContext<'a, 'b, 'c, V: View> {
3399    view_context: &'c mut ViewContext<'a, 'b, V>,
3400    new_parents: &'c mut HashMap<usize, usize>,
3401    views_to_notify_if_ancestors_change: &'c mut HashMap<usize, SmallVec<[usize; 2]>>,
3402    text_style_stack: Vec<Arc<TextStyle>>,
3403    pub refreshing: bool,
3404}
3405
3406impl<'a, 'b, 'c, V: View> LayoutContext<'a, 'b, 'c, V> {
3407    pub fn new(
3408        view_context: &'c mut ViewContext<'a, 'b, V>,
3409        new_parents: &'c mut HashMap<usize, usize>,
3410        views_to_notify_if_ancestors_change: &'c mut HashMap<usize, SmallVec<[usize; 2]>>,
3411        refreshing: bool,
3412    ) -> Self {
3413        Self {
3414            view_context,
3415            new_parents,
3416            views_to_notify_if_ancestors_change,
3417            text_style_stack: Vec::new(),
3418            refreshing,
3419        }
3420    }
3421
3422    pub fn view_context(&mut self) -> &mut ViewContext<'a, 'b, V> {
3423        self.view_context
3424    }
3425
3426    /// Return keystrokes that would dispatch the given action on the given view.
3427    pub(crate) fn keystrokes_for_action(
3428        &mut self,
3429        view_id: usize,
3430        action: &dyn Action,
3431    ) -> Option<SmallVec<[Keystroke; 2]>> {
3432        self.notify_if_view_ancestors_change(view_id);
3433
3434        let window = self.window_handle;
3435        let mut contexts = Vec::new();
3436        let mut handler_depth = None;
3437        for (i, view_id) in self.ancestors(view_id).enumerate() {
3438            if let Some(view_metadata) = self.views_metadata.get(&(window, view_id)) {
3439                if let Some(actions) = self.actions.get(&view_metadata.type_id) {
3440                    if actions.contains_key(&action.id()) {
3441                        handler_depth = Some(i);
3442                    }
3443                }
3444                contexts.push(view_metadata.keymap_context.clone());
3445            }
3446        }
3447
3448        if self.global_actions.contains_key(&action.id()) {
3449            handler_depth = Some(contexts.len())
3450        }
3451
3452        let action_contexts = if let Some(depth) = handler_depth {
3453            &contexts[depth..]
3454        } else {
3455            &contexts
3456        };
3457
3458        self.keystroke_matcher
3459            .keystrokes_for_action(action, action_contexts)
3460    }
3461
3462    fn notify_if_view_ancestors_change(&mut self, view_id: usize) {
3463        let self_view_id = self.view_id;
3464        self.views_to_notify_if_ancestors_change
3465            .entry(view_id)
3466            .or_default()
3467            .push(self_view_id);
3468    }
3469
3470    pub fn text_style(&self) -> Arc<TextStyle> {
3471        self.text_style_stack
3472            .last()
3473            .cloned()
3474            .unwrap_or(Default::default())
3475    }
3476
3477    pub fn with_text_style<S, F, T>(&mut self, style: S, f: F) -> T
3478    where
3479        S: Into<Arc<TextStyle>>,
3480        F: FnOnce(&mut Self) -> T,
3481    {
3482        self.text_style_stack.push(style.into());
3483        let result = f(self);
3484        self.text_style_stack.pop();
3485        result
3486    }
3487}
3488
3489impl<'a, 'b, 'c, V: View> Deref for LayoutContext<'a, 'b, 'c, V> {
3490    type Target = ViewContext<'a, 'b, V>;
3491
3492    fn deref(&self) -> &Self::Target {
3493        &self.view_context
3494    }
3495}
3496
3497impl<V: View> DerefMut for LayoutContext<'_, '_, '_, V> {
3498    fn deref_mut(&mut self) -> &mut Self::Target {
3499        &mut self.view_context
3500    }
3501}
3502
3503impl<V: View> BorrowAppContext for LayoutContext<'_, '_, '_, V> {
3504    fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
3505        BorrowAppContext::read_with(&*self.view_context, f)
3506    }
3507
3508    fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
3509        BorrowAppContext::update(&mut *self.view_context, f)
3510    }
3511}
3512
3513impl<V: View> BorrowWindowContext for LayoutContext<'_, '_, '_, V> {
3514    type Result<T> = T;
3515
3516    fn read_window<T, F: FnOnce(&WindowContext) -> T>(&self, window: AnyWindowHandle, f: F) -> T {
3517        BorrowWindowContext::read_window(&*self.view_context, window, f)
3518    }
3519
3520    fn read_window_optional<T, F>(&self, window: AnyWindowHandle, f: F) -> Option<T>
3521    where
3522        F: FnOnce(&WindowContext) -> Option<T>,
3523    {
3524        BorrowWindowContext::read_window_optional(&*self.view_context, window, f)
3525    }
3526
3527    fn update_window<T, F: FnOnce(&mut WindowContext) -> T>(
3528        &mut self,
3529        window: AnyWindowHandle,
3530        f: F,
3531    ) -> T {
3532        BorrowWindowContext::update_window(&mut *self.view_context, window, f)
3533    }
3534
3535    fn update_window_optional<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Option<T>
3536    where
3537        F: FnOnce(&mut WindowContext) -> Option<T>,
3538    {
3539        BorrowWindowContext::update_window_optional(&mut *self.view_context, window, f)
3540    }
3541}
3542
3543pub struct PaintContext<'a, 'b, 'c, V: View> {
3544    view_context: &'c mut ViewContext<'a, 'b, V>,
3545    text_style_stack: Vec<Arc<TextStyle>>,
3546}
3547
3548impl<'a, 'b, 'c, V: View> PaintContext<'a, 'b, 'c, V> {
3549    pub fn new(view_context: &'c mut ViewContext<'a, 'b, V>) -> Self {
3550        Self {
3551            view_context,
3552            text_style_stack: Vec::new(),
3553        }
3554    }
3555
3556    pub fn text_style(&self) -> Arc<TextStyle> {
3557        self.text_style_stack
3558            .last()
3559            .cloned()
3560            .unwrap_or(Default::default())
3561    }
3562
3563    pub fn with_text_style<S, F, T>(&mut self, style: S, f: F) -> T
3564    where
3565        S: Into<Arc<TextStyle>>,
3566        F: FnOnce(&mut Self) -> T,
3567    {
3568        self.text_style_stack.push(style.into());
3569        let result = f(self);
3570        self.text_style_stack.pop();
3571        result
3572    }
3573}
3574
3575impl<'a, 'b, 'c, V: View> Deref for PaintContext<'a, 'b, 'c, V> {
3576    type Target = ViewContext<'a, 'b, V>;
3577
3578    fn deref(&self) -> &Self::Target {
3579        &self.view_context
3580    }
3581}
3582
3583impl<V: View> DerefMut for PaintContext<'_, '_, '_, V> {
3584    fn deref_mut(&mut self) -> &mut Self::Target {
3585        &mut self.view_context
3586    }
3587}
3588
3589impl<V: View> BorrowAppContext for PaintContext<'_, '_, '_, V> {
3590    fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
3591        BorrowAppContext::read_with(&*self.view_context, f)
3592    }
3593
3594    fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
3595        BorrowAppContext::update(&mut *self.view_context, f)
3596    }
3597}
3598
3599impl<V: View> BorrowWindowContext for PaintContext<'_, '_, '_, V> {
3600    type Result<T> = T;
3601
3602    fn read_window<T, F>(&self, window: AnyWindowHandle, f: F) -> Self::Result<T>
3603    where
3604        F: FnOnce(&WindowContext) -> T,
3605    {
3606        BorrowWindowContext::read_window(self.view_context, window, f)
3607    }
3608
3609    fn read_window_optional<T, F>(&self, window: AnyWindowHandle, f: F) -> Option<T>
3610    where
3611        F: FnOnce(&WindowContext) -> Option<T>,
3612    {
3613        BorrowWindowContext::read_window_optional(self.view_context, window, f)
3614    }
3615
3616    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Self::Result<T>
3617    where
3618        F: FnOnce(&mut WindowContext) -> T,
3619    {
3620        BorrowWindowContext::update_window(self.view_context, window, f)
3621    }
3622
3623    fn update_window_optional<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Option<T>
3624    where
3625        F: FnOnce(&mut WindowContext) -> Option<T>,
3626    {
3627        BorrowWindowContext::update_window_optional(self.view_context, window, f)
3628    }
3629}
3630
3631pub struct EventContext<'a, 'b, 'c, V: View> {
3632    view_context: &'c mut ViewContext<'a, 'b, V>,
3633    pub(crate) handled: bool,
3634}
3635
3636impl<'a, 'b, 'c, V: View> EventContext<'a, 'b, 'c, V> {
3637    pub(crate) fn new(view_context: &'c mut ViewContext<'a, 'b, V>) -> Self {
3638        EventContext {
3639            view_context,
3640            handled: true,
3641        }
3642    }
3643
3644    pub fn propagate_event(&mut self) {
3645        self.handled = false;
3646    }
3647}
3648
3649impl<'a, 'b, 'c, V: View> Deref for EventContext<'a, 'b, 'c, V> {
3650    type Target = ViewContext<'a, 'b, V>;
3651
3652    fn deref(&self) -> &Self::Target {
3653        &self.view_context
3654    }
3655}
3656
3657impl<V: View> DerefMut for EventContext<'_, '_, '_, V> {
3658    fn deref_mut(&mut self) -> &mut Self::Target {
3659        &mut self.view_context
3660    }
3661}
3662
3663impl<V: View> BorrowAppContext for EventContext<'_, '_, '_, V> {
3664    fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
3665        BorrowAppContext::read_with(&*self.view_context, f)
3666    }
3667
3668    fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
3669        BorrowAppContext::update(&mut *self.view_context, f)
3670    }
3671}
3672
3673impl<V: View> BorrowWindowContext for EventContext<'_, '_, '_, V> {
3674    type Result<T> = T;
3675
3676    fn read_window<T, F: FnOnce(&WindowContext) -> T>(&self, window: AnyWindowHandle, f: F) -> T {
3677        BorrowWindowContext::read_window(&*self.view_context, window, f)
3678    }
3679
3680    fn read_window_optional<T, F>(&self, window: AnyWindowHandle, f: F) -> Option<T>
3681    where
3682        F: FnOnce(&WindowContext) -> Option<T>,
3683    {
3684        BorrowWindowContext::read_window_optional(&*self.view_context, window, f)
3685    }
3686
3687    fn update_window<T, F: FnOnce(&mut WindowContext) -> T>(
3688        &mut self,
3689        window: AnyWindowHandle,
3690        f: F,
3691    ) -> T {
3692        BorrowWindowContext::update_window(&mut *self.view_context, window, f)
3693    }
3694
3695    fn update_window_optional<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Option<T>
3696    where
3697        F: FnOnce(&mut WindowContext) -> Option<T>,
3698    {
3699        BorrowWindowContext::update_window_optional(&mut *self.view_context, window, f)
3700    }
3701}
3702
3703pub(crate) enum Reference<'a, T> {
3704    Immutable(&'a T),
3705    Mutable(&'a mut T),
3706}
3707
3708impl<'a, T> Deref for Reference<'a, T> {
3709    type Target = T;
3710
3711    fn deref(&self) -> &Self::Target {
3712        match self {
3713            Reference::Immutable(target) => target,
3714            Reference::Mutable(target) => target,
3715        }
3716    }
3717}
3718
3719impl<'a, T> DerefMut for Reference<'a, T> {
3720    fn deref_mut(&mut self) -> &mut Self::Target {
3721        match self {
3722            Reference::Immutable(_) => {
3723                panic!("cannot mutably deref an immutable reference. this is a bug in GPUI.");
3724            }
3725            Reference::Mutable(target) => target,
3726        }
3727    }
3728}
3729
3730#[derive(Debug, Clone, Default)]
3731pub struct MouseState {
3732    pub(crate) hovered: bool,
3733    pub(crate) clicked: Option<MouseButton>,
3734    pub(crate) accessed_hovered: bool,
3735    pub(crate) accessed_clicked: bool,
3736}
3737
3738impl MouseState {
3739    pub fn hovered(&mut self) -> bool {
3740        self.accessed_hovered = true;
3741        self.hovered
3742    }
3743
3744    pub fn clicked(&mut self) -> Option<MouseButton> {
3745        self.accessed_clicked = true;
3746        self.clicked
3747    }
3748
3749    pub fn accessed_hovered(&self) -> bool {
3750        self.accessed_hovered
3751    }
3752
3753    pub fn accessed_clicked(&self) -> bool {
3754        self.accessed_clicked
3755    }
3756}
3757
3758pub trait Handle<T> {
3759    type Weak: 'static;
3760    fn id(&self) -> usize;
3761    fn location(&self) -> EntityLocation;
3762    fn downgrade(&self) -> Self::Weak;
3763    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3764    where
3765        Self: Sized;
3766}
3767
3768pub trait WeakHandle {
3769    fn id(&self) -> usize;
3770}
3771
3772#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
3773pub enum EntityLocation {
3774    Model(usize),
3775    View(usize, usize),
3776}
3777
3778pub struct ModelHandle<T: Entity> {
3779    any_handle: AnyModelHandle,
3780    model_type: PhantomData<T>,
3781}
3782
3783impl<T: Entity> Deref for ModelHandle<T> {
3784    type Target = AnyModelHandle;
3785
3786    fn deref(&self) -> &Self::Target {
3787        &self.any_handle
3788    }
3789}
3790
3791impl<T: Entity> ModelHandle<T> {
3792    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3793        Self {
3794            any_handle: AnyModelHandle::new(model_id, TypeId::of::<T>(), ref_counts.clone()),
3795            model_type: PhantomData,
3796        }
3797    }
3798
3799    pub fn downgrade(&self) -> WeakModelHandle<T> {
3800        WeakModelHandle::new(self.model_id)
3801    }
3802
3803    pub fn id(&self) -> usize {
3804        self.model_id
3805    }
3806
3807    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3808        cx.read_model(self)
3809    }
3810
3811    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3812    where
3813        C: BorrowAppContext,
3814        F: FnOnce(&T, &AppContext) -> S,
3815    {
3816        cx.read_with(|cx| read(self.read(cx), cx))
3817    }
3818
3819    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3820    where
3821        C: BorrowAppContext,
3822        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
3823    {
3824        let mut update = Some(update);
3825        cx.update(|cx| {
3826            cx.update_model(self, &mut |model, cx| {
3827                let update = update.take().unwrap();
3828                update(model, cx)
3829            })
3830        })
3831    }
3832}
3833
3834impl<T: Entity> Clone for ModelHandle<T> {
3835    fn clone(&self) -> Self {
3836        Self::new(self.model_id, &self.ref_counts)
3837    }
3838}
3839
3840impl<T: Entity> PartialEq for ModelHandle<T> {
3841    fn eq(&self, other: &Self) -> bool {
3842        self.model_id == other.model_id
3843    }
3844}
3845
3846impl<T: Entity> Eq for ModelHandle<T> {}
3847
3848impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
3849    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
3850        self.model_id == other.model_id
3851    }
3852}
3853
3854impl<T: Entity> Hash for ModelHandle<T> {
3855    fn hash<H: Hasher>(&self, state: &mut H) {
3856        self.model_id.hash(state);
3857    }
3858}
3859
3860impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
3861    fn borrow(&self) -> &usize {
3862        &self.model_id
3863    }
3864}
3865
3866impl<T: Entity> Debug for ModelHandle<T> {
3867    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3868        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
3869            .field(&self.model_id)
3870            .finish()
3871    }
3872}
3873
3874unsafe impl<T: Entity> Send for ModelHandle<T> {}
3875unsafe impl<T: Entity> Sync for ModelHandle<T> {}
3876
3877impl<T: Entity> Handle<T> for ModelHandle<T> {
3878    type Weak = WeakModelHandle<T>;
3879
3880    fn id(&self) -> usize {
3881        self.model_id
3882    }
3883
3884    fn location(&self) -> EntityLocation {
3885        EntityLocation::Model(self.model_id)
3886    }
3887
3888    fn downgrade(&self) -> Self::Weak {
3889        self.downgrade()
3890    }
3891
3892    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3893    where
3894        Self: Sized,
3895    {
3896        weak.upgrade(cx)
3897    }
3898}
3899
3900pub struct WeakModelHandle<T> {
3901    any_handle: AnyWeakModelHandle,
3902    model_type: PhantomData<T>,
3903}
3904
3905impl<T> WeakModelHandle<T> {
3906    pub fn into_any(self) -> AnyWeakModelHandle {
3907        self.any_handle
3908    }
3909}
3910
3911impl<T> Deref for WeakModelHandle<T> {
3912    type Target = AnyWeakModelHandle;
3913
3914    fn deref(&self) -> &Self::Target {
3915        &self.any_handle
3916    }
3917}
3918
3919impl<T> WeakHandle for WeakModelHandle<T> {
3920    fn id(&self) -> usize {
3921        self.model_id
3922    }
3923}
3924
3925unsafe impl<T> Send for WeakModelHandle<T> {}
3926unsafe impl<T> Sync for WeakModelHandle<T> {}
3927
3928impl<T: Entity> WeakModelHandle<T> {
3929    fn new(model_id: usize) -> Self {
3930        Self {
3931            any_handle: AnyWeakModelHandle {
3932                model_id,
3933                model_type: TypeId::of::<T>(),
3934            },
3935            model_type: PhantomData,
3936        }
3937    }
3938
3939    pub fn id(&self) -> usize {
3940        self.model_id
3941    }
3942
3943    pub fn is_upgradable(&self, cx: &impl BorrowAppContext) -> bool {
3944        cx.read_with(|cx| cx.model_handle_is_upgradable(self))
3945    }
3946
3947    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<T>> {
3948        cx.read_with(|cx| cx.upgrade_model_handle(self))
3949    }
3950}
3951
3952impl<T> Hash for WeakModelHandle<T> {
3953    fn hash<H: Hasher>(&self, state: &mut H) {
3954        self.model_id.hash(state)
3955    }
3956}
3957
3958impl<T> PartialEq for WeakModelHandle<T> {
3959    fn eq(&self, other: &Self) -> bool {
3960        self.model_id == other.model_id
3961    }
3962}
3963
3964impl<T> Eq for WeakModelHandle<T> {}
3965
3966impl<T: Entity> PartialEq<ModelHandle<T>> for WeakModelHandle<T> {
3967    fn eq(&self, other: &ModelHandle<T>) -> bool {
3968        self.model_id == other.model_id
3969    }
3970}
3971
3972impl<T> Clone for WeakModelHandle<T> {
3973    fn clone(&self) -> Self {
3974        Self {
3975            any_handle: self.any_handle.clone(),
3976            model_type: PhantomData,
3977        }
3978    }
3979}
3980
3981impl<T> Copy for WeakModelHandle<T> {}
3982
3983#[derive(Deref)]
3984pub struct WindowHandle<V> {
3985    #[deref]
3986    any_handle: AnyWindowHandle,
3987    root_view_type: PhantomData<V>,
3988}
3989
3990impl<V> Clone for WindowHandle<V> {
3991    fn clone(&self) -> Self {
3992        Self {
3993            any_handle: self.any_handle.clone(),
3994            root_view_type: PhantomData,
3995        }
3996    }
3997}
3998
3999impl<V> Copy for WindowHandle<V> {}
4000
4001impl<V: View> WindowHandle<V> {
4002    fn new(window_id: usize) -> Self {
4003        WindowHandle {
4004            any_handle: AnyWindowHandle::new(window_id, TypeId::of::<V>()),
4005            root_view_type: PhantomData,
4006        }
4007    }
4008
4009    pub fn root<C: BorrowWindowContext>(&self, cx: &C) -> C::Result<ViewHandle<V>> {
4010        self.read_with(cx, |cx| cx.root_view().clone().downcast().unwrap())
4011    }
4012
4013    pub fn read_root_with<C, F, R>(&self, cx: &C, read: F) -> C::Result<R>
4014    where
4015        C: BorrowWindowContext,
4016        F: FnOnce(&V, &ViewContext<V>) -> R,
4017    {
4018        self.read_with(cx, |cx| {
4019            cx.root_view()
4020                .downcast_ref::<V>()
4021                .unwrap()
4022                .read_with(cx, read)
4023        })
4024    }
4025
4026    pub fn update_root<C, F, R>(&self, cx: &mut C, update: F) -> C::Result<R>
4027    where
4028        C: BorrowWindowContext,
4029        F: FnOnce(&mut V, &mut ViewContext<V>) -> R,
4030    {
4031        cx.update_window(self.any_handle, |cx| {
4032            cx.root_view()
4033                .clone()
4034                .downcast::<V>()
4035                .unwrap()
4036                .update(cx, update)
4037        })
4038    }
4039
4040    pub fn replace_root<C, F>(&self, cx: &mut C, build_root: F) -> C::Result<ViewHandle<V>>
4041    where
4042        C: BorrowWindowContext,
4043        F: FnOnce(&mut ViewContext<V>) -> V,
4044    {
4045        cx.update_window(self.any_handle, |cx| {
4046            let root_view = self.add_view(cx, |cx| build_root(cx));
4047            cx.window.root_view = Some(root_view.clone().into_any());
4048            cx.window.focused_view_id = Some(root_view.id());
4049            root_view
4050        })
4051    }
4052}
4053
4054impl<V> Into<AnyWindowHandle> for WindowHandle<V> {
4055    fn into(self) -> AnyWindowHandle {
4056        self.any_handle
4057    }
4058}
4059
4060#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
4061pub struct AnyWindowHandle {
4062    window_id: usize,
4063    root_view_type: TypeId,
4064}
4065
4066impl AnyWindowHandle {
4067    fn new(window_id: usize, root_view_type: TypeId) -> Self {
4068        Self {
4069            window_id,
4070            root_view_type,
4071        }
4072    }
4073
4074    pub fn id(&self) -> usize {
4075        self.window_id
4076    }
4077
4078    pub fn read_with<C, F, R>(&self, cx: &C, read: F) -> C::Result<R>
4079    where
4080        C: BorrowWindowContext,
4081        F: FnOnce(&WindowContext) -> R,
4082    {
4083        cx.read_window(*self, |cx| read(cx))
4084    }
4085
4086    pub fn read_optional_with<C, F, R>(&self, cx: &C, read: F) -> Option<R>
4087    where
4088        C: BorrowWindowContext,
4089        F: FnOnce(&WindowContext) -> Option<R>,
4090    {
4091        cx.read_window_optional(*self, |cx| read(cx))
4092    }
4093
4094    pub fn update<C, F, R>(&self, cx: &mut C, update: F) -> C::Result<R>
4095    where
4096        C: BorrowWindowContext,
4097        F: FnOnce(&mut WindowContext) -> R,
4098    {
4099        cx.update_window(*self, update)
4100    }
4101
4102    pub fn update_optional<C, F, R>(&self, cx: &mut C, update: F) -> Option<R>
4103    where
4104        C: BorrowWindowContext,
4105        F: FnOnce(&mut WindowContext) -> Option<R>,
4106    {
4107        cx.update_window_optional(*self, update)
4108    }
4109
4110    pub fn add_view<C, U, F>(&self, cx: &mut C, build_view: F) -> C::Result<ViewHandle<U>>
4111    where
4112        C: BorrowWindowContext,
4113        U: View,
4114        F: FnOnce(&mut ViewContext<U>) -> U,
4115    {
4116        self.update(cx, |cx| cx.add_view(build_view))
4117    }
4118
4119    pub fn downcast<V: View>(self) -> Option<WindowHandle<V>> {
4120        if self.root_view_type == TypeId::of::<V>() {
4121            Some(WindowHandle {
4122                any_handle: self,
4123                root_view_type: PhantomData,
4124            })
4125        } else {
4126            None
4127        }
4128    }
4129
4130    pub fn root_is<V: View>(&self) -> bool {
4131        self.root_view_type == TypeId::of::<V>()
4132    }
4133
4134    pub fn is_active<C: BorrowWindowContext>(&self, cx: &C) -> C::Result<bool> {
4135        self.read_with(cx, |cx| cx.window.is_active)
4136    }
4137
4138    pub fn remove<C: BorrowWindowContext>(&self, cx: &mut C) -> C::Result<()> {
4139        self.update(cx, |cx| cx.remove_window())
4140    }
4141
4142    pub fn debug_elements<C: BorrowWindowContext>(&self, cx: &C) -> Option<json::Value> {
4143        self.read_optional_with(cx, |cx| {
4144            let root_view = cx.window.root_view();
4145            let root_element = cx.window.rendered_views.get(&root_view.id())?;
4146            root_element.debug(cx).log_err()
4147        })
4148    }
4149
4150    pub fn activate<C: BorrowWindowContext>(&mut self, cx: &mut C) -> C::Result<()> {
4151        self.update(cx, |cx| cx.activate_window())
4152    }
4153
4154    pub fn prompt<C: BorrowWindowContext>(
4155        &self,
4156        level: PromptLevel,
4157        msg: &str,
4158        answers: &[&str],
4159        cx: &mut C,
4160    ) -> C::Result<oneshot::Receiver<usize>> {
4161        self.update(cx, |cx| cx.prompt(level, msg, answers))
4162    }
4163
4164    pub fn dispatch_action<C: BorrowWindowContext>(
4165        &self,
4166        view_id: usize,
4167        action: &dyn Action,
4168        cx: &mut C,
4169    ) -> C::Result<()> {
4170        self.update(cx, |cx| {
4171            cx.dispatch_action(Some(view_id), action);
4172        })
4173    }
4174
4175    pub fn available_actions<C: BorrowWindowContext>(
4176        &self,
4177        view_id: usize,
4178        cx: &C,
4179    ) -> C::Result<Vec<(&'static str, Box<dyn Action>, SmallVec<[Binding; 1]>)>> {
4180        self.read_with(cx, |cx| cx.available_actions(view_id))
4181    }
4182
4183    #[cfg(any(test, feature = "test-support"))]
4184    pub fn simulate_activation(&self, cx: &mut TestAppContext) {
4185        self.update(cx, |cx| {
4186            let other_windows = cx
4187                .windows()
4188                .filter(|window| *window != *self)
4189                .collect::<Vec<_>>();
4190
4191            for window in other_windows {
4192                cx.window_changed_active_status(window, false)
4193            }
4194
4195            cx.window_changed_active_status(*self, true)
4196        });
4197    }
4198
4199    #[cfg(any(test, feature = "test-support"))]
4200    pub fn simulate_deactivation(&self, cx: &mut TestAppContext) {
4201        self.update(cx, |cx| {
4202            cx.window_changed_active_status(*self, false);
4203        })
4204    }
4205}
4206
4207#[repr(transparent)]
4208pub struct ViewHandle<T> {
4209    any_handle: AnyViewHandle,
4210    view_type: PhantomData<T>,
4211}
4212
4213impl<T> Deref for ViewHandle<T> {
4214    type Target = AnyViewHandle;
4215
4216    fn deref(&self) -> &Self::Target {
4217        &self.any_handle
4218    }
4219}
4220
4221impl<T: View> ViewHandle<T> {
4222    fn new(window: AnyWindowHandle, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4223        Self {
4224            any_handle: AnyViewHandle::new(window, view_id, TypeId::of::<T>(), ref_counts.clone()),
4225            view_type: PhantomData,
4226        }
4227    }
4228
4229    pub fn downgrade(&self) -> WeakViewHandle<T> {
4230        WeakViewHandle::new(self.window, self.view_id)
4231    }
4232
4233    pub fn into_any(self) -> AnyViewHandle {
4234        self.any_handle
4235    }
4236
4237    pub fn window(&self) -> AnyWindowHandle {
4238        self.window
4239    }
4240
4241    pub fn id(&self) -> usize {
4242        self.view_id
4243    }
4244
4245    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
4246        cx.read_view(self)
4247    }
4248
4249    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> C::Result<S>
4250    where
4251        C: BorrowWindowContext,
4252        F: FnOnce(&T, &ViewContext<T>) -> S,
4253    {
4254        cx.read_window(self.window, |cx| {
4255            let cx = ViewContext::immutable(cx, self.view_id);
4256            read(cx.read_view(self), &cx)
4257        })
4258    }
4259
4260    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> C::Result<S>
4261    where
4262        C: BorrowWindowContext,
4263        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
4264    {
4265        let mut update = Some(update);
4266
4267        cx.update_window(self.window, |cx| {
4268            cx.update_view(self, &mut |view, cx| {
4269                let update = update.take().unwrap();
4270                update(view, cx)
4271            })
4272        })
4273    }
4274
4275    pub fn is_focused(&self, cx: &WindowContext) -> bool {
4276        cx.focused_view_id() == Some(self.view_id)
4277    }
4278}
4279
4280impl<T: View> Clone for ViewHandle<T> {
4281    fn clone(&self) -> Self {
4282        ViewHandle::new(self.window, self.view_id, &self.ref_counts)
4283    }
4284}
4285
4286impl<T> PartialEq for ViewHandle<T> {
4287    fn eq(&self, other: &Self) -> bool {
4288        self.window == other.window && self.view_id == other.view_id
4289    }
4290}
4291
4292impl<T> PartialEq<AnyViewHandle> for ViewHandle<T> {
4293    fn eq(&self, other: &AnyViewHandle) -> bool {
4294        self.window == other.window && self.view_id == other.view_id
4295    }
4296}
4297
4298impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
4299    fn eq(&self, other: &WeakViewHandle<T>) -> bool {
4300        self.window == other.window && self.view_id == other.view_id
4301    }
4302}
4303
4304impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
4305    fn eq(&self, other: &ViewHandle<T>) -> bool {
4306        self.window == other.window && self.view_id == other.view_id
4307    }
4308}
4309
4310impl<T> Eq for ViewHandle<T> {}
4311
4312impl<T> Hash for ViewHandle<T> {
4313    fn hash<H: Hasher>(&self, state: &mut H) {
4314        self.window.hash(state);
4315        self.view_id.hash(state);
4316    }
4317}
4318
4319impl<T> Debug for ViewHandle<T> {
4320    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4321        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
4322            .field("window_id", &self.window)
4323            .field("view_id", &self.view_id)
4324            .finish()
4325    }
4326}
4327
4328impl<T: View> Handle<T> for ViewHandle<T> {
4329    type Weak = WeakViewHandle<T>;
4330
4331    fn id(&self) -> usize {
4332        self.view_id
4333    }
4334
4335    fn location(&self) -> EntityLocation {
4336        EntityLocation::View(self.window.id(), self.view_id)
4337    }
4338
4339    fn downgrade(&self) -> Self::Weak {
4340        self.downgrade()
4341    }
4342
4343    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4344    where
4345        Self: Sized,
4346    {
4347        weak.upgrade(cx)
4348    }
4349}
4350
4351pub struct AnyViewHandle {
4352    window: AnyWindowHandle,
4353    view_id: usize,
4354    view_type: TypeId,
4355    ref_counts: Arc<Mutex<RefCounts>>,
4356
4357    #[cfg(any(test, feature = "test-support"))]
4358    handle_id: usize,
4359}
4360
4361impl AnyViewHandle {
4362    fn new(
4363        window: AnyWindowHandle,
4364        view_id: usize,
4365        view_type: TypeId,
4366        ref_counts: Arc<Mutex<RefCounts>>,
4367    ) -> Self {
4368        ref_counts.lock().inc_view(window, view_id);
4369
4370        #[cfg(any(test, feature = "test-support"))]
4371        let handle_id = ref_counts
4372            .lock()
4373            .leak_detector
4374            .lock()
4375            .handle_created(None, view_id);
4376
4377        Self {
4378            window,
4379            view_id,
4380            view_type,
4381            ref_counts,
4382            #[cfg(any(test, feature = "test-support"))]
4383            handle_id,
4384        }
4385    }
4386
4387    pub fn window(&self) -> AnyWindowHandle {
4388        self.window
4389    }
4390
4391    pub fn id(&self) -> usize {
4392        self.view_id
4393    }
4394
4395    pub fn is<T: 'static>(&self) -> bool {
4396        TypeId::of::<T>() == self.view_type
4397    }
4398
4399    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
4400        if self.is::<T>() {
4401            Some(ViewHandle {
4402                any_handle: self,
4403                view_type: PhantomData,
4404            })
4405        } else {
4406            None
4407        }
4408    }
4409
4410    pub fn downcast_ref<T: View>(&self) -> Option<&ViewHandle<T>> {
4411        if self.is::<T>() {
4412            Some(unsafe { mem::transmute(self) })
4413        } else {
4414            None
4415        }
4416    }
4417
4418    pub fn downgrade(&self) -> AnyWeakViewHandle {
4419        AnyWeakViewHandle {
4420            window: self.window,
4421            view_id: self.view_id,
4422            view_type: self.view_type,
4423        }
4424    }
4425
4426    pub fn view_type(&self) -> TypeId {
4427        self.view_type
4428    }
4429
4430    pub fn debug_json<'a, 'b>(&self, cx: &'b WindowContext<'a>) -> serde_json::Value {
4431        cx.views
4432            .get(&(self.window, self.view_id))
4433            .map_or_else(|| serde_json::Value::Null, |view| view.debug_json(cx))
4434    }
4435}
4436
4437impl Clone for AnyViewHandle {
4438    fn clone(&self) -> Self {
4439        Self::new(
4440            self.window,
4441            self.view_id,
4442            self.view_type,
4443            self.ref_counts.clone(),
4444        )
4445    }
4446}
4447
4448impl PartialEq for AnyViewHandle {
4449    fn eq(&self, other: &Self) -> bool {
4450        self.window == other.window && self.view_id == other.view_id
4451    }
4452}
4453
4454impl<T> PartialEq<ViewHandle<T>> for AnyViewHandle {
4455    fn eq(&self, other: &ViewHandle<T>) -> bool {
4456        self.window == other.window && self.view_id == other.view_id
4457    }
4458}
4459
4460impl Drop for AnyViewHandle {
4461    fn drop(&mut self) {
4462        self.ref_counts.lock().dec_view(self.window, self.view_id);
4463        #[cfg(any(test, feature = "test-support"))]
4464        self.ref_counts
4465            .lock()
4466            .leak_detector
4467            .lock()
4468            .handle_dropped(self.view_id, self.handle_id);
4469    }
4470}
4471
4472impl Debug for AnyViewHandle {
4473    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4474        f.debug_struct("AnyViewHandle")
4475            .field("window_id", &self.window.id())
4476            .field("view_id", &self.view_id)
4477            .finish()
4478    }
4479}
4480
4481pub struct AnyModelHandle {
4482    model_id: usize,
4483    model_type: TypeId,
4484    ref_counts: Arc<Mutex<RefCounts>>,
4485
4486    #[cfg(any(test, feature = "test-support"))]
4487    handle_id: usize,
4488}
4489
4490impl AnyModelHandle {
4491    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
4492        ref_counts.lock().inc_model(model_id);
4493
4494        #[cfg(any(test, feature = "test-support"))]
4495        let handle_id = ref_counts
4496            .lock()
4497            .leak_detector
4498            .lock()
4499            .handle_created(None, model_id);
4500
4501        Self {
4502            model_id,
4503            model_type,
4504            ref_counts,
4505
4506            #[cfg(any(test, feature = "test-support"))]
4507            handle_id,
4508        }
4509    }
4510
4511    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
4512        if self.is::<T>() {
4513            Some(ModelHandle {
4514                any_handle: self,
4515                model_type: PhantomData,
4516            })
4517        } else {
4518            None
4519        }
4520    }
4521
4522    pub fn downgrade(&self) -> AnyWeakModelHandle {
4523        AnyWeakModelHandle {
4524            model_id: self.model_id,
4525            model_type: self.model_type,
4526        }
4527    }
4528
4529    pub fn is<T: Entity>(&self) -> bool {
4530        self.model_type == TypeId::of::<T>()
4531    }
4532
4533    pub fn model_type(&self) -> TypeId {
4534        self.model_type
4535    }
4536}
4537
4538impl Clone for AnyModelHandle {
4539    fn clone(&self) -> Self {
4540        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
4541    }
4542}
4543
4544impl Drop for AnyModelHandle {
4545    fn drop(&mut self) {
4546        let mut ref_counts = self.ref_counts.lock();
4547        ref_counts.dec_model(self.model_id);
4548
4549        #[cfg(any(test, feature = "test-support"))]
4550        ref_counts
4551            .leak_detector
4552            .lock()
4553            .handle_dropped(self.model_id, self.handle_id);
4554    }
4555}
4556
4557#[derive(Hash, PartialEq, Eq, Debug, Clone, Copy)]
4558pub struct AnyWeakModelHandle {
4559    model_id: usize,
4560    model_type: TypeId,
4561}
4562
4563impl AnyWeakModelHandle {
4564    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<AnyModelHandle> {
4565        cx.read_with(|cx| cx.upgrade_any_model_handle(self))
4566    }
4567
4568    pub fn model_type(&self) -> TypeId {
4569        self.model_type
4570    }
4571
4572    fn is<T: 'static>(&self) -> bool {
4573        TypeId::of::<T>() == self.model_type
4574    }
4575
4576    pub fn downcast<T: Entity>(self) -> Option<WeakModelHandle<T>> {
4577        if self.is::<T>() {
4578            let result = Some(WeakModelHandle {
4579                any_handle: self,
4580                model_type: PhantomData,
4581            });
4582
4583            result
4584        } else {
4585            None
4586        }
4587    }
4588}
4589
4590#[derive(Copy)]
4591pub struct WeakViewHandle<T> {
4592    any_handle: AnyWeakViewHandle,
4593    view_type: PhantomData<T>,
4594}
4595
4596impl<T> Debug for WeakViewHandle<T> {
4597    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4598        f.debug_struct(&format!("WeakViewHandle<{}>", type_name::<T>()))
4599            .field("any_handle", &self.any_handle)
4600            .finish()
4601    }
4602}
4603
4604impl<T> WeakHandle for WeakViewHandle<T> {
4605    fn id(&self) -> usize {
4606        self.view_id
4607    }
4608}
4609
4610impl<V: View> WeakViewHandle<V> {
4611    fn new(window: AnyWindowHandle, view_id: usize) -> Self {
4612        Self {
4613            any_handle: AnyWeakViewHandle {
4614                window,
4615                view_id,
4616                view_type: TypeId::of::<V>(),
4617            },
4618            view_type: PhantomData,
4619        }
4620    }
4621
4622    pub fn id(&self) -> usize {
4623        self.view_id
4624    }
4625
4626    pub fn window(&self) -> AnyWindowHandle {
4627        self.window
4628    }
4629
4630    pub fn window_id(&self) -> usize {
4631        self.window.id()
4632    }
4633
4634    pub fn into_any(self) -> AnyWeakViewHandle {
4635        self.any_handle
4636    }
4637
4638    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ViewHandle<V>> {
4639        cx.read_with(|cx| cx.upgrade_view_handle(self))
4640    }
4641
4642    pub fn read_with<T>(
4643        &self,
4644        cx: &AsyncAppContext,
4645        read: impl FnOnce(&V, &ViewContext<V>) -> T,
4646    ) -> Result<T> {
4647        cx.read(|cx| {
4648            let handle = cx
4649                .upgrade_view_handle(self)
4650                .ok_or_else(|| anyhow!("view {} was dropped", V::ui_name()))?;
4651            cx.read_window(self.window, |cx| handle.read_with(cx, read))
4652                .ok_or_else(|| anyhow!("window was removed"))
4653        })
4654    }
4655
4656    pub fn update<T>(
4657        &self,
4658        cx: &mut AsyncAppContext,
4659        update: impl FnOnce(&mut V, &mut ViewContext<V>) -> T,
4660    ) -> Result<T> {
4661        cx.update(|cx| {
4662            let handle = cx
4663                .upgrade_view_handle(self)
4664                .ok_or_else(|| anyhow!("view {} was dropped", V::ui_name()))?;
4665            cx.update_window(self.window, |cx| handle.update(cx, update))
4666                .ok_or_else(|| anyhow!("window was removed"))
4667        })
4668    }
4669}
4670
4671impl<T> Deref for WeakViewHandle<T> {
4672    type Target = AnyWeakViewHandle;
4673
4674    fn deref(&self) -> &Self::Target {
4675        &self.any_handle
4676    }
4677}
4678
4679impl<T> Clone for WeakViewHandle<T> {
4680    fn clone(&self) -> Self {
4681        Self {
4682            any_handle: self.any_handle.clone(),
4683            view_type: PhantomData,
4684        }
4685    }
4686}
4687
4688impl<T> PartialEq for WeakViewHandle<T> {
4689    fn eq(&self, other: &Self) -> bool {
4690        self.window == other.window && self.view_id == other.view_id
4691    }
4692}
4693
4694impl<T> Eq for WeakViewHandle<T> {}
4695
4696impl<T> Hash for WeakViewHandle<T> {
4697    fn hash<H: Hasher>(&self, state: &mut H) {
4698        self.any_handle.hash(state);
4699    }
4700}
4701
4702#[derive(Debug, Clone, Copy, Eq, PartialEq)]
4703pub struct AnyWeakViewHandle {
4704    window: AnyWindowHandle,
4705    view_id: usize,
4706    view_type: TypeId,
4707}
4708
4709impl AnyWeakViewHandle {
4710    pub fn id(&self) -> usize {
4711        self.view_id
4712    }
4713
4714    fn is<T: 'static>(&self) -> bool {
4715        TypeId::of::<T>() == self.view_type
4716    }
4717
4718    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<AnyViewHandle> {
4719        cx.read_with(|cx| cx.upgrade_any_view_handle(self))
4720    }
4721
4722    pub fn downcast<T: View>(self) -> Option<WeakViewHandle<T>> {
4723        if self.is::<T>() {
4724            Some(WeakViewHandle {
4725                any_handle: self,
4726                view_type: PhantomData,
4727            })
4728        } else {
4729            None
4730        }
4731    }
4732}
4733
4734impl Hash for AnyWeakViewHandle {
4735    fn hash<H: Hasher>(&self, state: &mut H) {
4736        self.window.hash(state);
4737        self.view_id.hash(state);
4738        self.view_type.hash(state);
4739    }
4740}
4741
4742#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4743pub struct ElementStateId {
4744    view_id: usize,
4745    element_id: usize,
4746    tag: TypeId,
4747}
4748
4749pub struct ElementStateHandle<T> {
4750    value_type: PhantomData<T>,
4751    id: ElementStateId,
4752    ref_counts: Weak<Mutex<RefCounts>>,
4753}
4754
4755impl<T: 'static> ElementStateHandle<T> {
4756    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4757        ref_counts.lock().inc_element_state(id, frame_id);
4758        Self {
4759            value_type: PhantomData,
4760            id,
4761            ref_counts: Arc::downgrade(ref_counts),
4762        }
4763    }
4764
4765    pub fn id(&self) -> ElementStateId {
4766        self.id
4767    }
4768
4769    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
4770        cx.element_states
4771            .get(&self.id)
4772            .unwrap()
4773            .downcast_ref()
4774            .unwrap()
4775    }
4776
4777    pub fn update<C, D, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
4778    where
4779        C: DerefMut<Target = D>,
4780        D: DerefMut<Target = AppContext>,
4781    {
4782        let mut element_state = cx.deref_mut().element_states.remove(&self.id).unwrap();
4783        let result = f(element_state.downcast_mut().unwrap(), cx);
4784        cx.deref_mut().element_states.insert(self.id, element_state);
4785        result
4786    }
4787}
4788
4789impl<T> Drop for ElementStateHandle<T> {
4790    fn drop(&mut self) {
4791        if let Some(ref_counts) = self.ref_counts.upgrade() {
4792            ref_counts.lock().dec_element_state(self.id);
4793        }
4794    }
4795}
4796
4797#[must_use]
4798pub enum Subscription {
4799    Subscription(callback_collection::Subscription<usize, SubscriptionCallback>),
4800    Observation(callback_collection::Subscription<usize, ObservationCallback>),
4801    GlobalSubscription(callback_collection::Subscription<TypeId, GlobalSubscriptionCallback>),
4802    GlobalObservation(callback_collection::Subscription<TypeId, GlobalObservationCallback>),
4803    FocusObservation(callback_collection::Subscription<usize, FocusObservationCallback>),
4804    WindowActivationObservation(
4805        callback_collection::Subscription<AnyWindowHandle, WindowActivationCallback>,
4806    ),
4807    WindowFullscreenObservation(
4808        callback_collection::Subscription<AnyWindowHandle, WindowFullscreenCallback>,
4809    ),
4810    WindowBoundsObservation(
4811        callback_collection::Subscription<AnyWindowHandle, WindowBoundsCallback>,
4812    ),
4813    KeystrokeObservation(callback_collection::Subscription<AnyWindowHandle, KeystrokeCallback>),
4814    ReleaseObservation(callback_collection::Subscription<usize, ReleaseObservationCallback>),
4815    ActionObservation(callback_collection::Subscription<(), ActionObservationCallback>),
4816    ActiveLabeledTasksObservation(
4817        callback_collection::Subscription<(), ActiveLabeledTasksCallback>,
4818    ),
4819}
4820
4821impl Subscription {
4822    pub fn id(&self) -> usize {
4823        match self {
4824            Subscription::Subscription(subscription) => subscription.id(),
4825            Subscription::Observation(subscription) => subscription.id(),
4826            Subscription::GlobalSubscription(subscription) => subscription.id(),
4827            Subscription::GlobalObservation(subscription) => subscription.id(),
4828            Subscription::FocusObservation(subscription) => subscription.id(),
4829            Subscription::WindowActivationObservation(subscription) => subscription.id(),
4830            Subscription::WindowFullscreenObservation(subscription) => subscription.id(),
4831            Subscription::WindowBoundsObservation(subscription) => subscription.id(),
4832            Subscription::KeystrokeObservation(subscription) => subscription.id(),
4833            Subscription::ReleaseObservation(subscription) => subscription.id(),
4834            Subscription::ActionObservation(subscription) => subscription.id(),
4835            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.id(),
4836        }
4837    }
4838
4839    pub fn detach(&mut self) {
4840        match self {
4841            Subscription::Subscription(subscription) => subscription.detach(),
4842            Subscription::GlobalSubscription(subscription) => subscription.detach(),
4843            Subscription::Observation(subscription) => subscription.detach(),
4844            Subscription::GlobalObservation(subscription) => subscription.detach(),
4845            Subscription::FocusObservation(subscription) => subscription.detach(),
4846            Subscription::KeystrokeObservation(subscription) => subscription.detach(),
4847            Subscription::WindowActivationObservation(subscription) => subscription.detach(),
4848            Subscription::WindowFullscreenObservation(subscription) => subscription.detach(),
4849            Subscription::WindowBoundsObservation(subscription) => subscription.detach(),
4850            Subscription::ReleaseObservation(subscription) => subscription.detach(),
4851            Subscription::ActionObservation(subscription) => subscription.detach(),
4852            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.detach(),
4853        }
4854    }
4855}
4856
4857#[cfg(test)]
4858mod tests {
4859    use super::*;
4860    use crate::{
4861        actions,
4862        elements::*,
4863        impl_actions,
4864        platform::{MouseButton, MouseButtonEvent},
4865        window::ChildView,
4866    };
4867    use itertools::Itertools;
4868    use postage::{sink::Sink, stream::Stream};
4869    use serde::Deserialize;
4870    use smol::future::poll_once;
4871    use std::{
4872        cell::Cell,
4873        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
4874    };
4875
4876    #[crate::test(self)]
4877    fn test_model_handles(cx: &mut AppContext) {
4878        struct Model {
4879            other: Option<ModelHandle<Model>>,
4880            events: Vec<String>,
4881        }
4882
4883        impl Entity for Model {
4884            type Event = usize;
4885        }
4886
4887        impl Model {
4888            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
4889                if let Some(other) = other.as_ref() {
4890                    cx.observe(other, |me, _, _| {
4891                        me.events.push("notified".into());
4892                    })
4893                    .detach();
4894                    cx.subscribe(other, |me, _, event, _| {
4895                        me.events.push(format!("observed event {}", event));
4896                    })
4897                    .detach();
4898                }
4899
4900                Self {
4901                    other,
4902                    events: Vec::new(),
4903                }
4904            }
4905        }
4906
4907        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
4908        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
4909        assert_eq!(cx.models.len(), 2);
4910
4911        handle_1.update(cx, |model, cx| {
4912            model.events.push("updated".into());
4913            cx.emit(1);
4914            cx.notify();
4915            cx.emit(2);
4916        });
4917        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4918        assert_eq!(
4919            handle_2.read(cx).events,
4920            vec![
4921                "observed event 1".to_string(),
4922                "notified".to_string(),
4923                "observed event 2".to_string(),
4924            ]
4925        );
4926
4927        handle_2.update(cx, |model, _| {
4928            drop(handle_1);
4929            model.other.take();
4930        });
4931
4932        assert_eq!(cx.models.len(), 1);
4933        assert!(cx.subscriptions.is_empty());
4934        assert!(cx.observations.is_empty());
4935    }
4936
4937    #[crate::test(self)]
4938    fn test_model_events(cx: &mut AppContext) {
4939        #[derive(Default)]
4940        struct Model {
4941            events: Vec<usize>,
4942        }
4943
4944        impl Entity for Model {
4945            type Event = usize;
4946        }
4947
4948        let handle_1 = cx.add_model(|_| Model::default());
4949        let handle_2 = cx.add_model(|_| Model::default());
4950
4951        handle_1.update(cx, |_, cx| {
4952            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
4953                model.events.push(*event);
4954
4955                cx.subscribe(&emitter, |model, _, event, _| {
4956                    model.events.push(*event * 2);
4957                })
4958                .detach();
4959            })
4960            .detach();
4961        });
4962
4963        handle_2.update(cx, |_, c| c.emit(7));
4964        assert_eq!(handle_1.read(cx).events, vec![7]);
4965
4966        handle_2.update(cx, |_, c| c.emit(5));
4967        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4968    }
4969
4970    #[crate::test(self)]
4971    fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
4972        #[derive(Default)]
4973        struct Model;
4974
4975        impl Entity for Model {
4976            type Event = ();
4977        }
4978
4979        let events = Rc::new(RefCell::new(Vec::new()));
4980        cx.add_model(|cx| {
4981            drop(cx.subscribe(&cx.handle(), {
4982                let events = events.clone();
4983                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
4984            }));
4985            cx.subscribe(&cx.handle(), {
4986                let events = events.clone();
4987                move |_, _, _, _| events.borrow_mut().push("before emit")
4988            })
4989            .detach();
4990            cx.emit(());
4991            cx.subscribe(&cx.handle(), {
4992                let events = events.clone();
4993                move |_, _, _, _| events.borrow_mut().push("after emit")
4994            })
4995            .detach();
4996            Model
4997        });
4998        assert_eq!(*events.borrow(), ["before emit"]);
4999    }
5000
5001    #[crate::test(self)]
5002    fn test_observe_and_notify_from_model(cx: &mut AppContext) {
5003        #[derive(Default)]
5004        struct Model {
5005            count: usize,
5006            events: Vec<usize>,
5007        }
5008
5009        impl Entity for Model {
5010            type Event = ();
5011        }
5012
5013        let handle_1 = cx.add_model(|_| Model::default());
5014        let handle_2 = cx.add_model(|_| Model::default());
5015
5016        handle_1.update(cx, |_, c| {
5017            c.observe(&handle_2, move |model, observed, c| {
5018                model.events.push(observed.read(c).count);
5019                c.observe(&observed, |model, observed, c| {
5020                    model.events.push(observed.read(c).count * 2);
5021                })
5022                .detach();
5023            })
5024            .detach();
5025        });
5026
5027        handle_2.update(cx, |model, c| {
5028            model.count = 7;
5029            c.notify()
5030        });
5031        assert_eq!(handle_1.read(cx).events, vec![7]);
5032
5033        handle_2.update(cx, |model, c| {
5034            model.count = 5;
5035            c.notify()
5036        });
5037        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
5038    }
5039
5040    #[crate::test(self)]
5041    fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
5042        #[derive(Default)]
5043        struct Model;
5044
5045        impl Entity for Model {
5046            type Event = ();
5047        }
5048
5049        let events = Rc::new(RefCell::new(Vec::new()));
5050        cx.add_model(|cx| {
5051            drop(cx.observe(&cx.handle(), {
5052                let events = events.clone();
5053                move |_, _, _| events.borrow_mut().push("dropped before flush")
5054            }));
5055            cx.observe(&cx.handle(), {
5056                let events = events.clone();
5057                move |_, _, _| events.borrow_mut().push("before notify")
5058            })
5059            .detach();
5060            cx.notify();
5061            cx.observe(&cx.handle(), {
5062                let events = events.clone();
5063                move |_, _, _| events.borrow_mut().push("after notify")
5064            })
5065            .detach();
5066            Model
5067        });
5068        assert_eq!(*events.borrow(), ["before notify"]);
5069    }
5070
5071    #[crate::test(self)]
5072    fn test_defer_and_after_window_update(cx: &mut TestAppContext) {
5073        struct View {
5074            render_count: usize,
5075        }
5076
5077        impl Entity for View {
5078            type Event = usize;
5079        }
5080
5081        impl super::View for View {
5082            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5083                post_inc(&mut self.render_count);
5084                Empty::new().into_any()
5085            }
5086
5087            fn ui_name() -> &'static str {
5088                "View"
5089            }
5090        }
5091
5092        let window = cx.add_window(|_| View { render_count: 0 });
5093        let called_defer = Rc::new(AtomicBool::new(false));
5094        let called_after_window_update = Rc::new(AtomicBool::new(false));
5095
5096        window.root(cx).update(cx, |this, cx| {
5097            assert_eq!(this.render_count, 1);
5098            cx.defer({
5099                let called_defer = called_defer.clone();
5100                move |this, _| {
5101                    assert_eq!(this.render_count, 1);
5102                    called_defer.store(true, SeqCst);
5103                }
5104            });
5105            cx.after_window_update({
5106                let called_after_window_update = called_after_window_update.clone();
5107                move |this, cx| {
5108                    assert_eq!(this.render_count, 2);
5109                    called_after_window_update.store(true, SeqCst);
5110                    cx.notify();
5111                }
5112            });
5113            assert!(!called_defer.load(SeqCst));
5114            assert!(!called_after_window_update.load(SeqCst));
5115            cx.notify();
5116        });
5117
5118        assert!(called_defer.load(SeqCst));
5119        assert!(called_after_window_update.load(SeqCst));
5120        assert_eq!(window.read_root_with(cx, |view, _| view.render_count), 3);
5121    }
5122
5123    #[crate::test(self)]
5124    fn test_view_handles(cx: &mut TestAppContext) {
5125        struct View {
5126            other: Option<ViewHandle<View>>,
5127            events: Vec<String>,
5128        }
5129
5130        impl Entity for View {
5131            type Event = usize;
5132        }
5133
5134        impl super::View for View {
5135            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5136                Empty::new().into_any()
5137            }
5138
5139            fn ui_name() -> &'static str {
5140                "View"
5141            }
5142        }
5143
5144        impl View {
5145            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
5146                if let Some(other) = other.as_ref() {
5147                    cx.subscribe(other, |me, _, event, _| {
5148                        me.events.push(format!("observed event {}", event));
5149                    })
5150                    .detach();
5151                }
5152                Self {
5153                    other,
5154                    events: Vec::new(),
5155                }
5156            }
5157        }
5158
5159        let window = cx.add_window(|cx| View::new(None, cx));
5160        let handle_1 = window.add_view(cx, |cx| View::new(None, cx));
5161        let handle_2 = window.add_view(cx, |cx| View::new(Some(handle_1.clone()), cx));
5162        assert_eq!(cx.read(|cx| cx.views.len()), 3);
5163
5164        handle_1.update(cx, |view, cx| {
5165            view.events.push("updated".into());
5166            cx.emit(1);
5167            cx.emit(2);
5168        });
5169        handle_1.read_with(cx, |view, _| {
5170            assert_eq!(view.events, vec!["updated".to_string()]);
5171        });
5172        handle_2.read_with(cx, |view, _| {
5173            assert_eq!(
5174                view.events,
5175                vec![
5176                    "observed event 1".to_string(),
5177                    "observed event 2".to_string(),
5178                ]
5179            );
5180        });
5181
5182        handle_2.update(cx, |view, _| {
5183            drop(handle_1);
5184            view.other.take();
5185        });
5186
5187        cx.read(|cx| {
5188            assert_eq!(cx.views.len(), 2);
5189            assert!(cx.subscriptions.is_empty());
5190            assert!(cx.observations.is_empty());
5191        });
5192    }
5193
5194    #[crate::test(self)]
5195    fn test_add_window(cx: &mut AppContext) {
5196        struct View {
5197            mouse_down_count: Arc<AtomicUsize>,
5198        }
5199
5200        impl Entity for View {
5201            type Event = ();
5202        }
5203
5204        impl super::View for View {
5205            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
5206                enum Handler {}
5207                let mouse_down_count = self.mouse_down_count.clone();
5208                MouseEventHandler::new::<Handler, _>(0, cx, |_, _| Empty::new())
5209                    .on_down(MouseButton::Left, move |_, _, _| {
5210                        mouse_down_count.fetch_add(1, SeqCst);
5211                    })
5212                    .into_any()
5213            }
5214
5215            fn ui_name() -> &'static str {
5216                "View"
5217            }
5218        }
5219
5220        let mouse_down_count = Arc::new(AtomicUsize::new(0));
5221        let window = cx.add_window(Default::default(), |_| View {
5222            mouse_down_count: mouse_down_count.clone(),
5223        });
5224
5225        window.update(cx, |cx| {
5226            // Ensure window's root element is in a valid lifecycle state.
5227            cx.dispatch_event(
5228                Event::MouseDown(MouseButtonEvent {
5229                    position: Default::default(),
5230                    button: MouseButton::Left,
5231                    modifiers: Default::default(),
5232                    click_count: 1,
5233                }),
5234                false,
5235            );
5236            assert_eq!(mouse_down_count.load(SeqCst), 1);
5237        });
5238    }
5239
5240    #[crate::test(self)]
5241    fn test_entity_release_hooks(cx: &mut TestAppContext) {
5242        struct Model {
5243            released: Rc<Cell<bool>>,
5244        }
5245
5246        struct View {
5247            released: Rc<Cell<bool>>,
5248        }
5249
5250        impl Entity for Model {
5251            type Event = ();
5252
5253            fn release(&mut self, _: &mut AppContext) {
5254                self.released.set(true);
5255            }
5256        }
5257
5258        impl Entity for View {
5259            type Event = ();
5260
5261            fn release(&mut self, _: &mut AppContext) {
5262                self.released.set(true);
5263            }
5264        }
5265
5266        impl super::View for View {
5267            fn ui_name() -> &'static str {
5268                "View"
5269            }
5270
5271            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5272                Empty::new().into_any()
5273            }
5274        }
5275
5276        let model_released = Rc::new(Cell::new(false));
5277        let model_release_observed = Rc::new(Cell::new(false));
5278        let view_released = Rc::new(Cell::new(false));
5279        let view_release_observed = Rc::new(Cell::new(false));
5280
5281        let model = cx.add_model(|_| Model {
5282            released: model_released.clone(),
5283        });
5284        let window = cx.add_window(|_| View {
5285            released: view_released.clone(),
5286        });
5287        let view = window.root(cx);
5288
5289        assert!(!model_released.get());
5290        assert!(!view_released.get());
5291
5292        cx.update(|cx| {
5293            cx.observe_release(&model, {
5294                let model_release_observed = model_release_observed.clone();
5295                move |_, _| model_release_observed.set(true)
5296            })
5297            .detach();
5298            cx.observe_release(&view, {
5299                let view_release_observed = view_release_observed.clone();
5300                move |_, _| view_release_observed.set(true)
5301            })
5302            .detach();
5303        });
5304
5305        cx.update(move |_| {
5306            drop(model);
5307        });
5308        assert!(model_released.get());
5309        assert!(model_release_observed.get());
5310
5311        drop(view);
5312        window.update(cx, |cx| cx.remove_window());
5313        assert!(view_released.get());
5314        assert!(view_release_observed.get());
5315    }
5316
5317    #[crate::test(self)]
5318    fn test_view_events(cx: &mut TestAppContext) {
5319        struct Model;
5320
5321        impl Entity for Model {
5322            type Event = String;
5323        }
5324
5325        let window = cx.add_window(|_| TestView::default());
5326        let handle_1 = window.root(cx);
5327        let handle_2 = window.add_view(cx, |_| TestView::default());
5328        let handle_3 = cx.add_model(|_| Model);
5329
5330        handle_1.update(cx, |_, cx| {
5331            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
5332                me.events.push(event.clone());
5333
5334                cx.subscribe(&emitter, |me, _, event, _| {
5335                    me.events.push(format!("{event} from inner"));
5336                })
5337                .detach();
5338            })
5339            .detach();
5340
5341            cx.subscribe(&handle_3, |me, _, event, _| {
5342                me.events.push(event.clone());
5343            })
5344            .detach();
5345        });
5346
5347        handle_2.update(cx, |_, c| c.emit("7".into()));
5348        handle_1.read_with(cx, |view, _| assert_eq!(view.events, ["7"]));
5349
5350        handle_2.update(cx, |_, c| c.emit("5".into()));
5351        handle_1.read_with(cx, |view, _| {
5352            assert_eq!(view.events, ["7", "5", "5 from inner"])
5353        });
5354
5355        handle_3.update(cx, |_, c| c.emit("9".into()));
5356        handle_1.read_with(cx, |view, _| {
5357            assert_eq!(view.events, ["7", "5", "5 from inner", "9"])
5358        });
5359    }
5360
5361    #[crate::test(self)]
5362    fn test_global_events(cx: &mut AppContext) {
5363        #[derive(Clone, Debug, Eq, PartialEq)]
5364        struct GlobalEvent(u64);
5365
5366        let events = Rc::new(RefCell::new(Vec::new()));
5367        let first_subscription;
5368        let second_subscription;
5369
5370        {
5371            let events = events.clone();
5372            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5373                events.borrow_mut().push(("First", e.clone()));
5374            });
5375        }
5376
5377        {
5378            let events = events.clone();
5379            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5380                events.borrow_mut().push(("Second", e.clone()));
5381            });
5382        }
5383
5384        cx.update(|cx| {
5385            cx.emit_global(GlobalEvent(1));
5386            cx.emit_global(GlobalEvent(2));
5387        });
5388
5389        drop(first_subscription);
5390
5391        cx.update(|cx| {
5392            cx.emit_global(GlobalEvent(3));
5393        });
5394
5395        drop(second_subscription);
5396
5397        cx.update(|cx| {
5398            cx.emit_global(GlobalEvent(4));
5399        });
5400
5401        assert_eq!(
5402            &*events.borrow(),
5403            &[
5404                ("First", GlobalEvent(1)),
5405                ("Second", GlobalEvent(1)),
5406                ("First", GlobalEvent(2)),
5407                ("Second", GlobalEvent(2)),
5408                ("Second", GlobalEvent(3)),
5409            ]
5410        );
5411    }
5412
5413    #[crate::test(self)]
5414    fn test_global_events_emitted_before_subscription_in_same_update_cycle(cx: &mut AppContext) {
5415        let events = Rc::new(RefCell::new(Vec::new()));
5416        cx.update(|cx| {
5417            {
5418                let events = events.clone();
5419                drop(cx.subscribe_global(move |_: &(), _| {
5420                    events.borrow_mut().push("dropped before emit");
5421                }));
5422            }
5423
5424            {
5425                let events = events.clone();
5426                cx.subscribe_global(move |_: &(), _| {
5427                    events.borrow_mut().push("before emit");
5428                })
5429                .detach();
5430            }
5431
5432            cx.emit_global(());
5433
5434            {
5435                let events = events.clone();
5436                cx.subscribe_global(move |_: &(), _| {
5437                    events.borrow_mut().push("after emit");
5438                })
5439                .detach();
5440            }
5441        });
5442
5443        assert_eq!(*events.borrow(), ["before emit"]);
5444    }
5445
5446    #[crate::test(self)]
5447    fn test_global_nested_events(cx: &mut AppContext) {
5448        #[derive(Clone, Debug, Eq, PartialEq)]
5449        struct GlobalEvent(u64);
5450
5451        let events = Rc::new(RefCell::new(Vec::new()));
5452
5453        {
5454            let events = events.clone();
5455            cx.subscribe_global(move |e: &GlobalEvent, cx| {
5456                events.borrow_mut().push(("Outer", e.clone()));
5457
5458                if e.0 == 1 {
5459                    let events = events.clone();
5460                    cx.subscribe_global(move |e: &GlobalEvent, _| {
5461                        events.borrow_mut().push(("Inner", e.clone()));
5462                    })
5463                    .detach();
5464                }
5465            })
5466            .detach();
5467        }
5468
5469        cx.update(|cx| {
5470            cx.emit_global(GlobalEvent(1));
5471            cx.emit_global(GlobalEvent(2));
5472            cx.emit_global(GlobalEvent(3));
5473        });
5474        cx.update(|cx| {
5475            cx.emit_global(GlobalEvent(4));
5476        });
5477
5478        assert_eq!(
5479            &*events.borrow(),
5480            &[
5481                ("Outer", GlobalEvent(1)),
5482                ("Outer", GlobalEvent(2)),
5483                ("Outer", GlobalEvent(3)),
5484                ("Outer", GlobalEvent(4)),
5485                ("Inner", GlobalEvent(4)),
5486            ]
5487        );
5488    }
5489
5490    #[crate::test(self)]
5491    fn test_global(cx: &mut AppContext) {
5492        type Global = usize;
5493
5494        let observation_count = Rc::new(RefCell::new(0));
5495        let subscription = cx.observe_global::<Global, _>({
5496            let observation_count = observation_count.clone();
5497            move |_| {
5498                *observation_count.borrow_mut() += 1;
5499            }
5500        });
5501
5502        assert!(!cx.has_global::<Global>());
5503        assert_eq!(cx.default_global::<Global>(), &0);
5504        assert_eq!(*observation_count.borrow(), 1);
5505        assert!(cx.has_global::<Global>());
5506        assert_eq!(
5507            cx.update_global::<Global, _, _>(|global, _| {
5508                *global = 1;
5509                "Update Result"
5510            }),
5511            "Update Result"
5512        );
5513        assert_eq!(*observation_count.borrow(), 2);
5514        assert_eq!(cx.global::<Global>(), &1);
5515
5516        drop(subscription);
5517        cx.update_global::<Global, _, _>(|global, _| {
5518            *global = 2;
5519        });
5520        assert_eq!(*observation_count.borrow(), 2);
5521
5522        type OtherGlobal = f32;
5523
5524        let observation_count = Rc::new(RefCell::new(0));
5525        cx.observe_global::<OtherGlobal, _>({
5526            let observation_count = observation_count.clone();
5527            move |_| {
5528                *observation_count.borrow_mut() += 1;
5529            }
5530        })
5531        .detach();
5532
5533        assert_eq!(
5534            cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
5535                assert_eq!(global, &0.0);
5536                *global = 2.0;
5537                "Default update result"
5538            }),
5539            "Default update result"
5540        );
5541        assert_eq!(cx.global::<OtherGlobal>(), &2.0);
5542        assert_eq!(*observation_count.borrow(), 1);
5543    }
5544
5545    #[crate::test(self)]
5546    fn test_dropping_subscribers(cx: &mut TestAppContext) {
5547        struct Model;
5548
5549        impl Entity for Model {
5550            type Event = ();
5551        }
5552
5553        let window = cx.add_window(|_| TestView::default());
5554        let observing_view = window.add_view(cx, |_| TestView::default());
5555        let emitting_view = window.add_view(cx, |_| TestView::default());
5556        let observing_model = cx.add_model(|_| Model);
5557        let observed_model = cx.add_model(|_| Model);
5558
5559        observing_view.update(cx, |_, cx| {
5560            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
5561            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5562        });
5563        observing_model.update(cx, |_, cx| {
5564            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5565        });
5566
5567        cx.update(|_| {
5568            drop(observing_view);
5569            drop(observing_model);
5570        });
5571
5572        emitting_view.update(cx, |_, cx| cx.emit(Default::default()));
5573        observed_model.update(cx, |_, cx| cx.emit(()));
5574    }
5575
5576    #[crate::test(self)]
5577    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
5578        let window = cx.add_window::<TestView, _>(Default::default(), |cx| {
5579            drop(cx.subscribe(&cx.handle(), {
5580                move |this, _, _, _| this.events.push("dropped before flush".into())
5581            }));
5582            cx.subscribe(&cx.handle(), {
5583                move |this, _, _, _| this.events.push("before emit".into())
5584            })
5585            .detach();
5586            cx.emit("the event".into());
5587            cx.subscribe(&cx.handle(), {
5588                move |this, _, _, _| this.events.push("after emit".into())
5589            })
5590            .detach();
5591            TestView { events: Vec::new() }
5592        });
5593
5594        window.read_root_with(cx, |view, _| assert_eq!(view.events, ["before emit"]));
5595    }
5596
5597    #[crate::test(self)]
5598    fn test_observe_and_notify_from_view(cx: &mut TestAppContext) {
5599        #[derive(Default)]
5600        struct Model {
5601            state: String,
5602        }
5603
5604        impl Entity for Model {
5605            type Event = ();
5606        }
5607
5608        let window = cx.add_window(|_| TestView::default());
5609        let view = window.root(cx);
5610        let model = cx.add_model(|_| Model {
5611            state: "old-state".into(),
5612        });
5613
5614        view.update(cx, |_, c| {
5615            c.observe(&model, |me, observed, cx| {
5616                me.events.push(observed.read(cx).state.clone())
5617            })
5618            .detach();
5619        });
5620
5621        model.update(cx, |model, cx| {
5622            model.state = "new-state".into();
5623            cx.notify();
5624        });
5625        view.read_with(cx, |view, _| assert_eq!(view.events, ["new-state"]));
5626    }
5627
5628    #[crate::test(self)]
5629    fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
5630        let window = cx.add_window::<TestView, _>(Default::default(), |cx| {
5631            drop(cx.observe(&cx.handle(), {
5632                move |this, _, _| this.events.push("dropped before flush".into())
5633            }));
5634            cx.observe(&cx.handle(), {
5635                move |this, _, _| this.events.push("before notify".into())
5636            })
5637            .detach();
5638            cx.notify();
5639            cx.observe(&cx.handle(), {
5640                move |this, _, _| this.events.push("after notify".into())
5641            })
5642            .detach();
5643            TestView { events: Vec::new() }
5644        });
5645
5646        window.read_root_with(cx, |view, _| assert_eq!(view.events, ["before notify"]));
5647    }
5648
5649    #[crate::test(self)]
5650    fn test_notify_and_drop_observe_subscription_in_same_update_cycle(cx: &mut TestAppContext) {
5651        struct Model;
5652        impl Entity for Model {
5653            type Event = ();
5654        }
5655
5656        let model = cx.add_model(|_| Model);
5657        let window = cx.add_window(|_| TestView::default());
5658        let view = window.root(cx);
5659
5660        view.update(cx, |_, cx| {
5661            model.update(cx, |_, cx| cx.notify());
5662            drop(cx.observe(&model, move |this, _, _| {
5663                this.events.push("model notified".into());
5664            }));
5665            model.update(cx, |_, cx| cx.notify());
5666        });
5667
5668        for _ in 0..3 {
5669            model.update(cx, |_, cx| cx.notify());
5670        }
5671        view.read_with(cx, |view, _| assert_eq!(view.events, Vec::<&str>::new()));
5672    }
5673
5674    #[crate::test(self)]
5675    fn test_dropping_observers(cx: &mut TestAppContext) {
5676        struct Model;
5677
5678        impl Entity for Model {
5679            type Event = ();
5680        }
5681
5682        let window = cx.add_window(|_| TestView::default());
5683        let observing_view = window.add_view(cx, |_| TestView::default());
5684        let observing_model = cx.add_model(|_| Model);
5685        let observed_model = cx.add_model(|_| Model);
5686
5687        observing_view.update(cx, |_, cx| {
5688            cx.observe(&observed_model, |_, _, _| {}).detach();
5689        });
5690        observing_model.update(cx, |_, cx| {
5691            cx.observe(&observed_model, |_, _, _| {}).detach();
5692        });
5693
5694        cx.update(|_| {
5695            drop(observing_view);
5696            drop(observing_model);
5697        });
5698
5699        observed_model.update(cx, |_, cx| cx.notify());
5700    }
5701
5702    #[crate::test(self)]
5703    fn test_dropping_subscriptions_during_callback(cx: &mut TestAppContext) {
5704        struct Model;
5705
5706        impl Entity for Model {
5707            type Event = u64;
5708        }
5709
5710        // Events
5711        let observing_model = cx.add_model(|_| Model);
5712        let observed_model = cx.add_model(|_| Model);
5713
5714        let events = Rc::new(RefCell::new(Vec::new()));
5715
5716        observing_model.update(cx, |_, cx| {
5717            let events = events.clone();
5718            let subscription = Rc::new(RefCell::new(None));
5719            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
5720                let subscription = subscription.clone();
5721                move |_, _, e, _| {
5722                    subscription.borrow_mut().take();
5723                    events.borrow_mut().push(*e);
5724                }
5725            }));
5726        });
5727
5728        observed_model.update(cx, |_, cx| {
5729            cx.emit(1);
5730            cx.emit(2);
5731        });
5732
5733        assert_eq!(*events.borrow(), [1]);
5734
5735        // Global Events
5736        #[derive(Clone, Debug, Eq, PartialEq)]
5737        struct GlobalEvent(u64);
5738
5739        let events = Rc::new(RefCell::new(Vec::new()));
5740
5741        {
5742            let events = events.clone();
5743            let subscription = Rc::new(RefCell::new(None));
5744            *subscription.borrow_mut() = Some(cx.subscribe_global({
5745                let subscription = subscription.clone();
5746                move |e: &GlobalEvent, _| {
5747                    subscription.borrow_mut().take();
5748                    events.borrow_mut().push(e.clone());
5749                }
5750            }));
5751        }
5752
5753        cx.update(|cx| {
5754            cx.emit_global(GlobalEvent(1));
5755            cx.emit_global(GlobalEvent(2));
5756        });
5757
5758        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
5759
5760        // Model Observation
5761        let observing_model = cx.add_model(|_| Model);
5762        let observed_model = cx.add_model(|_| Model);
5763
5764        let observation_count = Rc::new(RefCell::new(0));
5765
5766        observing_model.update(cx, |_, cx| {
5767            let observation_count = observation_count.clone();
5768            let subscription = Rc::new(RefCell::new(None));
5769            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
5770                let subscription = subscription.clone();
5771                move |_, _, _| {
5772                    subscription.borrow_mut().take();
5773                    *observation_count.borrow_mut() += 1;
5774                }
5775            }));
5776        });
5777
5778        observed_model.update(cx, |_, cx| {
5779            cx.notify();
5780        });
5781
5782        observed_model.update(cx, |_, cx| {
5783            cx.notify();
5784        });
5785
5786        assert_eq!(*observation_count.borrow(), 1);
5787
5788        // View Observation
5789        struct View;
5790
5791        impl Entity for View {
5792            type Event = ();
5793        }
5794
5795        impl super::View for View {
5796            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5797                Empty::new().into_any()
5798            }
5799
5800            fn ui_name() -> &'static str {
5801                "View"
5802            }
5803        }
5804
5805        let window = cx.add_window(|_| View);
5806        let observing_view = window.add_view(cx, |_| View);
5807        let observed_view = window.add_view(cx, |_| View);
5808
5809        let observation_count = Rc::new(RefCell::new(0));
5810        observing_view.update(cx, |_, cx| {
5811            let observation_count = observation_count.clone();
5812            let subscription = Rc::new(RefCell::new(None));
5813            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
5814                let subscription = subscription.clone();
5815                move |_, _, _| {
5816                    subscription.borrow_mut().take();
5817                    *observation_count.borrow_mut() += 1;
5818                }
5819            }));
5820        });
5821
5822        observed_view.update(cx, |_, cx| {
5823            cx.notify();
5824        });
5825
5826        observed_view.update(cx, |_, cx| {
5827            cx.notify();
5828        });
5829
5830        assert_eq!(*observation_count.borrow(), 1);
5831
5832        // Global Observation
5833        let observation_count = Rc::new(RefCell::new(0));
5834        let subscription = Rc::new(RefCell::new(None));
5835        *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
5836            let observation_count = observation_count.clone();
5837            let subscription = subscription.clone();
5838            move |_| {
5839                subscription.borrow_mut().take();
5840                *observation_count.borrow_mut() += 1;
5841            }
5842        }));
5843
5844        cx.update(|cx| {
5845            cx.default_global::<()>();
5846            cx.set_global(());
5847        });
5848        assert_eq!(*observation_count.borrow(), 1);
5849    }
5850
5851    #[crate::test(self)]
5852    fn test_focus(cx: &mut TestAppContext) {
5853        struct View {
5854            name: String,
5855            events: Arc<Mutex<Vec<String>>>,
5856            child: Option<AnyViewHandle>,
5857        }
5858
5859        impl Entity for View {
5860            type Event = ();
5861        }
5862
5863        impl super::View for View {
5864            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
5865                self.child
5866                    .as_ref()
5867                    .map(|child| ChildView::new(child, cx).into_any())
5868                    .unwrap_or(Empty::new().into_any())
5869            }
5870
5871            fn ui_name() -> &'static str {
5872                "View"
5873            }
5874
5875            fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
5876                if cx.handle().id() == focused.id() {
5877                    self.events.lock().push(format!("{} focused", &self.name));
5878                }
5879            }
5880
5881            fn focus_out(&mut self, blurred: AnyViewHandle, cx: &mut ViewContext<Self>) {
5882                if cx.handle().id() == blurred.id() {
5883                    self.events.lock().push(format!("{} blurred", &self.name));
5884                }
5885            }
5886        }
5887
5888        let view_events: Arc<Mutex<Vec<String>>> = Default::default();
5889        let window = cx.add_window(|_| View {
5890            events: view_events.clone(),
5891            name: "view 1".to_string(),
5892            child: None,
5893        });
5894        let view_1 = window.root(cx);
5895        let view_2 = window.update(cx, |cx| {
5896            let view_2 = cx.add_view(|_| View {
5897                events: view_events.clone(),
5898                name: "view 2".to_string(),
5899                child: None,
5900            });
5901            view_1.update(cx, |view_1, cx| {
5902                view_1.child = Some(view_2.clone().into_any());
5903                cx.notify();
5904            });
5905            view_2
5906        });
5907
5908        let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
5909        view_1.update(cx, |_, cx| {
5910            cx.observe_focus(&view_2, {
5911                let observed_events = observed_events.clone();
5912                move |this, view, focused, cx| {
5913                    let label = if focused { "focus" } else { "blur" };
5914                    observed_events.lock().push(format!(
5915                        "{} observed {}'s {}",
5916                        this.name,
5917                        view.read(cx).name,
5918                        label
5919                    ))
5920                }
5921            })
5922            .detach();
5923        });
5924        view_2.update(cx, |_, cx| {
5925            cx.observe_focus(&view_1, {
5926                let observed_events = observed_events.clone();
5927                move |this, view, focused, cx| {
5928                    let label = if focused { "focus" } else { "blur" };
5929                    observed_events.lock().push(format!(
5930                        "{} observed {}'s {}",
5931                        this.name,
5932                        view.read(cx).name,
5933                        label
5934                    ))
5935                }
5936            })
5937            .detach();
5938        });
5939        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
5940        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
5941
5942        view_1.update(cx, |_, cx| {
5943            // Ensure only the last focus event is honored.
5944            cx.focus(&view_2);
5945            cx.focus(&view_1);
5946            cx.focus(&view_2);
5947        });
5948
5949        assert_eq!(
5950            mem::take(&mut *view_events.lock()),
5951            ["view 1 blurred", "view 2 focused"],
5952        );
5953        assert_eq!(
5954            mem::take(&mut *observed_events.lock()),
5955            [
5956                "view 2 observed view 1's blur",
5957                "view 1 observed view 2's focus"
5958            ]
5959        );
5960
5961        view_1.update(cx, |_, cx| cx.focus(&view_1));
5962        assert_eq!(
5963            mem::take(&mut *view_events.lock()),
5964            ["view 2 blurred", "view 1 focused"],
5965        );
5966        assert_eq!(
5967            mem::take(&mut *observed_events.lock()),
5968            [
5969                "view 1 observed view 2's blur",
5970                "view 2 observed view 1's focus"
5971            ]
5972        );
5973
5974        view_1.update(cx, |_, cx| cx.focus(&view_2));
5975        assert_eq!(
5976            mem::take(&mut *view_events.lock()),
5977            ["view 1 blurred", "view 2 focused"],
5978        );
5979        assert_eq!(
5980            mem::take(&mut *observed_events.lock()),
5981            [
5982                "view 2 observed view 1's blur",
5983                "view 1 observed view 2's focus"
5984            ]
5985        );
5986
5987        println!("=====================");
5988        view_1.update(cx, |view, _| {
5989            drop(view_2);
5990            view.child = None;
5991        });
5992        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
5993        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
5994    }
5995
5996    #[crate::test(self)]
5997    fn test_deserialize_actions(cx: &mut AppContext) {
5998        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
5999        pub struct ComplexAction {
6000            arg: String,
6001            count: usize,
6002        }
6003
6004        actions!(test::something, [SimpleAction]);
6005        impl_actions!(test::something, [ComplexAction]);
6006
6007        cx.add_global_action(move |_: &SimpleAction, _: &mut AppContext| {});
6008        cx.add_global_action(move |_: &ComplexAction, _: &mut AppContext| {});
6009
6010        let action1 = cx
6011            .deserialize_action(
6012                "test::something::ComplexAction",
6013                Some(serde_json::from_str(r#"{"arg": "a", "count": 5}"#).unwrap()),
6014            )
6015            .unwrap();
6016        let action2 = cx
6017            .deserialize_action("test::something::SimpleAction", None)
6018            .unwrap();
6019        assert_eq!(
6020            action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
6021            &ComplexAction {
6022                arg: "a".to_string(),
6023                count: 5,
6024            }
6025        );
6026        assert_eq!(
6027            action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
6028            &SimpleAction
6029        );
6030    }
6031
6032    #[crate::test(self)]
6033    fn test_dispatch_action(cx: &mut TestAppContext) {
6034        struct ViewA {
6035            id: usize,
6036            child: Option<AnyViewHandle>,
6037        }
6038
6039        impl Entity for ViewA {
6040            type Event = ();
6041        }
6042
6043        impl View for ViewA {
6044            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
6045                self.child
6046                    .as_ref()
6047                    .map(|child| ChildView::new(child, cx).into_any())
6048                    .unwrap_or(Empty::new().into_any())
6049            }
6050
6051            fn ui_name() -> &'static str {
6052                "View"
6053            }
6054        }
6055
6056        struct ViewB {
6057            id: usize,
6058            child: Option<AnyViewHandle>,
6059        }
6060
6061        impl Entity for ViewB {
6062            type Event = ();
6063        }
6064
6065        impl View for ViewB {
6066            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
6067                self.child
6068                    .as_ref()
6069                    .map(|child| ChildView::new(child, cx).into_any())
6070                    .unwrap_or(Empty::new().into_any())
6071            }
6072
6073            fn ui_name() -> &'static str {
6074                "View"
6075            }
6076        }
6077
6078        #[derive(Clone, Default, Deserialize, PartialEq)]
6079        pub struct Action(pub String);
6080
6081        impl_actions!(test, [Action]);
6082
6083        let actions = Rc::new(RefCell::new(Vec::new()));
6084        let observed_actions = Rc::new(RefCell::new(Vec::new()));
6085
6086        cx.update(|cx| {
6087            cx.add_global_action({
6088                let actions = actions.clone();
6089                move |_: &Action, _: &mut AppContext| {
6090                    actions.borrow_mut().push("global".to_string());
6091                }
6092            });
6093
6094            cx.add_action({
6095                let actions = actions.clone();
6096                move |view: &mut ViewA, action: &Action, cx| {
6097                    assert_eq!(action.0, "bar");
6098                    cx.propagate_action();
6099                    actions.borrow_mut().push(format!("{} a", view.id));
6100                }
6101            });
6102
6103            cx.add_action({
6104                let actions = actions.clone();
6105                move |view: &mut ViewA, _: &Action, cx| {
6106                    if view.id != 1 {
6107                        cx.add_view(|cx| {
6108                            cx.propagate_action(); // Still works on a nested ViewContext
6109                            ViewB { id: 5, child: None }
6110                        });
6111                    }
6112                    actions.borrow_mut().push(format!("{} b", view.id));
6113                }
6114            });
6115
6116            cx.add_action({
6117                let actions = actions.clone();
6118                move |view: &mut ViewB, _: &Action, cx| {
6119                    cx.propagate_action();
6120                    actions.borrow_mut().push(format!("{} c", view.id));
6121                }
6122            });
6123
6124            cx.add_action({
6125                let actions = actions.clone();
6126                move |view: &mut ViewB, _: &Action, cx| {
6127                    cx.propagate_action();
6128                    actions.borrow_mut().push(format!("{} d", view.id));
6129                }
6130            });
6131
6132            cx.capture_action({
6133                let actions = actions.clone();
6134                move |view: &mut ViewA, _: &Action, cx| {
6135                    cx.propagate_action();
6136                    actions.borrow_mut().push(format!("{} capture", view.id));
6137                }
6138            });
6139
6140            cx.observe_actions({
6141                let observed_actions = observed_actions.clone();
6142                move |action_id, _| observed_actions.borrow_mut().push(action_id)
6143            })
6144            .detach();
6145        });
6146
6147        let window = cx.add_window(|_| ViewA { id: 1, child: None });
6148        let view_1 = window.root(cx);
6149        let view_2 = window.update(cx, |cx| {
6150            let child = cx.add_view(|_| ViewB { id: 2, child: None });
6151            view_1.update(cx, |view, cx| {
6152                view.child = Some(child.clone().into_any());
6153                cx.notify();
6154            });
6155            child
6156        });
6157        let view_3 = window.update(cx, |cx| {
6158            let child = cx.add_view(|_| ViewA { id: 3, child: None });
6159            view_2.update(cx, |view, cx| {
6160                view.child = Some(child.clone().into_any());
6161                cx.notify();
6162            });
6163            child
6164        });
6165        let view_4 = window.update(cx, |cx| {
6166            let child = cx.add_view(|_| ViewB { id: 4, child: None });
6167            view_3.update(cx, |view, cx| {
6168                view.child = Some(child.clone().into_any());
6169                cx.notify();
6170            });
6171            child
6172        });
6173
6174        window.update(cx, |cx| {
6175            cx.dispatch_action(Some(view_4.id()), &Action("bar".to_string()))
6176        });
6177
6178        assert_eq!(
6179            *actions.borrow(),
6180            vec![
6181                "1 capture",
6182                "3 capture",
6183                "4 d",
6184                "4 c",
6185                "3 b",
6186                "3 a",
6187                "2 d",
6188                "2 c",
6189                "1 b"
6190            ]
6191        );
6192        assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
6193
6194        // Remove view_1, which doesn't propagate the action
6195
6196        let window = cx.add_window(|_| ViewB { id: 2, child: None });
6197        let view_2 = window.root(cx);
6198        let view_3 = window.update(cx, |cx| {
6199            let child = cx.add_view(|_| ViewA { id: 3, child: None });
6200            view_2.update(cx, |view, cx| {
6201                view.child = Some(child.clone().into_any());
6202                cx.notify();
6203            });
6204            child
6205        });
6206        let view_4 = window.update(cx, |cx| {
6207            let child = cx.add_view(|_| ViewB { id: 4, child: None });
6208            view_3.update(cx, |view, cx| {
6209                view.child = Some(child.clone().into_any());
6210                cx.notify();
6211            });
6212            child
6213        });
6214
6215        actions.borrow_mut().clear();
6216        window.update(cx, |cx| {
6217            cx.dispatch_action(Some(view_4.id()), &Action("bar".to_string()))
6218        });
6219
6220        assert_eq!(
6221            *actions.borrow(),
6222            vec![
6223                "3 capture",
6224                "4 d",
6225                "4 c",
6226                "3 b",
6227                "3 a",
6228                "2 d",
6229                "2 c",
6230                "global"
6231            ]
6232        );
6233        assert_eq!(
6234            *observed_actions.borrow(),
6235            [Action::default().id(), Action::default().id()]
6236        );
6237    }
6238
6239    #[crate::test(self)]
6240    fn test_dispatch_keystroke(cx: &mut AppContext) {
6241        #[derive(Clone, Deserialize, PartialEq)]
6242        pub struct Action(String);
6243
6244        impl_actions!(test, [Action]);
6245
6246        struct View {
6247            id: usize,
6248            keymap_context: KeymapContext,
6249            child: Option<AnyViewHandle>,
6250        }
6251
6252        impl Entity for View {
6253            type Event = ();
6254        }
6255
6256        impl super::View for View {
6257            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
6258                self.child
6259                    .as_ref()
6260                    .map(|child| ChildView::new(child, cx).into_any())
6261                    .unwrap_or(Empty::new().into_any())
6262            }
6263
6264            fn ui_name() -> &'static str {
6265                "View"
6266            }
6267
6268            fn update_keymap_context(&self, keymap: &mut KeymapContext, _: &AppContext) {
6269                *keymap = self.keymap_context.clone();
6270            }
6271        }
6272
6273        impl View {
6274            fn new(id: usize) -> Self {
6275                View {
6276                    id,
6277                    keymap_context: KeymapContext::default(),
6278                    child: None,
6279                }
6280            }
6281        }
6282
6283        let mut view_1 = View::new(1);
6284        let mut view_2 = View::new(2);
6285        let mut view_3 = View::new(3);
6286        view_1.keymap_context.add_identifier("a");
6287        view_2.keymap_context.add_identifier("a");
6288        view_2.keymap_context.add_identifier("b");
6289        view_3.keymap_context.add_identifier("a");
6290        view_3.keymap_context.add_identifier("b");
6291        view_3.keymap_context.add_identifier("c");
6292
6293        let window = cx.add_window(Default::default(), |cx| {
6294            let view_2 = cx.add_view(|cx| {
6295                let view_3 = cx.add_view(|cx| {
6296                    cx.focus_self();
6297                    view_3
6298                });
6299                view_2.child = Some(view_3.into_any());
6300                view_2
6301            });
6302            view_1.child = Some(view_2.into_any());
6303            view_1
6304        });
6305
6306        // This binding only dispatches an action on view 2 because that view will have
6307        // "a" and "b" in its context, but not "c".
6308        cx.add_bindings(vec![Binding::new(
6309            "a",
6310            Action("a".to_string()),
6311            Some("a && b && !c"),
6312        )]);
6313
6314        cx.add_bindings(vec![Binding::new("b", Action("b".to_string()), None)]);
6315
6316        // This binding only dispatches an action on views 2 and 3, because they have
6317        // a parent view with a in its context
6318        cx.add_bindings(vec![Binding::new(
6319            "c",
6320            Action("c".to_string()),
6321            Some("b > c"),
6322        )]);
6323
6324        // This binding only dispatches an action on view 2, because they have
6325        // a parent view with a in its context
6326        cx.add_bindings(vec![Binding::new(
6327            "d",
6328            Action("d".to_string()),
6329            Some("a && !b > b"),
6330        )]);
6331
6332        let actions = Rc::new(RefCell::new(Vec::new()));
6333        cx.add_action({
6334            let actions = actions.clone();
6335            move |view: &mut View, action: &Action, cx| {
6336                actions
6337                    .borrow_mut()
6338                    .push(format!("{} {}", view.id, action.0));
6339
6340                if action.0 == "b" {
6341                    cx.propagate_action();
6342                }
6343            }
6344        });
6345
6346        cx.add_global_action({
6347            let actions = actions.clone();
6348            move |action: &Action, _| {
6349                actions.borrow_mut().push(format!("global {}", action.0));
6350            }
6351        });
6352
6353        window.update(cx, |cx| {
6354            cx.dispatch_keystroke(&Keystroke::parse("a").unwrap())
6355        });
6356        assert_eq!(&*actions.borrow(), &["2 a"]);
6357        actions.borrow_mut().clear();
6358
6359        window.update(cx, |cx| {
6360            cx.dispatch_keystroke(&Keystroke::parse("b").unwrap());
6361        });
6362
6363        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
6364        actions.borrow_mut().clear();
6365
6366        window.update(cx, |cx| {
6367            cx.dispatch_keystroke(&Keystroke::parse("c").unwrap());
6368        });
6369        assert_eq!(&*actions.borrow(), &["3 c"]);
6370        actions.borrow_mut().clear();
6371
6372        window.update(cx, |cx| {
6373            cx.dispatch_keystroke(&Keystroke::parse("d").unwrap());
6374        });
6375        assert_eq!(&*actions.borrow(), &["2 d"]);
6376        actions.borrow_mut().clear();
6377    }
6378
6379    #[crate::test(self)]
6380    fn test_keystrokes_for_action(cx: &mut TestAppContext) {
6381        actions!(test, [Action1, Action2, GlobalAction]);
6382
6383        struct View1 {
6384            child: ViewHandle<View2>,
6385        }
6386        struct View2 {}
6387
6388        impl Entity for View1 {
6389            type Event = ();
6390        }
6391        impl Entity for View2 {
6392            type Event = ();
6393        }
6394
6395        impl super::View for View1 {
6396            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
6397                ChildView::new(&self.child, cx).into_any()
6398            }
6399            fn ui_name() -> &'static str {
6400                "View1"
6401            }
6402        }
6403        impl super::View for View2 {
6404            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6405                Empty::new().into_any()
6406            }
6407            fn ui_name() -> &'static str {
6408                "View2"
6409            }
6410        }
6411
6412        let window = cx.add_window(|cx| {
6413            let view_2 = cx.add_view(|cx| {
6414                cx.focus_self();
6415                View2 {}
6416            });
6417            View1 { child: view_2 }
6418        });
6419        let view_1 = window.root(cx);
6420        let view_2 = view_1.read_with(cx, |view, _| view.child.clone());
6421
6422        cx.update(|cx| {
6423            cx.add_action(|_: &mut View1, _: &Action1, _cx| {});
6424            cx.add_action(|_: &mut View2, _: &Action2, _cx| {});
6425            cx.add_global_action(|_: &GlobalAction, _| {});
6426            cx.add_bindings(vec![
6427                Binding::new("a", Action1, Some("View1")),
6428                Binding::new("b", Action2, Some("View1 > View2")),
6429                Binding::new("c", GlobalAction, Some("View3")), // View 3 does not exist
6430            ]);
6431        });
6432
6433        let view_1_id = view_1.id();
6434        view_1.update(cx, |_, cx| {
6435            view_2.update(cx, |_, cx| {
6436                // Sanity check
6437                let mut new_parents = Default::default();
6438                let mut notify_views_if_parents_change = Default::default();
6439                let mut layout_cx = LayoutContext::new(
6440                    cx,
6441                    &mut new_parents,
6442                    &mut notify_views_if_parents_change,
6443                    false,
6444                );
6445                assert_eq!(
6446                    layout_cx
6447                        .keystrokes_for_action(view_1_id, &Action1)
6448                        .unwrap()
6449                        .as_slice(),
6450                    &[Keystroke::parse("a").unwrap()]
6451                );
6452                assert_eq!(
6453                    layout_cx
6454                        .keystrokes_for_action(view_2.id(), &Action2)
6455                        .unwrap()
6456                        .as_slice(),
6457                    &[Keystroke::parse("b").unwrap()]
6458                );
6459
6460                // The 'a' keystroke propagates up the view tree from view_2
6461                // to view_1. The action, Action1, is handled by view_1.
6462                assert_eq!(
6463                    layout_cx
6464                        .keystrokes_for_action(view_2.id(), &Action1)
6465                        .unwrap()
6466                        .as_slice(),
6467                    &[Keystroke::parse("a").unwrap()]
6468                );
6469
6470                // Actions that are handled below the current view don't have bindings
6471                assert_eq!(layout_cx.keystrokes_for_action(view_1_id, &Action2), None);
6472
6473                // Actions that are handled in other branches of the tree should not have a binding
6474                assert_eq!(
6475                    layout_cx.keystrokes_for_action(view_2.id(), &GlobalAction),
6476                    None
6477                );
6478            });
6479        });
6480
6481        // Check that global actions do not have a binding, even if a binding does exist in another view
6482        assert_eq!(
6483            &available_actions(window.into(), view_1.id(), cx),
6484            &[
6485                ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
6486                ("test::GlobalAction", vec![])
6487            ],
6488        );
6489
6490        // Check that view 1 actions and bindings are available even when called from view 2
6491        assert_eq!(
6492            &available_actions(window.into(), view_2.id(), cx),
6493            &[
6494                ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
6495                ("test::Action2", vec![Keystroke::parse("b").unwrap()]),
6496                ("test::GlobalAction", vec![]),
6497            ],
6498        );
6499
6500        // Produces a list of actions and key bindings
6501        fn available_actions(
6502            window: AnyWindowHandle,
6503            view_id: usize,
6504            cx: &TestAppContext,
6505        ) -> Vec<(&'static str, Vec<Keystroke>)> {
6506            cx.available_actions(window.into(), view_id)
6507                .into_iter()
6508                .map(|(action_name, _, bindings)| {
6509                    (
6510                        action_name,
6511                        bindings
6512                            .iter()
6513                            .map(|binding| binding.keystrokes()[0].clone())
6514                            .collect::<Vec<_>>(),
6515                    )
6516                })
6517                .sorted_by(|(name1, _), (name2, _)| name1.cmp(name2))
6518                .collect()
6519        }
6520    }
6521
6522    #[crate::test(self)]
6523    fn test_keystrokes_for_action_with_data(cx: &mut TestAppContext) {
6524        #[derive(Clone, Debug, Deserialize, PartialEq)]
6525        struct ActionWithArg {
6526            #[serde(default)]
6527            arg: bool,
6528        }
6529
6530        struct View;
6531        impl super::Entity for View {
6532            type Event = ();
6533        }
6534        impl super::View for View {
6535            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6536                Empty::new().into_any()
6537            }
6538            fn ui_name() -> &'static str {
6539                "View"
6540            }
6541        }
6542
6543        impl_actions!(test, [ActionWithArg]);
6544
6545        let window = cx.add_window(|_| View);
6546        let view = window.root(cx);
6547        cx.update(|cx| {
6548            cx.add_global_action(|_: &ActionWithArg, _| {});
6549            cx.add_bindings(vec![
6550                Binding::new("a", ActionWithArg { arg: false }, None),
6551                Binding::new("shift-a", ActionWithArg { arg: true }, None),
6552            ]);
6553        });
6554
6555        let actions = cx.available_actions(window.into(), view.id());
6556        assert_eq!(
6557            actions[0].1.as_any().downcast_ref::<ActionWithArg>(),
6558            Some(&ActionWithArg { arg: false })
6559        );
6560        assert_eq!(
6561            actions[0]
6562                .2
6563                .iter()
6564                .map(|b| b.keystrokes()[0].clone())
6565                .collect::<Vec<_>>(),
6566            vec![Keystroke::parse("a").unwrap()],
6567        );
6568    }
6569
6570    #[crate::test(self)]
6571    async fn test_model_condition(cx: &mut TestAppContext) {
6572        struct Counter(usize);
6573
6574        impl super::Entity for Counter {
6575            type Event = ();
6576        }
6577
6578        impl Counter {
6579            fn inc(&mut self, cx: &mut ModelContext<Self>) {
6580                self.0 += 1;
6581                cx.notify();
6582            }
6583        }
6584
6585        let model = cx.add_model(|_| Counter(0));
6586
6587        let condition1 = model.condition(cx, |model, _| model.0 == 2);
6588        let condition2 = model.condition(cx, |model, _| model.0 == 3);
6589        smol::pin!(condition1, condition2);
6590
6591        model.update(cx, |model, cx| model.inc(cx));
6592        assert_eq!(poll_once(&mut condition1).await, None);
6593        assert_eq!(poll_once(&mut condition2).await, None);
6594
6595        model.update(cx, |model, cx| model.inc(cx));
6596        assert_eq!(poll_once(&mut condition1).await, Some(()));
6597        assert_eq!(poll_once(&mut condition2).await, None);
6598
6599        model.update(cx, |model, cx| model.inc(cx));
6600        assert_eq!(poll_once(&mut condition2).await, Some(()));
6601
6602        model.update(cx, |_, cx| cx.notify());
6603    }
6604
6605    #[crate::test(self)]
6606    #[should_panic]
6607    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
6608        struct Model;
6609
6610        impl super::Entity for Model {
6611            type Event = ();
6612        }
6613
6614        let model = cx.add_model(|_| Model);
6615        model.condition(cx, |_, _| false).await;
6616    }
6617
6618    #[crate::test(self)]
6619    #[should_panic(expected = "model dropped with pending condition")]
6620    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
6621        struct Model;
6622
6623        impl super::Entity for Model {
6624            type Event = ();
6625        }
6626
6627        let model = cx.add_model(|_| Model);
6628        let condition = model.condition(cx, |_, _| false);
6629        cx.update(|_| drop(model));
6630        condition.await;
6631    }
6632
6633    #[crate::test(self)]
6634    async fn test_view_condition(cx: &mut TestAppContext) {
6635        struct Counter(usize);
6636
6637        impl super::Entity for Counter {
6638            type Event = ();
6639        }
6640
6641        impl super::View for Counter {
6642            fn ui_name() -> &'static str {
6643                "test view"
6644            }
6645
6646            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6647                Empty::new().into_any()
6648            }
6649        }
6650
6651        impl Counter {
6652            fn inc(&mut self, cx: &mut ViewContext<Self>) {
6653                self.0 += 1;
6654                cx.notify();
6655            }
6656        }
6657
6658        let window = cx.add_window(|_| Counter(0));
6659        let view = window.root(cx);
6660
6661        let condition1 = view.condition(cx, |view, _| view.0 == 2);
6662        let condition2 = view.condition(cx, |view, _| view.0 == 3);
6663        smol::pin!(condition1, condition2);
6664
6665        view.update(cx, |view, cx| view.inc(cx));
6666        assert_eq!(poll_once(&mut condition1).await, None);
6667        assert_eq!(poll_once(&mut condition2).await, None);
6668
6669        view.update(cx, |view, cx| view.inc(cx));
6670        assert_eq!(poll_once(&mut condition1).await, Some(()));
6671        assert_eq!(poll_once(&mut condition2).await, None);
6672
6673        view.update(cx, |view, cx| view.inc(cx));
6674        assert_eq!(poll_once(&mut condition2).await, Some(()));
6675        view.update(cx, |_, cx| cx.notify());
6676    }
6677
6678    #[crate::test(self)]
6679    #[should_panic]
6680    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
6681        let window = cx.add_window(|_| TestView::default());
6682        window.root(cx).condition(cx, |_, _| false).await;
6683    }
6684
6685    #[crate::test(self)]
6686    #[should_panic(expected = "view dropped with pending condition")]
6687    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
6688        let window = cx.add_window(|_| TestView::default());
6689        let view = window.add_view(cx, |_| TestView::default());
6690
6691        let condition = view.condition(cx, |_, _| false);
6692        cx.update(|_| drop(view));
6693        condition.await;
6694    }
6695
6696    #[crate::test(self)]
6697    fn test_refresh_windows(cx: &mut TestAppContext) {
6698        struct View(usize);
6699
6700        impl super::Entity for View {
6701            type Event = ();
6702        }
6703
6704        impl super::View for View {
6705            fn ui_name() -> &'static str {
6706                "test view"
6707            }
6708
6709            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6710                Empty::new().into_any_named(format!("render count: {}", post_inc(&mut self.0)))
6711            }
6712        }
6713
6714        let window = cx.add_window(|_| View(0));
6715        let root_view = window.root(cx);
6716        window.update(cx, |cx| {
6717            assert_eq!(
6718                cx.window.rendered_views[&root_view.id()].name(),
6719                Some("render count: 0")
6720            );
6721        });
6722
6723        let view = window.update(cx, |cx| {
6724            cx.refresh_windows();
6725            cx.add_view(|_| View(0))
6726        });
6727
6728        window.update(cx, |cx| {
6729            assert_eq!(
6730                cx.window.rendered_views[&root_view.id()].name(),
6731                Some("render count: 1")
6732            );
6733            assert_eq!(
6734                cx.window.rendered_views[&view.id()].name(),
6735                Some("render count: 0")
6736            );
6737        });
6738
6739        cx.update(|cx| cx.refresh_windows());
6740
6741        window.update(cx, |cx| {
6742            assert_eq!(
6743                cx.window.rendered_views[&root_view.id()].name(),
6744                Some("render count: 2")
6745            );
6746            assert_eq!(
6747                cx.window.rendered_views[&view.id()].name(),
6748                Some("render count: 1")
6749            );
6750        });
6751
6752        cx.update(|cx| {
6753            cx.refresh_windows();
6754            drop(view);
6755        });
6756
6757        window.update(cx, |cx| {
6758            assert_eq!(
6759                cx.window.rendered_views[&root_view.id()].name(),
6760                Some("render count: 3")
6761            );
6762            assert_eq!(cx.window.rendered_views.len(), 1);
6763        });
6764    }
6765
6766    #[crate::test(self)]
6767    async fn test_labeled_tasks(cx: &mut TestAppContext) {
6768        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6769        let (mut sender, mut receiver) = postage::oneshot::channel::<()>();
6770        let task = cx
6771            .update(|cx| cx.spawn_labeled("Test Label", |_| async move { receiver.recv().await }));
6772
6773        assert_eq!(
6774            Some("Test Label"),
6775            cx.update(|cx| cx.active_labeled_tasks().next())
6776        );
6777        sender
6778            .send(())
6779            .await
6780            .expect("Could not send message to complete task");
6781        task.await;
6782
6783        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6784    }
6785
6786    #[crate::test(self)]
6787    async fn test_window_activation(cx: &mut TestAppContext) {
6788        struct View(&'static str);
6789
6790        impl super::Entity for View {
6791            type Event = ();
6792        }
6793
6794        impl super::View for View {
6795            fn ui_name() -> &'static str {
6796                "test view"
6797            }
6798
6799            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6800                Empty::new().into_any()
6801            }
6802        }
6803
6804        let events = Rc::new(RefCell::new(Vec::new()));
6805        let window_1 = cx.add_window(|cx: &mut ViewContext<View>| {
6806            cx.observe_window_activation({
6807                let events = events.clone();
6808                move |this, active, _| events.borrow_mut().push((this.0, active))
6809            })
6810            .detach();
6811            View("window 1")
6812        });
6813        assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
6814
6815        let window_2 = cx.add_window(|cx: &mut ViewContext<View>| {
6816            cx.observe_window_activation({
6817                let events = events.clone();
6818                move |this, active, _| events.borrow_mut().push((this.0, active))
6819            })
6820            .detach();
6821            View("window 2")
6822        });
6823        assert_eq!(
6824            mem::take(&mut *events.borrow_mut()),
6825            [("window 1", false), ("window 2", true)]
6826        );
6827
6828        let window_3 = cx.add_window(|cx: &mut ViewContext<View>| {
6829            cx.observe_window_activation({
6830                let events = events.clone();
6831                move |this, active, _| events.borrow_mut().push((this.0, active))
6832            })
6833            .detach();
6834            View("window 3")
6835        });
6836        assert_eq!(
6837            mem::take(&mut *events.borrow_mut()),
6838            [("window 2", false), ("window 3", true)]
6839        );
6840
6841        window_2.simulate_activation(cx);
6842        assert_eq!(
6843            mem::take(&mut *events.borrow_mut()),
6844            [("window 3", false), ("window 2", true)]
6845        );
6846
6847        window_1.simulate_activation(cx);
6848        assert_eq!(
6849            mem::take(&mut *events.borrow_mut()),
6850            [("window 2", false), ("window 1", true)]
6851        );
6852
6853        window_3.simulate_activation(cx);
6854        assert_eq!(
6855            mem::take(&mut *events.borrow_mut()),
6856            [("window 1", false), ("window 3", true)]
6857        );
6858
6859        window_3.simulate_activation(cx);
6860        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6861    }
6862
6863    #[crate::test(self)]
6864    fn test_child_view(cx: &mut TestAppContext) {
6865        struct Child {
6866            rendered: Rc<Cell<bool>>,
6867            dropped: Rc<Cell<bool>>,
6868        }
6869
6870        impl super::Entity for Child {
6871            type Event = ();
6872        }
6873
6874        impl super::View for Child {
6875            fn ui_name() -> &'static str {
6876                "child view"
6877            }
6878
6879            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6880                self.rendered.set(true);
6881                Empty::new().into_any()
6882            }
6883        }
6884
6885        impl Drop for Child {
6886            fn drop(&mut self) {
6887                self.dropped.set(true);
6888            }
6889        }
6890
6891        struct Parent {
6892            child: Option<ViewHandle<Child>>,
6893        }
6894
6895        impl super::Entity for Parent {
6896            type Event = ();
6897        }
6898
6899        impl super::View for Parent {
6900            fn ui_name() -> &'static str {
6901                "parent view"
6902            }
6903
6904            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
6905                if let Some(child) = self.child.as_ref() {
6906                    ChildView::new(child, cx).into_any()
6907                } else {
6908                    Empty::new().into_any()
6909                }
6910            }
6911        }
6912
6913        let child_rendered = Rc::new(Cell::new(false));
6914        let child_dropped = Rc::new(Cell::new(false));
6915        let window = cx.add_window(|cx| Parent {
6916            child: Some(cx.add_view(|_| Child {
6917                rendered: child_rendered.clone(),
6918                dropped: child_dropped.clone(),
6919            })),
6920        });
6921        let root_view = window.root(cx);
6922        assert!(child_rendered.take());
6923        assert!(!child_dropped.take());
6924
6925        root_view.update(cx, |view, cx| {
6926            view.child.take();
6927            cx.notify();
6928        });
6929        assert!(!child_rendered.take());
6930        assert!(child_dropped.take());
6931    }
6932
6933    #[derive(Default)]
6934    struct TestView {
6935        events: Vec<String>,
6936    }
6937
6938    impl Entity for TestView {
6939        type Event = String;
6940    }
6941
6942    impl View for TestView {
6943        fn ui_name() -> &'static str {
6944            "TestView"
6945        }
6946
6947        fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6948            Empty::new().into_any()
6949        }
6950    }
6951}