app.rs

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