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