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