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, B>(
4684        &self,
4685        cx: &mut B,
4686        update: impl FnOnce(&mut V, &mut ViewContext<V>) -> T,
4687    ) -> Result<T>
4688    where
4689        B: BorrowWindowContext,
4690        B::Result<Option<T>>: Flatten<T>,
4691    {
4692        cx.update_window(self.window(), |cx| {
4693            cx.upgrade_view_handle(self)
4694                .map(|handle| handle.update(cx, update))
4695        })
4696        .flatten()
4697        .ok_or_else(|| anyhow!("window was removed"))
4698    }
4699}
4700
4701pub trait Flatten<T> {
4702    fn flatten(self) -> Option<T>;
4703}
4704
4705impl<T> Flatten<T> for Option<Option<T>> {
4706    fn flatten(self) -> Option<T> {
4707        self.flatten()
4708    }
4709}
4710
4711impl<T> Flatten<T> for Option<T> {
4712    fn flatten(self) -> Option<T> {
4713        self
4714    }
4715}
4716
4717impl<V> Deref for WeakViewHandle<V> {
4718    type Target = AnyWeakViewHandle;
4719
4720    fn deref(&self) -> &Self::Target {
4721        &self.any_handle
4722    }
4723}
4724
4725impl<V> Clone for WeakViewHandle<V> {
4726    fn clone(&self) -> Self {
4727        Self {
4728            any_handle: self.any_handle.clone(),
4729            view_type: PhantomData,
4730        }
4731    }
4732}
4733
4734impl<T> PartialEq for WeakViewHandle<T> {
4735    fn eq(&self, other: &Self) -> bool {
4736        self.window == other.window && self.view_id == other.view_id
4737    }
4738}
4739
4740impl<T> Eq for WeakViewHandle<T> {}
4741
4742impl<T> Hash for WeakViewHandle<T> {
4743    fn hash<H: Hasher>(&self, state: &mut H) {
4744        self.any_handle.hash(state);
4745    }
4746}
4747
4748#[derive(Debug, Clone, Copy, Eq, PartialEq)]
4749pub struct AnyWeakViewHandle {
4750    window: AnyWindowHandle,
4751    view_id: usize,
4752    view_type: TypeId,
4753}
4754
4755impl AnyWeakViewHandle {
4756    pub fn id(&self) -> usize {
4757        self.view_id
4758    }
4759
4760    fn is<T: 'static>(&self) -> bool {
4761        TypeId::of::<T>() == self.view_type
4762    }
4763
4764    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<AnyViewHandle> {
4765        cx.read_with(|cx| cx.upgrade_any_view_handle(self))
4766    }
4767
4768    pub fn downcast<T: View>(self) -> Option<WeakViewHandle<T>> {
4769        if self.is::<T>() {
4770            Some(WeakViewHandle {
4771                any_handle: self,
4772                view_type: PhantomData,
4773            })
4774        } else {
4775            None
4776        }
4777    }
4778}
4779
4780impl Hash for AnyWeakViewHandle {
4781    fn hash<H: Hasher>(&self, state: &mut H) {
4782        self.window.hash(state);
4783        self.view_id.hash(state);
4784        self.view_type.hash(state);
4785    }
4786}
4787
4788#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4789pub struct ElementStateId {
4790    view_id: usize,
4791    element_id: usize,
4792    tag: TypeId,
4793}
4794
4795pub struct ElementStateHandle<T> {
4796    value_type: PhantomData<T>,
4797    id: ElementStateId,
4798    ref_counts: Weak<Mutex<RefCounts>>,
4799}
4800
4801impl<T: 'static> ElementStateHandle<T> {
4802    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4803        ref_counts.lock().inc_element_state(id, frame_id);
4804        Self {
4805            value_type: PhantomData,
4806            id,
4807            ref_counts: Arc::downgrade(ref_counts),
4808        }
4809    }
4810
4811    pub fn id(&self) -> ElementStateId {
4812        self.id
4813    }
4814
4815    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
4816        cx.element_states
4817            .get(&self.id)
4818            .unwrap()
4819            .downcast_ref()
4820            .unwrap()
4821    }
4822
4823    pub fn update<C, D, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
4824    where
4825        C: DerefMut<Target = D>,
4826        D: DerefMut<Target = AppContext>,
4827    {
4828        let mut element_state = cx.deref_mut().element_states.remove(&self.id).unwrap();
4829        let result = f(element_state.downcast_mut().unwrap(), cx);
4830        cx.deref_mut().element_states.insert(self.id, element_state);
4831        result
4832    }
4833}
4834
4835impl<T> Drop for ElementStateHandle<T> {
4836    fn drop(&mut self) {
4837        if let Some(ref_counts) = self.ref_counts.upgrade() {
4838            ref_counts.lock().dec_element_state(self.id);
4839        }
4840    }
4841}
4842
4843#[must_use]
4844pub enum Subscription {
4845    Subscription(callback_collection::Subscription<usize, SubscriptionCallback>),
4846    Observation(callback_collection::Subscription<usize, ObservationCallback>),
4847    GlobalSubscription(callback_collection::Subscription<TypeId, GlobalSubscriptionCallback>),
4848    GlobalObservation(callback_collection::Subscription<TypeId, GlobalObservationCallback>),
4849    FocusObservation(callback_collection::Subscription<usize, FocusObservationCallback>),
4850    WindowActivationObservation(
4851        callback_collection::Subscription<AnyWindowHandle, WindowActivationCallback>,
4852    ),
4853    WindowFullscreenObservation(
4854        callback_collection::Subscription<AnyWindowHandle, WindowFullscreenCallback>,
4855    ),
4856    WindowBoundsObservation(
4857        callback_collection::Subscription<AnyWindowHandle, WindowBoundsCallback>,
4858    ),
4859    KeystrokeObservation(callback_collection::Subscription<AnyWindowHandle, KeystrokeCallback>),
4860    ReleaseObservation(callback_collection::Subscription<usize, ReleaseObservationCallback>),
4861    ActionObservation(callback_collection::Subscription<(), ActionObservationCallback>),
4862    ActiveLabeledTasksObservation(
4863        callback_collection::Subscription<(), ActiveLabeledTasksCallback>,
4864    ),
4865}
4866
4867impl Subscription {
4868    pub fn id(&self) -> usize {
4869        match self {
4870            Subscription::Subscription(subscription) => subscription.id(),
4871            Subscription::Observation(subscription) => subscription.id(),
4872            Subscription::GlobalSubscription(subscription) => subscription.id(),
4873            Subscription::GlobalObservation(subscription) => subscription.id(),
4874            Subscription::FocusObservation(subscription) => subscription.id(),
4875            Subscription::WindowActivationObservation(subscription) => subscription.id(),
4876            Subscription::WindowFullscreenObservation(subscription) => subscription.id(),
4877            Subscription::WindowBoundsObservation(subscription) => subscription.id(),
4878            Subscription::KeystrokeObservation(subscription) => subscription.id(),
4879            Subscription::ReleaseObservation(subscription) => subscription.id(),
4880            Subscription::ActionObservation(subscription) => subscription.id(),
4881            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.id(),
4882        }
4883    }
4884
4885    pub fn detach(&mut self) {
4886        match self {
4887            Subscription::Subscription(subscription) => subscription.detach(),
4888            Subscription::GlobalSubscription(subscription) => subscription.detach(),
4889            Subscription::Observation(subscription) => subscription.detach(),
4890            Subscription::GlobalObservation(subscription) => subscription.detach(),
4891            Subscription::FocusObservation(subscription) => subscription.detach(),
4892            Subscription::KeystrokeObservation(subscription) => subscription.detach(),
4893            Subscription::WindowActivationObservation(subscription) => subscription.detach(),
4894            Subscription::WindowFullscreenObservation(subscription) => subscription.detach(),
4895            Subscription::WindowBoundsObservation(subscription) => subscription.detach(),
4896            Subscription::ReleaseObservation(subscription) => subscription.detach(),
4897            Subscription::ActionObservation(subscription) => subscription.detach(),
4898            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.detach(),
4899        }
4900    }
4901}
4902
4903#[cfg(test)]
4904mod tests {
4905    use super::*;
4906    use crate::{
4907        actions,
4908        elements::*,
4909        impl_actions,
4910        platform::{MouseButton, MouseButtonEvent},
4911        window::ChildView,
4912    };
4913    use itertools::Itertools;
4914    use postage::{sink::Sink, stream::Stream};
4915    use serde::Deserialize;
4916    use smol::future::poll_once;
4917    use std::{
4918        cell::Cell,
4919        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
4920    };
4921
4922    #[crate::test(self)]
4923    fn test_model_handles(cx: &mut AppContext) {
4924        struct Model {
4925            other: Option<ModelHandle<Model>>,
4926            events: Vec<String>,
4927        }
4928
4929        impl Entity for Model {
4930            type Event = usize;
4931        }
4932
4933        impl Model {
4934            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
4935                if let Some(other) = other.as_ref() {
4936                    cx.observe(other, |me, _, _| {
4937                        me.events.push("notified".into());
4938                    })
4939                    .detach();
4940                    cx.subscribe(other, |me, _, event, _| {
4941                        me.events.push(format!("observed event {}", event));
4942                    })
4943                    .detach();
4944                }
4945
4946                Self {
4947                    other,
4948                    events: Vec::new(),
4949                }
4950            }
4951        }
4952
4953        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
4954        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
4955        assert_eq!(cx.models.len(), 2);
4956
4957        handle_1.update(cx, |model, cx| {
4958            model.events.push("updated".into());
4959            cx.emit(1);
4960            cx.notify();
4961            cx.emit(2);
4962        });
4963        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4964        assert_eq!(
4965            handle_2.read(cx).events,
4966            vec![
4967                "observed event 1".to_string(),
4968                "notified".to_string(),
4969                "observed event 2".to_string(),
4970            ]
4971        );
4972
4973        handle_2.update(cx, |model, _| {
4974            drop(handle_1);
4975            model.other.take();
4976        });
4977
4978        assert_eq!(cx.models.len(), 1);
4979        assert!(cx.subscriptions.is_empty());
4980        assert!(cx.observations.is_empty());
4981    }
4982
4983    #[crate::test(self)]
4984    fn test_model_events(cx: &mut AppContext) {
4985        #[derive(Default)]
4986        struct Model {
4987            events: Vec<usize>,
4988        }
4989
4990        impl Entity for Model {
4991            type Event = usize;
4992        }
4993
4994        let handle_1 = cx.add_model(|_| Model::default());
4995        let handle_2 = cx.add_model(|_| Model::default());
4996
4997        handle_1.update(cx, |_, cx| {
4998            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
4999                model.events.push(*event);
5000
5001                cx.subscribe(&emitter, |model, _, event, _| {
5002                    model.events.push(*event * 2);
5003                })
5004                .detach();
5005            })
5006            .detach();
5007        });
5008
5009        handle_2.update(cx, |_, c| c.emit(7));
5010        assert_eq!(handle_1.read(cx).events, vec![7]);
5011
5012        handle_2.update(cx, |_, c| c.emit(5));
5013        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
5014    }
5015
5016    #[crate::test(self)]
5017    fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
5018        #[derive(Default)]
5019        struct Model;
5020
5021        impl Entity for Model {
5022            type Event = ();
5023        }
5024
5025        let events = Rc::new(RefCell::new(Vec::new()));
5026        cx.add_model(|cx| {
5027            drop(cx.subscribe(&cx.handle(), {
5028                let events = events.clone();
5029                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
5030            }));
5031            cx.subscribe(&cx.handle(), {
5032                let events = events.clone();
5033                move |_, _, _, _| events.borrow_mut().push("before emit")
5034            })
5035            .detach();
5036            cx.emit(());
5037            cx.subscribe(&cx.handle(), {
5038                let events = events.clone();
5039                move |_, _, _, _| events.borrow_mut().push("after emit")
5040            })
5041            .detach();
5042            Model
5043        });
5044        assert_eq!(*events.borrow(), ["before emit"]);
5045    }
5046
5047    #[crate::test(self)]
5048    fn test_observe_and_notify_from_model(cx: &mut AppContext) {
5049        #[derive(Default)]
5050        struct Model {
5051            count: usize,
5052            events: Vec<usize>,
5053        }
5054
5055        impl Entity for Model {
5056            type Event = ();
5057        }
5058
5059        let handle_1 = cx.add_model(|_| Model::default());
5060        let handle_2 = cx.add_model(|_| Model::default());
5061
5062        handle_1.update(cx, |_, c| {
5063            c.observe(&handle_2, move |model, observed, c| {
5064                model.events.push(observed.read(c).count);
5065                c.observe(&observed, |model, observed, c| {
5066                    model.events.push(observed.read(c).count * 2);
5067                })
5068                .detach();
5069            })
5070            .detach();
5071        });
5072
5073        handle_2.update(cx, |model, c| {
5074            model.count = 7;
5075            c.notify()
5076        });
5077        assert_eq!(handle_1.read(cx).events, vec![7]);
5078
5079        handle_2.update(cx, |model, c| {
5080            model.count = 5;
5081            c.notify()
5082        });
5083        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
5084    }
5085
5086    #[crate::test(self)]
5087    fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
5088        #[derive(Default)]
5089        struct Model;
5090
5091        impl Entity for Model {
5092            type Event = ();
5093        }
5094
5095        let events = Rc::new(RefCell::new(Vec::new()));
5096        cx.add_model(|cx| {
5097            drop(cx.observe(&cx.handle(), {
5098                let events = events.clone();
5099                move |_, _, _| events.borrow_mut().push("dropped before flush")
5100            }));
5101            cx.observe(&cx.handle(), {
5102                let events = events.clone();
5103                move |_, _, _| events.borrow_mut().push("before notify")
5104            })
5105            .detach();
5106            cx.notify();
5107            cx.observe(&cx.handle(), {
5108                let events = events.clone();
5109                move |_, _, _| events.borrow_mut().push("after notify")
5110            })
5111            .detach();
5112            Model
5113        });
5114        assert_eq!(*events.borrow(), ["before notify"]);
5115    }
5116
5117    #[crate::test(self)]
5118    fn test_defer_and_after_window_update(cx: &mut TestAppContext) {
5119        struct View {
5120            render_count: usize,
5121        }
5122
5123        impl Entity for View {
5124            type Event = usize;
5125        }
5126
5127        impl super::View for View {
5128            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5129                post_inc(&mut self.render_count);
5130                Empty::new().into_any()
5131            }
5132
5133            fn ui_name() -> &'static str {
5134                "View"
5135            }
5136        }
5137
5138        let window = cx.add_window(|_| View { render_count: 0 });
5139        let called_defer = Rc::new(AtomicBool::new(false));
5140        let called_after_window_update = Rc::new(AtomicBool::new(false));
5141
5142        window.root(cx).update(cx, |this, cx| {
5143            assert_eq!(this.render_count, 1);
5144            cx.defer({
5145                let called_defer = called_defer.clone();
5146                move |this, _| {
5147                    assert_eq!(this.render_count, 1);
5148                    called_defer.store(true, SeqCst);
5149                }
5150            });
5151            cx.after_window_update({
5152                let called_after_window_update = called_after_window_update.clone();
5153                move |this, cx| {
5154                    assert_eq!(this.render_count, 2);
5155                    called_after_window_update.store(true, SeqCst);
5156                    cx.notify();
5157                }
5158            });
5159            assert!(!called_defer.load(SeqCst));
5160            assert!(!called_after_window_update.load(SeqCst));
5161            cx.notify();
5162        });
5163
5164        assert!(called_defer.load(SeqCst));
5165        assert!(called_after_window_update.load(SeqCst));
5166        assert_eq!(window.read_root_with(cx, |view, _| view.render_count), 3);
5167    }
5168
5169    #[crate::test(self)]
5170    fn test_view_handles(cx: &mut TestAppContext) {
5171        struct View {
5172            other: Option<ViewHandle<View>>,
5173            events: Vec<String>,
5174        }
5175
5176        impl Entity for View {
5177            type Event = usize;
5178        }
5179
5180        impl super::View for View {
5181            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5182                Empty::new().into_any()
5183            }
5184
5185            fn ui_name() -> &'static str {
5186                "View"
5187            }
5188        }
5189
5190        impl View {
5191            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
5192                if let Some(other) = other.as_ref() {
5193                    cx.subscribe(other, |me, _, event, _| {
5194                        me.events.push(format!("observed event {}", event));
5195                    })
5196                    .detach();
5197                }
5198                Self {
5199                    other,
5200                    events: Vec::new(),
5201                }
5202            }
5203        }
5204
5205        let window = cx.add_window(|cx| View::new(None, cx));
5206        let handle_1 = window.add_view(cx, |cx| View::new(None, cx));
5207        let handle_2 = window.add_view(cx, |cx| View::new(Some(handle_1.clone()), cx));
5208        assert_eq!(cx.read(|cx| cx.views.len()), 3);
5209
5210        handle_1.update(cx, |view, cx| {
5211            view.events.push("updated".into());
5212            cx.emit(1);
5213            cx.emit(2);
5214        });
5215        handle_1.read_with(cx, |view, _| {
5216            assert_eq!(view.events, vec!["updated".to_string()]);
5217        });
5218        handle_2.read_with(cx, |view, _| {
5219            assert_eq!(
5220                view.events,
5221                vec![
5222                    "observed event 1".to_string(),
5223                    "observed event 2".to_string(),
5224                ]
5225            );
5226        });
5227
5228        handle_2.update(cx, |view, _| {
5229            drop(handle_1);
5230            view.other.take();
5231        });
5232
5233        cx.read(|cx| {
5234            assert_eq!(cx.views.len(), 2);
5235            assert!(cx.subscriptions.is_empty());
5236            assert!(cx.observations.is_empty());
5237        });
5238    }
5239
5240    #[crate::test(self)]
5241    fn test_add_window(cx: &mut AppContext) {
5242        struct View {
5243            mouse_down_count: Arc<AtomicUsize>,
5244        }
5245
5246        impl Entity for View {
5247            type Event = ();
5248        }
5249
5250        impl super::View for View {
5251            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
5252                enum Handler {}
5253                let mouse_down_count = self.mouse_down_count.clone();
5254                MouseEventHandler::<Handler, _>::new(0, cx, |_, _| Empty::new())
5255                    .on_down(MouseButton::Left, move |_, _, _| {
5256                        mouse_down_count.fetch_add(1, SeqCst);
5257                    })
5258                    .into_any()
5259            }
5260
5261            fn ui_name() -> &'static str {
5262                "View"
5263            }
5264        }
5265
5266        let mouse_down_count = Arc::new(AtomicUsize::new(0));
5267        let window = cx.add_window(Default::default(), |_| View {
5268            mouse_down_count: mouse_down_count.clone(),
5269        });
5270
5271        window.update(cx, |cx| {
5272            // Ensure window's root element is in a valid lifecycle state.
5273            cx.dispatch_event(
5274                Event::MouseDown(MouseButtonEvent {
5275                    position: Default::default(),
5276                    button: MouseButton::Left,
5277                    modifiers: Default::default(),
5278                    click_count: 1,
5279                    is_down: true,
5280                }),
5281                false,
5282            );
5283            assert_eq!(mouse_down_count.load(SeqCst), 1);
5284        });
5285    }
5286
5287    #[crate::test(self)]
5288    fn test_entity_release_hooks(cx: &mut TestAppContext) {
5289        struct Model {
5290            released: Rc<Cell<bool>>,
5291        }
5292
5293        struct View {
5294            released: Rc<Cell<bool>>,
5295        }
5296
5297        impl Entity for Model {
5298            type Event = ();
5299
5300            fn release(&mut self, _: &mut AppContext) {
5301                self.released.set(true);
5302            }
5303        }
5304
5305        impl Entity for View {
5306            type Event = ();
5307
5308            fn release(&mut self, _: &mut AppContext) {
5309                self.released.set(true);
5310            }
5311        }
5312
5313        impl super::View for View {
5314            fn ui_name() -> &'static str {
5315                "View"
5316            }
5317
5318            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5319                Empty::new().into_any()
5320            }
5321        }
5322
5323        let model_released = Rc::new(Cell::new(false));
5324        let model_release_observed = Rc::new(Cell::new(false));
5325        let view_released = Rc::new(Cell::new(false));
5326        let view_release_observed = Rc::new(Cell::new(false));
5327
5328        let model = cx.add_model(|_| Model {
5329            released: model_released.clone(),
5330        });
5331        let window = cx.add_window(|_| View {
5332            released: view_released.clone(),
5333        });
5334        let view = window.root(cx);
5335
5336        assert!(!model_released.get());
5337        assert!(!view_released.get());
5338
5339        cx.update(|cx| {
5340            cx.observe_release(&model, {
5341                let model_release_observed = model_release_observed.clone();
5342                move |_, _| model_release_observed.set(true)
5343            })
5344            .detach();
5345            cx.observe_release(&view, {
5346                let view_release_observed = view_release_observed.clone();
5347                move |_, _| view_release_observed.set(true)
5348            })
5349            .detach();
5350        });
5351
5352        cx.update(move |_| {
5353            drop(model);
5354        });
5355        assert!(model_released.get());
5356        assert!(model_release_observed.get());
5357
5358        drop(view);
5359        window.update(cx, |cx| cx.remove_window());
5360        assert!(view_released.get());
5361        assert!(view_release_observed.get());
5362    }
5363
5364    #[crate::test(self)]
5365    fn test_view_events(cx: &mut TestAppContext) {
5366        struct Model;
5367
5368        impl Entity for Model {
5369            type Event = String;
5370        }
5371
5372        let window = cx.add_window(|_| TestView::default());
5373        let handle_1 = window.root(cx);
5374        let handle_2 = window.add_view(cx, |_| TestView::default());
5375        let handle_3 = cx.add_model(|_| Model);
5376
5377        handle_1.update(cx, |_, cx| {
5378            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
5379                me.events.push(event.clone());
5380
5381                cx.subscribe(&emitter, |me, _, event, _| {
5382                    me.events.push(format!("{event} from inner"));
5383                })
5384                .detach();
5385            })
5386            .detach();
5387
5388            cx.subscribe(&handle_3, |me, _, event, _| {
5389                me.events.push(event.clone());
5390            })
5391            .detach();
5392        });
5393
5394        handle_2.update(cx, |_, c| c.emit("7".into()));
5395        handle_1.read_with(cx, |view, _| assert_eq!(view.events, ["7"]));
5396
5397        handle_2.update(cx, |_, c| c.emit("5".into()));
5398        handle_1.read_with(cx, |view, _| {
5399            assert_eq!(view.events, ["7", "5", "5 from inner"])
5400        });
5401
5402        handle_3.update(cx, |_, c| c.emit("9".into()));
5403        handle_1.read_with(cx, |view, _| {
5404            assert_eq!(view.events, ["7", "5", "5 from inner", "9"])
5405        });
5406    }
5407
5408    #[crate::test(self)]
5409    fn test_global_events(cx: &mut AppContext) {
5410        #[derive(Clone, Debug, Eq, PartialEq)]
5411        struct GlobalEvent(u64);
5412
5413        let events = Rc::new(RefCell::new(Vec::new()));
5414        let first_subscription;
5415        let second_subscription;
5416
5417        {
5418            let events = events.clone();
5419            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5420                events.borrow_mut().push(("First", e.clone()));
5421            });
5422        }
5423
5424        {
5425            let events = events.clone();
5426            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5427                events.borrow_mut().push(("Second", e.clone()));
5428            });
5429        }
5430
5431        cx.update(|cx| {
5432            cx.emit_global(GlobalEvent(1));
5433            cx.emit_global(GlobalEvent(2));
5434        });
5435
5436        drop(first_subscription);
5437
5438        cx.update(|cx| {
5439            cx.emit_global(GlobalEvent(3));
5440        });
5441
5442        drop(second_subscription);
5443
5444        cx.update(|cx| {
5445            cx.emit_global(GlobalEvent(4));
5446        });
5447
5448        assert_eq!(
5449            &*events.borrow(),
5450            &[
5451                ("First", GlobalEvent(1)),
5452                ("Second", GlobalEvent(1)),
5453                ("First", GlobalEvent(2)),
5454                ("Second", GlobalEvent(2)),
5455                ("Second", GlobalEvent(3)),
5456            ]
5457        );
5458    }
5459
5460    #[crate::test(self)]
5461    fn test_global_events_emitted_before_subscription_in_same_update_cycle(cx: &mut AppContext) {
5462        let events = Rc::new(RefCell::new(Vec::new()));
5463        cx.update(|cx| {
5464            {
5465                let events = events.clone();
5466                drop(cx.subscribe_global(move |_: &(), _| {
5467                    events.borrow_mut().push("dropped before emit");
5468                }));
5469            }
5470
5471            {
5472                let events = events.clone();
5473                cx.subscribe_global(move |_: &(), _| {
5474                    events.borrow_mut().push("before emit");
5475                })
5476                .detach();
5477            }
5478
5479            cx.emit_global(());
5480
5481            {
5482                let events = events.clone();
5483                cx.subscribe_global(move |_: &(), _| {
5484                    events.borrow_mut().push("after emit");
5485                })
5486                .detach();
5487            }
5488        });
5489
5490        assert_eq!(*events.borrow(), ["before emit"]);
5491    }
5492
5493    #[crate::test(self)]
5494    fn test_global_nested_events(cx: &mut AppContext) {
5495        #[derive(Clone, Debug, Eq, PartialEq)]
5496        struct GlobalEvent(u64);
5497
5498        let events = Rc::new(RefCell::new(Vec::new()));
5499
5500        {
5501            let events = events.clone();
5502            cx.subscribe_global(move |e: &GlobalEvent, cx| {
5503                events.borrow_mut().push(("Outer", e.clone()));
5504
5505                if e.0 == 1 {
5506                    let events = events.clone();
5507                    cx.subscribe_global(move |e: &GlobalEvent, _| {
5508                        events.borrow_mut().push(("Inner", e.clone()));
5509                    })
5510                    .detach();
5511                }
5512            })
5513            .detach();
5514        }
5515
5516        cx.update(|cx| {
5517            cx.emit_global(GlobalEvent(1));
5518            cx.emit_global(GlobalEvent(2));
5519            cx.emit_global(GlobalEvent(3));
5520        });
5521        cx.update(|cx| {
5522            cx.emit_global(GlobalEvent(4));
5523        });
5524
5525        assert_eq!(
5526            &*events.borrow(),
5527            &[
5528                ("Outer", GlobalEvent(1)),
5529                ("Outer", GlobalEvent(2)),
5530                ("Outer", GlobalEvent(3)),
5531                ("Outer", GlobalEvent(4)),
5532                ("Inner", GlobalEvent(4)),
5533            ]
5534        );
5535    }
5536
5537    #[crate::test(self)]
5538    fn test_global(cx: &mut AppContext) {
5539        type Global = usize;
5540
5541        let observation_count = Rc::new(RefCell::new(0));
5542        let subscription = cx.observe_global::<Global, _>({
5543            let observation_count = observation_count.clone();
5544            move |_| {
5545                *observation_count.borrow_mut() += 1;
5546            }
5547        });
5548
5549        assert!(!cx.has_global::<Global>());
5550        assert_eq!(cx.default_global::<Global>(), &0);
5551        assert_eq!(*observation_count.borrow(), 1);
5552        assert!(cx.has_global::<Global>());
5553        assert_eq!(
5554            cx.update_global::<Global, _, _>(|global, _| {
5555                *global = 1;
5556                "Update Result"
5557            }),
5558            "Update Result"
5559        );
5560        assert_eq!(*observation_count.borrow(), 2);
5561        assert_eq!(cx.global::<Global>(), &1);
5562
5563        drop(subscription);
5564        cx.update_global::<Global, _, _>(|global, _| {
5565            *global = 2;
5566        });
5567        assert_eq!(*observation_count.borrow(), 2);
5568
5569        type OtherGlobal = f32;
5570
5571        let observation_count = Rc::new(RefCell::new(0));
5572        cx.observe_global::<OtherGlobal, _>({
5573            let observation_count = observation_count.clone();
5574            move |_| {
5575                *observation_count.borrow_mut() += 1;
5576            }
5577        })
5578        .detach();
5579
5580        assert_eq!(
5581            cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
5582                assert_eq!(global, &0.0);
5583                *global = 2.0;
5584                "Default update result"
5585            }),
5586            "Default update result"
5587        );
5588        assert_eq!(cx.global::<OtherGlobal>(), &2.0);
5589        assert_eq!(*observation_count.borrow(), 1);
5590    }
5591
5592    #[crate::test(self)]
5593    fn test_dropping_subscribers(cx: &mut TestAppContext) {
5594        struct Model;
5595
5596        impl Entity for Model {
5597            type Event = ();
5598        }
5599
5600        let window = cx.add_window(|_| TestView::default());
5601        let observing_view = window.add_view(cx, |_| TestView::default());
5602        let emitting_view = window.add_view(cx, |_| TestView::default());
5603        let observing_model = cx.add_model(|_| Model);
5604        let observed_model = cx.add_model(|_| Model);
5605
5606        observing_view.update(cx, |_, cx| {
5607            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
5608            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5609        });
5610        observing_model.update(cx, |_, cx| {
5611            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5612        });
5613
5614        cx.update(|_| {
5615            drop(observing_view);
5616            drop(observing_model);
5617        });
5618
5619        emitting_view.update(cx, |_, cx| cx.emit(Default::default()));
5620        observed_model.update(cx, |_, cx| cx.emit(()));
5621    }
5622
5623    #[crate::test(self)]
5624    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
5625        let window = cx.add_window::<TestView, _>(Default::default(), |cx| {
5626            drop(cx.subscribe(&cx.handle(), {
5627                move |this, _, _, _| this.events.push("dropped before flush".into())
5628            }));
5629            cx.subscribe(&cx.handle(), {
5630                move |this, _, _, _| this.events.push("before emit".into())
5631            })
5632            .detach();
5633            cx.emit("the event".into());
5634            cx.subscribe(&cx.handle(), {
5635                move |this, _, _, _| this.events.push("after emit".into())
5636            })
5637            .detach();
5638            TestView { events: Vec::new() }
5639        });
5640
5641        window.read_root_with(cx, |view, _| assert_eq!(view.events, ["before emit"]));
5642    }
5643
5644    #[crate::test(self)]
5645    fn test_observe_and_notify_from_view(cx: &mut TestAppContext) {
5646        #[derive(Default)]
5647        struct Model {
5648            state: String,
5649        }
5650
5651        impl Entity for Model {
5652            type Event = ();
5653        }
5654
5655        let window = cx.add_window(|_| TestView::default());
5656        let view = window.root(cx);
5657        let model = cx.add_model(|_| Model {
5658            state: "old-state".into(),
5659        });
5660
5661        view.update(cx, |_, c| {
5662            c.observe(&model, |me, observed, cx| {
5663                me.events.push(observed.read(cx).state.clone())
5664            })
5665            .detach();
5666        });
5667
5668        model.update(cx, |model, cx| {
5669            model.state = "new-state".into();
5670            cx.notify();
5671        });
5672        view.read_with(cx, |view, _| assert_eq!(view.events, ["new-state"]));
5673    }
5674
5675    #[crate::test(self)]
5676    fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
5677        let window = cx.add_window::<TestView, _>(Default::default(), |cx| {
5678            drop(cx.observe(&cx.handle(), {
5679                move |this, _, _| this.events.push("dropped before flush".into())
5680            }));
5681            cx.observe(&cx.handle(), {
5682                move |this, _, _| this.events.push("before notify".into())
5683            })
5684            .detach();
5685            cx.notify();
5686            cx.observe(&cx.handle(), {
5687                move |this, _, _| this.events.push("after notify".into())
5688            })
5689            .detach();
5690            TestView { events: Vec::new() }
5691        });
5692
5693        window.read_root_with(cx, |view, _| assert_eq!(view.events, ["before notify"]));
5694    }
5695
5696    #[crate::test(self)]
5697    fn test_notify_and_drop_observe_subscription_in_same_update_cycle(cx: &mut TestAppContext) {
5698        struct Model;
5699        impl Entity for Model {
5700            type Event = ();
5701        }
5702
5703        let model = cx.add_model(|_| Model);
5704        let window = cx.add_window(|_| TestView::default());
5705        let view = window.root(cx);
5706
5707        view.update(cx, |_, cx| {
5708            model.update(cx, |_, cx| cx.notify());
5709            drop(cx.observe(&model, move |this, _, _| {
5710                this.events.push("model notified".into());
5711            }));
5712            model.update(cx, |_, cx| cx.notify());
5713        });
5714
5715        for _ in 0..3 {
5716            model.update(cx, |_, cx| cx.notify());
5717        }
5718        view.read_with(cx, |view, _| assert_eq!(view.events, Vec::<&str>::new()));
5719    }
5720
5721    #[crate::test(self)]
5722    fn test_dropping_observers(cx: &mut TestAppContext) {
5723        struct Model;
5724
5725        impl Entity for Model {
5726            type Event = ();
5727        }
5728
5729        let window = cx.add_window(|_| TestView::default());
5730        let observing_view = window.add_view(cx, |_| TestView::default());
5731        let observing_model = cx.add_model(|_| Model);
5732        let observed_model = cx.add_model(|_| Model);
5733
5734        observing_view.update(cx, |_, cx| {
5735            cx.observe(&observed_model, |_, _, _| {}).detach();
5736        });
5737        observing_model.update(cx, |_, cx| {
5738            cx.observe(&observed_model, |_, _, _| {}).detach();
5739        });
5740
5741        cx.update(|_| {
5742            drop(observing_view);
5743            drop(observing_model);
5744        });
5745
5746        observed_model.update(cx, |_, cx| cx.notify());
5747    }
5748
5749    #[crate::test(self)]
5750    fn test_dropping_subscriptions_during_callback(cx: &mut TestAppContext) {
5751        struct Model;
5752
5753        impl Entity for Model {
5754            type Event = u64;
5755        }
5756
5757        // Events
5758        let observing_model = cx.add_model(|_| Model);
5759        let observed_model = cx.add_model(|_| Model);
5760
5761        let events = Rc::new(RefCell::new(Vec::new()));
5762
5763        observing_model.update(cx, |_, cx| {
5764            let events = events.clone();
5765            let subscription = Rc::new(RefCell::new(None));
5766            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
5767                let subscription = subscription.clone();
5768                move |_, _, e, _| {
5769                    subscription.borrow_mut().take();
5770                    events.borrow_mut().push(*e);
5771                }
5772            }));
5773        });
5774
5775        observed_model.update(cx, |_, cx| {
5776            cx.emit(1);
5777            cx.emit(2);
5778        });
5779
5780        assert_eq!(*events.borrow(), [1]);
5781
5782        // Global Events
5783        #[derive(Clone, Debug, Eq, PartialEq)]
5784        struct GlobalEvent(u64);
5785
5786        let events = Rc::new(RefCell::new(Vec::new()));
5787
5788        {
5789            let events = events.clone();
5790            let subscription = Rc::new(RefCell::new(None));
5791            *subscription.borrow_mut() = Some(cx.subscribe_global({
5792                let subscription = subscription.clone();
5793                move |e: &GlobalEvent, _| {
5794                    subscription.borrow_mut().take();
5795                    events.borrow_mut().push(e.clone());
5796                }
5797            }));
5798        }
5799
5800        cx.update(|cx| {
5801            cx.emit_global(GlobalEvent(1));
5802            cx.emit_global(GlobalEvent(2));
5803        });
5804
5805        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
5806
5807        // Model Observation
5808        let observing_model = cx.add_model(|_| Model);
5809        let observed_model = cx.add_model(|_| Model);
5810
5811        let observation_count = Rc::new(RefCell::new(0));
5812
5813        observing_model.update(cx, |_, cx| {
5814            let observation_count = observation_count.clone();
5815            let subscription = Rc::new(RefCell::new(None));
5816            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
5817                let subscription = subscription.clone();
5818                move |_, _, _| {
5819                    subscription.borrow_mut().take();
5820                    *observation_count.borrow_mut() += 1;
5821                }
5822            }));
5823        });
5824
5825        observed_model.update(cx, |_, cx| {
5826            cx.notify();
5827        });
5828
5829        observed_model.update(cx, |_, cx| {
5830            cx.notify();
5831        });
5832
5833        assert_eq!(*observation_count.borrow(), 1);
5834
5835        // View Observation
5836        struct View;
5837
5838        impl Entity for View {
5839            type Event = ();
5840        }
5841
5842        impl super::View for View {
5843            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5844                Empty::new().into_any()
5845            }
5846
5847            fn ui_name() -> &'static str {
5848                "View"
5849            }
5850        }
5851
5852        let window = cx.add_window(|_| View);
5853        let observing_view = window.add_view(cx, |_| View);
5854        let observed_view = window.add_view(cx, |_| View);
5855
5856        let observation_count = Rc::new(RefCell::new(0));
5857        observing_view.update(cx, |_, cx| {
5858            let observation_count = observation_count.clone();
5859            let subscription = Rc::new(RefCell::new(None));
5860            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
5861                let subscription = subscription.clone();
5862                move |_, _, _| {
5863                    subscription.borrow_mut().take();
5864                    *observation_count.borrow_mut() += 1;
5865                }
5866            }));
5867        });
5868
5869        observed_view.update(cx, |_, cx| {
5870            cx.notify();
5871        });
5872
5873        observed_view.update(cx, |_, cx| {
5874            cx.notify();
5875        });
5876
5877        assert_eq!(*observation_count.borrow(), 1);
5878
5879        // Global Observation
5880        let observation_count = Rc::new(RefCell::new(0));
5881        let subscription = Rc::new(RefCell::new(None));
5882        *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
5883            let observation_count = observation_count.clone();
5884            let subscription = subscription.clone();
5885            move |_| {
5886                subscription.borrow_mut().take();
5887                *observation_count.borrow_mut() += 1;
5888            }
5889        }));
5890
5891        cx.update(|cx| {
5892            cx.default_global::<()>();
5893            cx.set_global(());
5894        });
5895        assert_eq!(*observation_count.borrow(), 1);
5896    }
5897
5898    #[crate::test(self)]
5899    fn test_focus(cx: &mut TestAppContext) {
5900        struct View {
5901            name: String,
5902            events: Arc<Mutex<Vec<String>>>,
5903            child: Option<AnyViewHandle>,
5904        }
5905
5906        impl Entity for View {
5907            type Event = ();
5908        }
5909
5910        impl super::View for View {
5911            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
5912                self.child
5913                    .as_ref()
5914                    .map(|child| ChildView::new(child, cx).into_any())
5915                    .unwrap_or(Empty::new().into_any())
5916            }
5917
5918            fn ui_name() -> &'static str {
5919                "View"
5920            }
5921
5922            fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
5923                if cx.handle().id() == focused.id() {
5924                    self.events.lock().push(format!("{} focused", &self.name));
5925                }
5926            }
5927
5928            fn focus_out(&mut self, blurred: AnyViewHandle, cx: &mut ViewContext<Self>) {
5929                if cx.handle().id() == blurred.id() {
5930                    self.events.lock().push(format!("{} blurred", &self.name));
5931                }
5932            }
5933        }
5934
5935        let view_events: Arc<Mutex<Vec<String>>> = Default::default();
5936        let window = cx.add_window(|_| View {
5937            events: view_events.clone(),
5938            name: "view 1".to_string(),
5939            child: None,
5940        });
5941        let view_1 = window.root(cx);
5942        let view_2 = window.update(cx, |cx| {
5943            let view_2 = cx.add_view(|_| View {
5944                events: view_events.clone(),
5945                name: "view 2".to_string(),
5946                child: None,
5947            });
5948            view_1.update(cx, |view_1, cx| {
5949                view_1.child = Some(view_2.clone().into_any());
5950                cx.notify();
5951            });
5952            view_2
5953        });
5954
5955        let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
5956        view_1.update(cx, |_, cx| {
5957            cx.observe_focus(&view_2, {
5958                let observed_events = observed_events.clone();
5959                move |this, view, focused, cx| {
5960                    let label = if focused { "focus" } else { "blur" };
5961                    observed_events.lock().push(format!(
5962                        "{} observed {}'s {}",
5963                        this.name,
5964                        view.read(cx).name,
5965                        label
5966                    ))
5967                }
5968            })
5969            .detach();
5970        });
5971        view_2.update(cx, |_, cx| {
5972            cx.observe_focus(&view_1, {
5973                let observed_events = observed_events.clone();
5974                move |this, view, focused, cx| {
5975                    let label = if focused { "focus" } else { "blur" };
5976                    observed_events.lock().push(format!(
5977                        "{} observed {}'s {}",
5978                        this.name,
5979                        view.read(cx).name,
5980                        label
5981                    ))
5982                }
5983            })
5984            .detach();
5985        });
5986        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
5987        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
5988
5989        view_1.update(cx, |_, cx| {
5990            // Ensure only the last focus event is honored.
5991            cx.focus(&view_2);
5992            cx.focus(&view_1);
5993            cx.focus(&view_2);
5994        });
5995
5996        assert_eq!(
5997            mem::take(&mut *view_events.lock()),
5998            ["view 1 blurred", "view 2 focused"],
5999        );
6000        assert_eq!(
6001            mem::take(&mut *observed_events.lock()),
6002            [
6003                "view 2 observed view 1's blur",
6004                "view 1 observed view 2's focus"
6005            ]
6006        );
6007
6008        view_1.update(cx, |_, cx| cx.focus(&view_1));
6009        assert_eq!(
6010            mem::take(&mut *view_events.lock()),
6011            ["view 2 blurred", "view 1 focused"],
6012        );
6013        assert_eq!(
6014            mem::take(&mut *observed_events.lock()),
6015            [
6016                "view 1 observed view 2's blur",
6017                "view 2 observed view 1's focus"
6018            ]
6019        );
6020
6021        view_1.update(cx, |_, cx| cx.focus(&view_2));
6022        assert_eq!(
6023            mem::take(&mut *view_events.lock()),
6024            ["view 1 blurred", "view 2 focused"],
6025        );
6026        assert_eq!(
6027            mem::take(&mut *observed_events.lock()),
6028            [
6029                "view 2 observed view 1's blur",
6030                "view 1 observed view 2's focus"
6031            ]
6032        );
6033
6034        println!("=====================");
6035        view_1.update(cx, |view, _| {
6036            drop(view_2);
6037            view.child = None;
6038        });
6039        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6040        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6041    }
6042
6043    #[crate::test(self)]
6044    fn test_deserialize_actions(cx: &mut AppContext) {
6045        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6046        pub struct ComplexAction {
6047            arg: String,
6048            count: usize,
6049        }
6050
6051        actions!(test::something, [SimpleAction]);
6052        impl_actions!(test::something, [ComplexAction]);
6053
6054        cx.add_global_action(move |_: &SimpleAction, _: &mut AppContext| {});
6055        cx.add_global_action(move |_: &ComplexAction, _: &mut AppContext| {});
6056
6057        let action1 = cx
6058            .deserialize_action(
6059                "test::something::ComplexAction",
6060                Some(serde_json::from_str(r#"{"arg": "a", "count": 5}"#).unwrap()),
6061            )
6062            .unwrap();
6063        let action2 = cx
6064            .deserialize_action("test::something::SimpleAction", None)
6065            .unwrap();
6066        assert_eq!(
6067            action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
6068            &ComplexAction {
6069                arg: "a".to_string(),
6070                count: 5,
6071            }
6072        );
6073        assert_eq!(
6074            action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
6075            &SimpleAction
6076        );
6077    }
6078
6079    #[crate::test(self)]
6080    fn test_dispatch_action(cx: &mut TestAppContext) {
6081        struct ViewA {
6082            id: usize,
6083            child: Option<AnyViewHandle>,
6084        }
6085
6086        impl Entity for ViewA {
6087            type Event = ();
6088        }
6089
6090        impl View for ViewA {
6091            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
6092                self.child
6093                    .as_ref()
6094                    .map(|child| ChildView::new(child, cx).into_any())
6095                    .unwrap_or(Empty::new().into_any())
6096            }
6097
6098            fn ui_name() -> &'static str {
6099                "View"
6100            }
6101        }
6102
6103        struct ViewB {
6104            id: usize,
6105            child: Option<AnyViewHandle>,
6106        }
6107
6108        impl Entity for ViewB {
6109            type Event = ();
6110        }
6111
6112        impl View for ViewB {
6113            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
6114                self.child
6115                    .as_ref()
6116                    .map(|child| ChildView::new(child, cx).into_any())
6117                    .unwrap_or(Empty::new().into_any())
6118            }
6119
6120            fn ui_name() -> &'static str {
6121                "View"
6122            }
6123        }
6124
6125        #[derive(Clone, Default, Deserialize, PartialEq)]
6126        pub struct Action(pub String);
6127
6128        impl_actions!(test, [Action]);
6129
6130        let actions = Rc::new(RefCell::new(Vec::new()));
6131        let observed_actions = Rc::new(RefCell::new(Vec::new()));
6132
6133        cx.update(|cx| {
6134            cx.add_global_action({
6135                let actions = actions.clone();
6136                move |_: &Action, _: &mut AppContext| {
6137                    actions.borrow_mut().push("global".to_string());
6138                }
6139            });
6140
6141            cx.add_action({
6142                let actions = actions.clone();
6143                move |view: &mut ViewA, action: &Action, cx| {
6144                    assert_eq!(action.0, "bar");
6145                    cx.propagate_action();
6146                    actions.borrow_mut().push(format!("{} a", view.id));
6147                }
6148            });
6149
6150            cx.add_action({
6151                let actions = actions.clone();
6152                move |view: &mut ViewA, _: &Action, cx| {
6153                    if view.id != 1 {
6154                        cx.add_view(|cx| {
6155                            cx.propagate_action(); // Still works on a nested ViewContext
6156                            ViewB { id: 5, child: None }
6157                        });
6158                    }
6159                    actions.borrow_mut().push(format!("{} b", view.id));
6160                }
6161            });
6162
6163            cx.add_action({
6164                let actions = actions.clone();
6165                move |view: &mut ViewB, _: &Action, cx| {
6166                    cx.propagate_action();
6167                    actions.borrow_mut().push(format!("{} c", view.id));
6168                }
6169            });
6170
6171            cx.add_action({
6172                let actions = actions.clone();
6173                move |view: &mut ViewB, _: &Action, cx| {
6174                    cx.propagate_action();
6175                    actions.borrow_mut().push(format!("{} d", view.id));
6176                }
6177            });
6178
6179            cx.capture_action({
6180                let actions = actions.clone();
6181                move |view: &mut ViewA, _: &Action, cx| {
6182                    cx.propagate_action();
6183                    actions.borrow_mut().push(format!("{} capture", view.id));
6184                }
6185            });
6186
6187            cx.observe_actions({
6188                let observed_actions = observed_actions.clone();
6189                move |action_id, _| observed_actions.borrow_mut().push(action_id)
6190            })
6191            .detach();
6192        });
6193
6194        let window = cx.add_window(|_| ViewA { id: 1, child: None });
6195        let view_1 = window.root(cx);
6196        let view_2 = window.update(cx, |cx| {
6197            let child = cx.add_view(|_| ViewB { id: 2, child: None });
6198            view_1.update(cx, |view, cx| {
6199                view.child = Some(child.clone().into_any());
6200                cx.notify();
6201            });
6202            child
6203        });
6204        let view_3 = window.update(cx, |cx| {
6205            let child = cx.add_view(|_| ViewA { id: 3, child: None });
6206            view_2.update(cx, |view, cx| {
6207                view.child = Some(child.clone().into_any());
6208                cx.notify();
6209            });
6210            child
6211        });
6212        let view_4 = window.update(cx, |cx| {
6213            let child = cx.add_view(|_| ViewB { id: 4, child: None });
6214            view_3.update(cx, |view, cx| {
6215                view.child = Some(child.clone().into_any());
6216                cx.notify();
6217            });
6218            child
6219        });
6220
6221        window.update(cx, |cx| {
6222            cx.dispatch_action(Some(view_4.id()), &Action("bar".to_string()))
6223        });
6224
6225        assert_eq!(
6226            *actions.borrow(),
6227            vec![
6228                "1 capture",
6229                "3 capture",
6230                "4 d",
6231                "4 c",
6232                "3 b",
6233                "3 a",
6234                "2 d",
6235                "2 c",
6236                "1 b"
6237            ]
6238        );
6239        assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
6240
6241        // Remove view_1, which doesn't propagate the action
6242
6243        let window = cx.add_window(|_| ViewB { id: 2, child: None });
6244        let view_2 = window.root(cx);
6245        let view_3 = window.update(cx, |cx| {
6246            let child = cx.add_view(|_| ViewA { id: 3, child: None });
6247            view_2.update(cx, |view, cx| {
6248                view.child = Some(child.clone().into_any());
6249                cx.notify();
6250            });
6251            child
6252        });
6253        let view_4 = window.update(cx, |cx| {
6254            let child = cx.add_view(|_| ViewB { id: 4, child: None });
6255            view_3.update(cx, |view, cx| {
6256                view.child = Some(child.clone().into_any());
6257                cx.notify();
6258            });
6259            child
6260        });
6261
6262        actions.borrow_mut().clear();
6263        window.update(cx, |cx| {
6264            cx.dispatch_action(Some(view_4.id()), &Action("bar".to_string()))
6265        });
6266
6267        assert_eq!(
6268            *actions.borrow(),
6269            vec![
6270                "3 capture",
6271                "4 d",
6272                "4 c",
6273                "3 b",
6274                "3 a",
6275                "2 d",
6276                "2 c",
6277                "global"
6278            ]
6279        );
6280        assert_eq!(
6281            *observed_actions.borrow(),
6282            [Action::default().id(), Action::default().id()]
6283        );
6284    }
6285
6286    #[crate::test(self)]
6287    fn test_dispatch_keystroke(cx: &mut AppContext) {
6288        #[derive(Clone, Deserialize, PartialEq)]
6289        pub struct Action(String);
6290
6291        impl_actions!(test, [Action]);
6292
6293        struct View {
6294            id: usize,
6295            keymap_context: KeymapContext,
6296            child: Option<AnyViewHandle>,
6297        }
6298
6299        impl Entity for View {
6300            type Event = ();
6301        }
6302
6303        impl super::View for View {
6304            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
6305                self.child
6306                    .as_ref()
6307                    .map(|child| ChildView::new(child, cx).into_any())
6308                    .unwrap_or(Empty::new().into_any())
6309            }
6310
6311            fn ui_name() -> &'static str {
6312                "View"
6313            }
6314
6315            fn update_keymap_context(&self, keymap: &mut KeymapContext, _: &AppContext) {
6316                *keymap = self.keymap_context.clone();
6317            }
6318        }
6319
6320        impl View {
6321            fn new(id: usize) -> Self {
6322                View {
6323                    id,
6324                    keymap_context: KeymapContext::default(),
6325                    child: None,
6326                }
6327            }
6328        }
6329
6330        let mut view_1 = View::new(1);
6331        let mut view_2 = View::new(2);
6332        let mut view_3 = View::new(3);
6333        view_1.keymap_context.add_identifier("a");
6334        view_2.keymap_context.add_identifier("a");
6335        view_2.keymap_context.add_identifier("b");
6336        view_3.keymap_context.add_identifier("a");
6337        view_3.keymap_context.add_identifier("b");
6338        view_3.keymap_context.add_identifier("c");
6339
6340        let window = cx.add_window(Default::default(), |cx| {
6341            let view_2 = cx.add_view(|cx| {
6342                let view_3 = cx.add_view(|cx| {
6343                    cx.focus_self();
6344                    view_3
6345                });
6346                view_2.child = Some(view_3.into_any());
6347                view_2
6348            });
6349            view_1.child = Some(view_2.into_any());
6350            view_1
6351        });
6352
6353        // This binding only dispatches an action on view 2 because that view will have
6354        // "a" and "b" in its context, but not "c".
6355        cx.add_bindings(vec![Binding::new(
6356            "a",
6357            Action("a".to_string()),
6358            Some("a && b && !c"),
6359        )]);
6360
6361        cx.add_bindings(vec![Binding::new("b", Action("b".to_string()), None)]);
6362
6363        // This binding only dispatches an action on views 2 and 3, because they have
6364        // a parent view with a in its context
6365        cx.add_bindings(vec![Binding::new(
6366            "c",
6367            Action("c".to_string()),
6368            Some("b > c"),
6369        )]);
6370
6371        // This binding only dispatches an action on view 2, because they have
6372        // a parent view with a in its context
6373        cx.add_bindings(vec![Binding::new(
6374            "d",
6375            Action("d".to_string()),
6376            Some("a && !b > b"),
6377        )]);
6378
6379        let actions = Rc::new(RefCell::new(Vec::new()));
6380        cx.add_action({
6381            let actions = actions.clone();
6382            move |view: &mut View, action: &Action, cx| {
6383                actions
6384                    .borrow_mut()
6385                    .push(format!("{} {}", view.id, action.0));
6386
6387                if action.0 == "b" {
6388                    cx.propagate_action();
6389                }
6390            }
6391        });
6392
6393        cx.add_global_action({
6394            let actions = actions.clone();
6395            move |action: &Action, _| {
6396                actions.borrow_mut().push(format!("global {}", action.0));
6397            }
6398        });
6399
6400        window.update(cx, |cx| {
6401            cx.dispatch_keystroke(&Keystroke::parse("a").unwrap())
6402        });
6403        assert_eq!(&*actions.borrow(), &["2 a"]);
6404        actions.borrow_mut().clear();
6405
6406        window.update(cx, |cx| {
6407            cx.dispatch_keystroke(&Keystroke::parse("b").unwrap());
6408        });
6409
6410        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
6411        actions.borrow_mut().clear();
6412
6413        window.update(cx, |cx| {
6414            cx.dispatch_keystroke(&Keystroke::parse("c").unwrap());
6415        });
6416        assert_eq!(&*actions.borrow(), &["3 c"]);
6417        actions.borrow_mut().clear();
6418
6419        window.update(cx, |cx| {
6420            cx.dispatch_keystroke(&Keystroke::parse("d").unwrap());
6421        });
6422        assert_eq!(&*actions.borrow(), &["2 d"]);
6423        actions.borrow_mut().clear();
6424    }
6425
6426    #[crate::test(self)]
6427    fn test_keystrokes_for_action(cx: &mut TestAppContext) {
6428        actions!(test, [Action1, Action2, GlobalAction]);
6429
6430        struct View1 {
6431            child: ViewHandle<View2>,
6432        }
6433        struct View2 {}
6434
6435        impl Entity for View1 {
6436            type Event = ();
6437        }
6438        impl Entity for View2 {
6439            type Event = ();
6440        }
6441
6442        impl super::View for View1 {
6443            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
6444                ChildView::new(&self.child, cx).into_any()
6445            }
6446            fn ui_name() -> &'static str {
6447                "View1"
6448            }
6449        }
6450        impl super::View for View2 {
6451            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6452                Empty::new().into_any()
6453            }
6454            fn ui_name() -> &'static str {
6455                "View2"
6456            }
6457        }
6458
6459        let window = cx.add_window(|cx| {
6460            let view_2 = cx.add_view(|cx| {
6461                cx.focus_self();
6462                View2 {}
6463            });
6464            View1 { child: view_2 }
6465        });
6466        let view_1 = window.root(cx);
6467        let view_2 = view_1.read_with(cx, |view, _| view.child.clone());
6468
6469        cx.update(|cx| {
6470            cx.add_action(|_: &mut View1, _: &Action1, _cx| {});
6471            cx.add_action(|_: &mut View2, _: &Action2, _cx| {});
6472            cx.add_global_action(|_: &GlobalAction, _| {});
6473            cx.add_bindings(vec![
6474                Binding::new("a", Action1, Some("View1")),
6475                Binding::new("b", Action2, Some("View1 > View2")),
6476                Binding::new("c", GlobalAction, Some("View3")), // View 3 does not exist
6477            ]);
6478        });
6479
6480        let view_1_id = view_1.id();
6481        view_1.update(cx, |_, cx| {
6482            view_2.update(cx, |_, cx| {
6483                // Sanity check
6484                let mut new_parents = Default::default();
6485                let mut notify_views_if_parents_change = Default::default();
6486                let mut layout_cx = LayoutContext::new(
6487                    cx,
6488                    &mut new_parents,
6489                    &mut notify_views_if_parents_change,
6490                    false,
6491                );
6492                assert_eq!(
6493                    layout_cx
6494                        .keystrokes_for_action(view_1_id, &Action1)
6495                        .unwrap()
6496                        .as_slice(),
6497                    &[Keystroke::parse("a").unwrap()]
6498                );
6499                assert_eq!(
6500                    layout_cx
6501                        .keystrokes_for_action(view_2.id(), &Action2)
6502                        .unwrap()
6503                        .as_slice(),
6504                    &[Keystroke::parse("b").unwrap()]
6505                );
6506
6507                // The 'a' keystroke propagates up the view tree from view_2
6508                // to view_1. The action, Action1, is handled by view_1.
6509                assert_eq!(
6510                    layout_cx
6511                        .keystrokes_for_action(view_2.id(), &Action1)
6512                        .unwrap()
6513                        .as_slice(),
6514                    &[Keystroke::parse("a").unwrap()]
6515                );
6516
6517                // Actions that are handled below the current view don't have bindings
6518                assert_eq!(layout_cx.keystrokes_for_action(view_1_id, &Action2), None);
6519
6520                // Actions that are handled in other branches of the tree should not have a binding
6521                assert_eq!(
6522                    layout_cx.keystrokes_for_action(view_2.id(), &GlobalAction),
6523                    None
6524                );
6525            });
6526        });
6527
6528        // Check that global actions do not have a binding, even if a binding does exist in another view
6529        assert_eq!(
6530            &available_actions(window.into(), view_1.id(), cx),
6531            &[
6532                ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
6533                ("test::GlobalAction", vec![])
6534            ],
6535        );
6536
6537        // Check that view 1 actions and bindings are available even when called from view 2
6538        assert_eq!(
6539            &available_actions(window.into(), view_2.id(), cx),
6540            &[
6541                ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
6542                ("test::Action2", vec![Keystroke::parse("b").unwrap()]),
6543                ("test::GlobalAction", vec![]),
6544            ],
6545        );
6546
6547        // Produces a list of actions and key bindings
6548        fn available_actions(
6549            window: AnyWindowHandle,
6550            view_id: usize,
6551            cx: &TestAppContext,
6552        ) -> Vec<(&'static str, Vec<Keystroke>)> {
6553            cx.available_actions(window.into(), view_id)
6554                .into_iter()
6555                .map(|(action_name, _, bindings)| {
6556                    (
6557                        action_name,
6558                        bindings
6559                            .iter()
6560                            .map(|binding| binding.keystrokes()[0].clone())
6561                            .collect::<Vec<_>>(),
6562                    )
6563                })
6564                .sorted_by(|(name1, _), (name2, _)| name1.cmp(name2))
6565                .collect()
6566        }
6567    }
6568
6569    #[crate::test(self)]
6570    fn test_keystrokes_for_action_with_data(cx: &mut TestAppContext) {
6571        #[derive(Clone, Debug, Deserialize, PartialEq)]
6572        struct ActionWithArg {
6573            #[serde(default)]
6574            arg: bool,
6575        }
6576
6577        struct View;
6578        impl super::Entity for View {
6579            type Event = ();
6580        }
6581        impl super::View for View {
6582            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6583                Empty::new().into_any()
6584            }
6585            fn ui_name() -> &'static str {
6586                "View"
6587            }
6588        }
6589
6590        impl_actions!(test, [ActionWithArg]);
6591
6592        let window = cx.add_window(|_| View);
6593        let view = window.root(cx);
6594        cx.update(|cx| {
6595            cx.add_global_action(|_: &ActionWithArg, _| {});
6596            cx.add_bindings(vec![
6597                Binding::new("a", ActionWithArg { arg: false }, None),
6598                Binding::new("shift-a", ActionWithArg { arg: true }, None),
6599            ]);
6600        });
6601
6602        let actions = cx.available_actions(window.into(), view.id());
6603        assert_eq!(
6604            actions[0].1.as_any().downcast_ref::<ActionWithArg>(),
6605            Some(&ActionWithArg { arg: false })
6606        );
6607        assert_eq!(
6608            actions[0]
6609                .2
6610                .iter()
6611                .map(|b| b.keystrokes()[0].clone())
6612                .collect::<Vec<_>>(),
6613            vec![Keystroke::parse("a").unwrap()],
6614        );
6615    }
6616
6617    #[crate::test(self)]
6618    async fn test_model_condition(cx: &mut TestAppContext) {
6619        struct Counter(usize);
6620
6621        impl super::Entity for Counter {
6622            type Event = ();
6623        }
6624
6625        impl Counter {
6626            fn inc(&mut self, cx: &mut ModelContext<Self>) {
6627                self.0 += 1;
6628                cx.notify();
6629            }
6630        }
6631
6632        let model = cx.add_model(|_| Counter(0));
6633
6634        let condition1 = model.condition(cx, |model, _| model.0 == 2);
6635        let condition2 = model.condition(cx, |model, _| model.0 == 3);
6636        smol::pin!(condition1, condition2);
6637
6638        model.update(cx, |model, cx| model.inc(cx));
6639        assert_eq!(poll_once(&mut condition1).await, None);
6640        assert_eq!(poll_once(&mut condition2).await, None);
6641
6642        model.update(cx, |model, cx| model.inc(cx));
6643        assert_eq!(poll_once(&mut condition1).await, Some(()));
6644        assert_eq!(poll_once(&mut condition2).await, None);
6645
6646        model.update(cx, |model, cx| model.inc(cx));
6647        assert_eq!(poll_once(&mut condition2).await, Some(()));
6648
6649        model.update(cx, |_, cx| cx.notify());
6650    }
6651
6652    #[crate::test(self)]
6653    #[should_panic]
6654    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
6655        struct Model;
6656
6657        impl super::Entity for Model {
6658            type Event = ();
6659        }
6660
6661        let model = cx.add_model(|_| Model);
6662        model.condition(cx, |_, _| false).await;
6663    }
6664
6665    #[crate::test(self)]
6666    #[should_panic(expected = "model dropped with pending condition")]
6667    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
6668        struct Model;
6669
6670        impl super::Entity for Model {
6671            type Event = ();
6672        }
6673
6674        let model = cx.add_model(|_| Model);
6675        let condition = model.condition(cx, |_, _| false);
6676        cx.update(|_| drop(model));
6677        condition.await;
6678    }
6679
6680    #[crate::test(self)]
6681    async fn test_view_condition(cx: &mut TestAppContext) {
6682        struct Counter(usize);
6683
6684        impl super::Entity for Counter {
6685            type Event = ();
6686        }
6687
6688        impl super::View for Counter {
6689            fn ui_name() -> &'static str {
6690                "test view"
6691            }
6692
6693            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6694                Empty::new().into_any()
6695            }
6696        }
6697
6698        impl Counter {
6699            fn inc(&mut self, cx: &mut ViewContext<Self>) {
6700                self.0 += 1;
6701                cx.notify();
6702            }
6703        }
6704
6705        let window = cx.add_window(|_| Counter(0));
6706        let view = window.root(cx);
6707
6708        let condition1 = view.condition(cx, |view, _| view.0 == 2);
6709        let condition2 = view.condition(cx, |view, _| view.0 == 3);
6710        smol::pin!(condition1, condition2);
6711
6712        view.update(cx, |view, cx| view.inc(cx));
6713        assert_eq!(poll_once(&mut condition1).await, None);
6714        assert_eq!(poll_once(&mut condition2).await, None);
6715
6716        view.update(cx, |view, cx| view.inc(cx));
6717        assert_eq!(poll_once(&mut condition1).await, Some(()));
6718        assert_eq!(poll_once(&mut condition2).await, None);
6719
6720        view.update(cx, |view, cx| view.inc(cx));
6721        assert_eq!(poll_once(&mut condition2).await, Some(()));
6722        view.update(cx, |_, cx| cx.notify());
6723    }
6724
6725    #[crate::test(self)]
6726    #[should_panic]
6727    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
6728        let window = cx.add_window(|_| TestView::default());
6729        window.root(cx).condition(cx, |_, _| false).await;
6730    }
6731
6732    #[crate::test(self)]
6733    #[should_panic(expected = "view dropped with pending condition")]
6734    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
6735        let window = cx.add_window(|_| TestView::default());
6736        let view = window.add_view(cx, |_| TestView::default());
6737
6738        let condition = view.condition(cx, |_, _| false);
6739        cx.update(|_| drop(view));
6740        condition.await;
6741    }
6742
6743    #[crate::test(self)]
6744    fn test_refresh_windows(cx: &mut TestAppContext) {
6745        struct View(usize);
6746
6747        impl super::Entity for View {
6748            type Event = ();
6749        }
6750
6751        impl super::View for View {
6752            fn ui_name() -> &'static str {
6753                "test view"
6754            }
6755
6756            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6757                Empty::new().into_any_named(format!("render count: {}", post_inc(&mut self.0)))
6758            }
6759        }
6760
6761        let window = cx.add_window(|_| View(0));
6762        let root_view = window.root(cx);
6763        window.update(cx, |cx| {
6764            assert_eq!(
6765                cx.window.rendered_views[&root_view.id()].name(),
6766                Some("render count: 0")
6767            );
6768        });
6769
6770        let view = window.update(cx, |cx| {
6771            cx.refresh_windows();
6772            cx.add_view(|_| View(0))
6773        });
6774
6775        window.update(cx, |cx| {
6776            assert_eq!(
6777                cx.window.rendered_views[&root_view.id()].name(),
6778                Some("render count: 1")
6779            );
6780            assert_eq!(
6781                cx.window.rendered_views[&view.id()].name(),
6782                Some("render count: 0")
6783            );
6784        });
6785
6786        cx.update(|cx| cx.refresh_windows());
6787
6788        window.update(cx, |cx| {
6789            assert_eq!(
6790                cx.window.rendered_views[&root_view.id()].name(),
6791                Some("render count: 2")
6792            );
6793            assert_eq!(
6794                cx.window.rendered_views[&view.id()].name(),
6795                Some("render count: 1")
6796            );
6797        });
6798
6799        cx.update(|cx| {
6800            cx.refresh_windows();
6801            drop(view);
6802        });
6803
6804        window.update(cx, |cx| {
6805            assert_eq!(
6806                cx.window.rendered_views[&root_view.id()].name(),
6807                Some("render count: 3")
6808            );
6809            assert_eq!(cx.window.rendered_views.len(), 1);
6810        });
6811    }
6812
6813    #[crate::test(self)]
6814    async fn test_labeled_tasks(cx: &mut TestAppContext) {
6815        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6816        let (mut sender, mut receiver) = postage::oneshot::channel::<()>();
6817        let task = cx
6818            .update(|cx| cx.spawn_labeled("Test Label", |_| async move { receiver.recv().await }));
6819
6820        assert_eq!(
6821            Some("Test Label"),
6822            cx.update(|cx| cx.active_labeled_tasks().next())
6823        );
6824        sender
6825            .send(())
6826            .await
6827            .expect("Could not send message to complete task");
6828        task.await;
6829
6830        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6831    }
6832
6833    #[crate::test(self)]
6834    async fn test_window_activation(cx: &mut TestAppContext) {
6835        struct View(&'static str);
6836
6837        impl super::Entity for View {
6838            type Event = ();
6839        }
6840
6841        impl super::View for View {
6842            fn ui_name() -> &'static str {
6843                "test view"
6844            }
6845
6846            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6847                Empty::new().into_any()
6848            }
6849        }
6850
6851        let events = Rc::new(RefCell::new(Vec::new()));
6852        let window_1 = cx.add_window(|cx: &mut ViewContext<View>| {
6853            cx.observe_window_activation({
6854                let events = events.clone();
6855                move |this, active, _| events.borrow_mut().push((this.0, active))
6856            })
6857            .detach();
6858            View("window 1")
6859        });
6860        assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
6861
6862        let window_2 = cx.add_window(|cx: &mut ViewContext<View>| {
6863            cx.observe_window_activation({
6864                let events = events.clone();
6865                move |this, active, _| events.borrow_mut().push((this.0, active))
6866            })
6867            .detach();
6868            View("window 2")
6869        });
6870        assert_eq!(
6871            mem::take(&mut *events.borrow_mut()),
6872            [("window 1", false), ("window 2", true)]
6873        );
6874
6875        let window_3 = cx.add_window(|cx: &mut ViewContext<View>| {
6876            cx.observe_window_activation({
6877                let events = events.clone();
6878                move |this, active, _| events.borrow_mut().push((this.0, active))
6879            })
6880            .detach();
6881            View("window 3")
6882        });
6883        assert_eq!(
6884            mem::take(&mut *events.borrow_mut()),
6885            [("window 2", false), ("window 3", true)]
6886        );
6887
6888        window_2.simulate_activation(cx);
6889        assert_eq!(
6890            mem::take(&mut *events.borrow_mut()),
6891            [("window 3", false), ("window 2", true)]
6892        );
6893
6894        window_1.simulate_activation(cx);
6895        assert_eq!(
6896            mem::take(&mut *events.borrow_mut()),
6897            [("window 2", false), ("window 1", true)]
6898        );
6899
6900        window_3.simulate_activation(cx);
6901        assert_eq!(
6902            mem::take(&mut *events.borrow_mut()),
6903            [("window 1", false), ("window 3", true)]
6904        );
6905
6906        window_3.simulate_activation(cx);
6907        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6908    }
6909
6910    #[crate::test(self)]
6911    fn test_child_view(cx: &mut TestAppContext) {
6912        struct Child {
6913            rendered: Rc<Cell<bool>>,
6914            dropped: Rc<Cell<bool>>,
6915        }
6916
6917        impl super::Entity for Child {
6918            type Event = ();
6919        }
6920
6921        impl super::View for Child {
6922            fn ui_name() -> &'static str {
6923                "child view"
6924            }
6925
6926            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6927                self.rendered.set(true);
6928                Empty::new().into_any()
6929            }
6930        }
6931
6932        impl Drop for Child {
6933            fn drop(&mut self) {
6934                self.dropped.set(true);
6935            }
6936        }
6937
6938        struct Parent {
6939            child: Option<ViewHandle<Child>>,
6940        }
6941
6942        impl super::Entity for Parent {
6943            type Event = ();
6944        }
6945
6946        impl super::View for Parent {
6947            fn ui_name() -> &'static str {
6948                "parent view"
6949            }
6950
6951            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
6952                if let Some(child) = self.child.as_ref() {
6953                    ChildView::new(child, cx).into_any()
6954                } else {
6955                    Empty::new().into_any()
6956                }
6957            }
6958        }
6959
6960        let child_rendered = Rc::new(Cell::new(false));
6961        let child_dropped = Rc::new(Cell::new(false));
6962        let window = cx.add_window(|cx| Parent {
6963            child: Some(cx.add_view(|_| Child {
6964                rendered: child_rendered.clone(),
6965                dropped: child_dropped.clone(),
6966            })),
6967        });
6968        let root_view = window.root(cx);
6969        assert!(child_rendered.take());
6970        assert!(!child_dropped.take());
6971
6972        root_view.update(cx, |view, cx| {
6973            view.child.take();
6974            cx.notify();
6975        });
6976        assert!(!child_rendered.take());
6977        assert!(child_dropped.take());
6978    }
6979
6980    #[derive(Default)]
6981    struct TestView {
6982        events: Vec<String>,
6983    }
6984
6985    impl Entity for TestView {
6986        type Event = String;
6987    }
6988
6989    impl View for TestView {
6990        fn ui_name() -> &'static str {
6991            "TestView"
6992        }
6993
6994        fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6995            Empty::new().into_any()
6996        }
6997    }
6998}