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