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