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