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