app.rs

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