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