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