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