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