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