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