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