app.rs

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