app.rs

   1pub mod action;
   2mod callback_collection;
   3mod menu;
   4pub(crate) mod ref_counts;
   5#[cfg(any(test, feature = "test-support"))]
   6pub mod test_app_context;
   7pub(crate) mod window;
   8mod window_input_handler;
   9
  10use std::{
  11    any::{type_name, Any, TypeId},
  12    cell::RefCell,
  13    fmt::{self, Debug},
  14    hash::{Hash, Hasher},
  15    marker::PhantomData,
  16    mem,
  17    ops::{Deref, DerefMut, Range},
  18    path::{Path, PathBuf},
  19    pin::Pin,
  20    rc::{self, Rc},
  21    sync::{Arc, Weak},
  22    time::Duration,
  23};
  24
  25use anyhow::{anyhow, Context, Result};
  26use parking_lot::Mutex;
  27use postage::oneshot;
  28use smol::prelude::*;
  29use util::ResultExt;
  30use uuid::Uuid;
  31
  32pub use action::*;
  33use callback_collection::CallbackCollection;
  34use collections::{hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque};
  35pub use menu::*;
  36use platform::Event;
  37#[cfg(any(test, feature = "test-support"))]
  38use ref_counts::LeakDetector;
  39#[cfg(any(test, feature = "test-support"))]
  40pub use test_app_context::{ContextHandle, TestAppContext};
  41use window_input_handler::WindowInputHandler;
  42
  43use crate::{
  44    elements::{AnyRootElement, Element, RootElement},
  45    executor::{self, Task},
  46    keymap_matcher::{self, Binding, KeymapContext, KeymapMatcher, Keystroke, MatchResult},
  47    platform::{
  48        self, FontSystem, KeyDownEvent, KeyUpEvent, ModifiersChangedEvent, MouseButton,
  49        PathPromptOptions, Platform, PromptLevel, WindowBounds, WindowOptions,
  50    },
  51    util::post_inc,
  52    window::{Window, WindowContext},
  53    AssetCache, AssetSource, ClipboardItem, FontCache, MouseRegionId,
  54};
  55
  56use self::ref_counts::RefCounts;
  57
  58pub trait Entity: 'static {
  59    type Event;
  60
  61    fn release(&mut self, _: &mut AppContext) {}
  62    fn app_will_quit(
  63        &mut self,
  64        _: &mut AppContext,
  65    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
  66        None
  67    }
  68}
  69
  70pub trait View: Entity + Sized {
  71    fn ui_name() -> &'static str;
  72    fn render(&mut self, cx: &mut ViewContext<'_, '_, '_, Self>) -> Element<Self>;
  73    fn focus_in(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {}
  74    fn focus_out(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {}
  75    fn key_down(&mut self, _: &KeyDownEvent, _: &mut ViewContext<Self>) -> bool {
  76        false
  77    }
  78    fn key_up(&mut self, _: &KeyUpEvent, _: &mut ViewContext<Self>) -> bool {
  79        false
  80    }
  81    fn modifiers_changed(&mut self, _: &ModifiersChangedEvent, _: &mut ViewContext<Self>) -> bool {
  82        false
  83    }
  84
  85    fn keymap_context(&self, _: &AppContext) -> keymap_matcher::KeymapContext {
  86        Self::default_keymap_context()
  87    }
  88    fn default_keymap_context() -> keymap_matcher::KeymapContext {
  89        let mut cx = keymap_matcher::KeymapContext::default();
  90        cx.add_identifier(Self::ui_name());
  91        cx
  92    }
  93    fn debug_json(&self, _: &AppContext) -> serde_json::Value {
  94        serde_json::Value::Null
  95    }
  96
  97    fn text_for_range(&self, _: Range<usize>, _: &AppContext) -> Option<String> {
  98        None
  99    }
 100    fn selected_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
 101        None
 102    }
 103    fn marked_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
 104        None
 105    }
 106    fn unmark_text(&mut self, _: &mut ViewContext<Self>) {}
 107    fn replace_text_in_range(
 108        &mut self,
 109        _: Option<Range<usize>>,
 110        _: &str,
 111        _: &mut ViewContext<Self>,
 112    ) {
 113    }
 114    fn replace_and_mark_text_in_range(
 115        &mut self,
 116        _: Option<Range<usize>>,
 117        _: &str,
 118        _: Option<Range<usize>>,
 119        _: &mut ViewContext<Self>,
 120    ) {
 121    }
 122}
 123
 124pub trait ReadModel {
 125    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T;
 126}
 127
 128pub trait ReadModelWith {
 129    fn read_model_with<E: Entity, T>(
 130        &self,
 131        handle: &ModelHandle<E>,
 132        read: &mut dyn FnMut(&E, &AppContext) -> T,
 133    ) -> T;
 134}
 135
 136pub trait UpdateModel {
 137    fn update_model<T: Entity, O>(
 138        &mut self,
 139        handle: &ModelHandle<T>,
 140        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
 141    ) -> O;
 142}
 143
 144pub trait UpgradeModelHandle {
 145    fn upgrade_model_handle<T: Entity>(
 146        &self,
 147        handle: &WeakModelHandle<T>,
 148    ) -> Option<ModelHandle<T>>;
 149
 150    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool;
 151
 152    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle>;
 153}
 154
 155pub trait UpgradeViewHandle {
 156    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>>;
 157
 158    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle>;
 159}
 160
 161pub trait ReadView {
 162    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T;
 163}
 164
 165pub trait ReadViewWith {
 166    fn read_view_with<V, T>(
 167        &self,
 168        handle: &ViewHandle<V>,
 169        read: &mut dyn FnMut(&V, &AppContext) -> T,
 170    ) -> T
 171    where
 172        V: View;
 173}
 174
 175pub trait UpdateView {
 176    fn update_view<T, S>(
 177        &mut self,
 178        handle: &ViewHandle<T>,
 179        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 180    ) -> S
 181    where
 182        T: View;
 183}
 184
 185#[derive(Clone)]
 186pub struct App(Rc<RefCell<AppContext>>);
 187
 188#[derive(Clone)]
 189pub struct AsyncAppContext(Rc<RefCell<AppContext>>);
 190
 191impl App {
 192    pub fn new(asset_source: impl AssetSource) -> Result<Self> {
 193        let platform = platform::current::platform();
 194        let foreground = Rc::new(executor::Foreground::platform(platform.dispatcher())?);
 195        let foreground_platform = platform::current::foreground_platform(foreground.clone());
 196        let app = Self(Rc::new(RefCell::new(AppContext::new(
 197            foreground,
 198            Arc::new(executor::Background::new()),
 199            platform.clone(),
 200            foreground_platform.clone(),
 201            Arc::new(FontCache::new(platform.fonts())),
 202            Default::default(),
 203            asset_source,
 204        ))));
 205
 206        foreground_platform.on_quit(Box::new({
 207            let cx = app.0.clone();
 208            move || {
 209                cx.borrow_mut().quit();
 210            }
 211        }));
 212        setup_menu_handlers(foreground_platform.as_ref(), &app);
 213
 214        app.0.borrow_mut().weak_self = Some(Rc::downgrade(&app.0));
 215        Ok(app)
 216    }
 217
 218    pub fn background(&self) -> Arc<executor::Background> {
 219        self.0.borrow().background().clone()
 220    }
 221
 222    pub fn on_become_active<F>(self, mut callback: F) -> Self
 223    where
 224        F: 'static + FnMut(&mut AppContext),
 225    {
 226        let cx = self.0.clone();
 227        self.0
 228            .borrow_mut()
 229            .foreground_platform
 230            .on_become_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 231        self
 232    }
 233
 234    pub fn on_resign_active<F>(self, mut callback: F) -> Self
 235    where
 236        F: 'static + FnMut(&mut AppContext),
 237    {
 238        let cx = self.0.clone();
 239        self.0
 240            .borrow_mut()
 241            .foreground_platform
 242            .on_resign_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 243        self
 244    }
 245
 246    pub fn on_quit<F>(&mut self, mut callback: F) -> &mut Self
 247    where
 248        F: 'static + FnMut(&mut AppContext),
 249    {
 250        let cx = self.0.clone();
 251        self.0
 252            .borrow_mut()
 253            .foreground_platform
 254            .on_quit(Box::new(move || callback(&mut *cx.borrow_mut())));
 255        self
 256    }
 257
 258    /// Handle the application being re-activated when no windows are open.
 259    pub fn on_reopen<F>(&mut self, mut callback: F) -> &mut Self
 260    where
 261        F: 'static + FnMut(&mut AppContext),
 262    {
 263        let cx = self.0.clone();
 264        self.0
 265            .borrow_mut()
 266            .foreground_platform
 267            .on_reopen(Box::new(move || callback(&mut *cx.borrow_mut())));
 268        self
 269    }
 270
 271    pub fn on_event<F>(&mut self, mut callback: F) -> &mut Self
 272    where
 273        F: 'static + FnMut(Event, &mut AppContext) -> bool,
 274    {
 275        let cx = self.0.clone();
 276        self.0
 277            .borrow_mut()
 278            .foreground_platform
 279            .on_event(Box::new(move |event| {
 280                callback(event, &mut *cx.borrow_mut())
 281            }));
 282        self
 283    }
 284
 285    pub fn on_open_urls<F>(&mut self, mut callback: F) -> &mut Self
 286    where
 287        F: 'static + FnMut(Vec<String>, &mut AppContext),
 288    {
 289        let cx = self.0.clone();
 290        self.0
 291            .borrow_mut()
 292            .foreground_platform
 293            .on_open_urls(Box::new(move |urls| callback(urls, &mut *cx.borrow_mut())));
 294        self
 295    }
 296
 297    pub fn run<F>(self, on_finish_launching: F)
 298    where
 299        F: 'static + FnOnce(&mut AppContext),
 300    {
 301        let platform = self.0.borrow().foreground_platform.clone();
 302        platform.run(Box::new(move || {
 303            let mut cx = self.0.borrow_mut();
 304            let cx = &mut *cx;
 305            crate::views::init(cx);
 306            on_finish_launching(cx);
 307        }))
 308    }
 309
 310    pub fn platform(&self) -> Arc<dyn Platform> {
 311        self.0.borrow().platform.clone()
 312    }
 313
 314    pub fn font_cache(&self) -> Arc<FontCache> {
 315        self.0.borrow().font_cache.clone()
 316    }
 317
 318    fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, callback: F) -> T {
 319        let mut state = self.0.borrow_mut();
 320        let result = state.update(callback);
 321        state.pending_notifications.clear();
 322        result
 323    }
 324
 325    fn update_window<T, F: FnOnce(&mut WindowContext) -> T>(
 326        &mut self,
 327        window_id: usize,
 328        callback: F,
 329    ) -> Option<T> {
 330        let mut state = self.0.borrow_mut();
 331        let result = state.update_window(window_id, callback);
 332        state.pending_notifications.clear();
 333        result
 334    }
 335}
 336
 337impl AsyncAppContext {
 338    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
 339    where
 340        F: FnOnce(AsyncAppContext) -> Fut,
 341        Fut: 'static + Future<Output = T>,
 342        T: 'static,
 343    {
 344        self.0.borrow().foreground.spawn(f(self.clone()))
 345    }
 346
 347    pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
 348        callback(&*self.0.borrow())
 349    }
 350
 351    pub fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, callback: F) -> T {
 352        self.0.borrow_mut().update(callback)
 353    }
 354
 355    fn update_window<T, F: FnOnce(&mut WindowContext) -> T>(
 356        &mut self,
 357        window_id: usize,
 358        callback: F,
 359    ) -> Option<T> {
 360        self.0.borrow_mut().update_window(window_id, callback)
 361    }
 362
 363    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 364    where
 365        T: Entity,
 366        F: FnOnce(&mut ModelContext<T>) -> T,
 367    {
 368        self.update(|cx| cx.add_model(build_model))
 369    }
 370
 371    pub fn add_window<T, F>(
 372        &mut self,
 373        window_options: WindowOptions,
 374        build_root_view: F,
 375    ) -> (usize, ViewHandle<T>)
 376    where
 377        T: View,
 378        F: FnOnce(&mut ViewContext<T>) -> T,
 379    {
 380        self.update(|cx| cx.add_window(window_options, build_root_view))
 381    }
 382
 383    pub fn remove_window(&mut self, window_id: usize) {
 384        self.update(|cx| cx.remove_window(window_id))
 385    }
 386
 387    pub fn activate_window(&mut self, window_id: usize) {
 388        self.update_window(window_id, |cx| cx.activate_window());
 389    }
 390
 391    // TODO: Can we eliminate this method and move it to WindowContext then call it with update_window?s
 392    pub fn prompt(
 393        &mut self,
 394        window_id: usize,
 395        level: PromptLevel,
 396        msg: &str,
 397        answers: &[&str],
 398    ) -> Option<oneshot::Receiver<usize>> {
 399        self.update_window(window_id, |cx| cx.prompt(level, msg, answers))
 400    }
 401
 402    pub fn platform(&self) -> Arc<dyn Platform> {
 403        self.0.borrow().platform().clone()
 404    }
 405
 406    pub fn foreground(&self) -> Rc<executor::Foreground> {
 407        self.0.borrow().foreground.clone()
 408    }
 409
 410    pub fn background(&self) -> Arc<executor::Background> {
 411        self.0.borrow().background.clone()
 412    }
 413}
 414
 415impl UpdateModel for AsyncAppContext {
 416    fn update_model<E: Entity, O>(
 417        &mut self,
 418        handle: &ModelHandle<E>,
 419        update: &mut dyn FnMut(&mut E, &mut ModelContext<E>) -> O,
 420    ) -> O {
 421        self.0.borrow_mut().update_model(handle, update)
 422    }
 423}
 424
 425impl UpgradeModelHandle for AsyncAppContext {
 426    fn upgrade_model_handle<T: Entity>(
 427        &self,
 428        handle: &WeakModelHandle<T>,
 429    ) -> Option<ModelHandle<T>> {
 430        self.0.borrow().upgrade_model_handle(handle)
 431    }
 432
 433    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
 434        self.0.borrow().model_handle_is_upgradable(handle)
 435    }
 436
 437    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
 438        self.0.borrow().upgrade_any_model_handle(handle)
 439    }
 440}
 441
 442impl UpgradeViewHandle for AsyncAppContext {
 443    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
 444        self.0.borrow_mut().upgrade_view_handle(handle)
 445    }
 446
 447    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
 448        self.0.borrow_mut().upgrade_any_view_handle(handle)
 449    }
 450}
 451
 452impl ReadModelWith for AsyncAppContext {
 453    fn read_model_with<E: Entity, T>(
 454        &self,
 455        handle: &ModelHandle<E>,
 456        read: &mut dyn FnMut(&E, &AppContext) -> T,
 457    ) -> T {
 458        let cx = self.0.borrow();
 459        let cx = &*cx;
 460        read(handle.read(cx), cx)
 461    }
 462}
 463
 464impl UpdateView for AsyncAppContext {
 465    fn update_view<T, S>(
 466        &mut self,
 467        handle: &ViewHandle<T>,
 468        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 469    ) -> S
 470    where
 471        T: View,
 472    {
 473        self.0.borrow_mut().update_view(handle, update)
 474    }
 475}
 476
 477impl ReadViewWith for AsyncAppContext {
 478    fn read_view_with<V, T>(
 479        &self,
 480        handle: &ViewHandle<V>,
 481        read: &mut dyn FnMut(&V, &AppContext) -> T,
 482    ) -> T
 483    where
 484        V: View,
 485    {
 486        let cx = self.0.borrow();
 487        let cx = &*cx;
 488        read(handle.read(cx), cx)
 489    }
 490}
 491
 492type ActionCallback = dyn FnMut(&mut dyn AnyView, &dyn Action, &mut WindowContext, usize);
 493type GlobalActionCallback = dyn FnMut(&dyn Action, &mut AppContext);
 494
 495type SubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool>;
 496type GlobalSubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut AppContext)>;
 497type ObservationCallback = Box<dyn FnMut(&mut AppContext) -> bool>;
 498type GlobalObservationCallback = Box<dyn FnMut(&mut AppContext)>;
 499type FocusObservationCallback = Box<dyn FnMut(bool, &mut WindowContext) -> bool>;
 500type ReleaseObservationCallback = Box<dyn FnMut(&dyn Any, &mut AppContext)>;
 501type ActionObservationCallback = Box<dyn FnMut(TypeId, &mut AppContext)>;
 502type WindowActivationCallback = Box<dyn FnMut(bool, &mut WindowContext) -> bool>;
 503type WindowFullscreenCallback = Box<dyn FnMut(bool, &mut 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(focused_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    #[cfg(any(test, feature = "test-support"))]
3932    pub fn is_focused(&self, cx: &AppContext) -> bool {
3933        cx.read_window(self.window_id, |cx| {
3934            cx.focused_view_id() == Some(self.view_id)
3935        })
3936        .unwrap_or(false)
3937    }
3938}
3939
3940impl<T: View> Clone for ViewHandle<T> {
3941    fn clone(&self) -> Self {
3942        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
3943    }
3944}
3945
3946impl<T> PartialEq for ViewHandle<T> {
3947    fn eq(&self, other: &Self) -> bool {
3948        self.window_id == other.window_id && self.view_id == other.view_id
3949    }
3950}
3951
3952impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
3953    fn eq(&self, other: &WeakViewHandle<T>) -> bool {
3954        self.window_id == other.window_id && self.view_id == other.view_id
3955    }
3956}
3957
3958impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
3959    fn eq(&self, other: &ViewHandle<T>) -> bool {
3960        self.window_id == other.window_id && self.view_id == other.view_id
3961    }
3962}
3963
3964impl<T> Eq for ViewHandle<T> {}
3965
3966impl<T> Hash for ViewHandle<T> {
3967    fn hash<H: Hasher>(&self, state: &mut H) {
3968        self.window_id.hash(state);
3969        self.view_id.hash(state);
3970    }
3971}
3972
3973impl<T> Debug for ViewHandle<T> {
3974    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3975        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
3976            .field("window_id", &self.window_id)
3977            .field("view_id", &self.view_id)
3978            .finish()
3979    }
3980}
3981
3982impl<T: View> Handle<T> for ViewHandle<T> {
3983    type Weak = WeakViewHandle<T>;
3984
3985    fn id(&self) -> usize {
3986        self.view_id
3987    }
3988
3989    fn location(&self) -> EntityLocation {
3990        EntityLocation::View(self.window_id, self.view_id)
3991    }
3992
3993    fn downgrade(&self) -> Self::Weak {
3994        self.downgrade()
3995    }
3996
3997    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3998    where
3999        Self: Sized,
4000    {
4001        weak.upgrade(cx)
4002    }
4003}
4004
4005pub struct AnyViewHandle {
4006    window_id: usize,
4007    view_id: usize,
4008    view_type: TypeId,
4009    ref_counts: Arc<Mutex<RefCounts>>,
4010
4011    #[cfg(any(test, feature = "test-support"))]
4012    handle_id: usize,
4013}
4014
4015impl AnyViewHandle {
4016    fn new(
4017        window_id: usize,
4018        view_id: usize,
4019        view_type: TypeId,
4020        ref_counts: Arc<Mutex<RefCounts>>,
4021    ) -> Self {
4022        ref_counts.lock().inc_view(window_id, view_id);
4023
4024        #[cfg(any(test, feature = "test-support"))]
4025        let handle_id = ref_counts
4026            .lock()
4027            .leak_detector
4028            .lock()
4029            .handle_created(None, view_id);
4030
4031        Self {
4032            window_id,
4033            view_id,
4034            view_type,
4035            ref_counts,
4036            #[cfg(any(test, feature = "test-support"))]
4037            handle_id,
4038        }
4039    }
4040
4041    pub fn window_id(&self) -> usize {
4042        self.window_id
4043    }
4044
4045    pub fn id(&self) -> usize {
4046        self.view_id
4047    }
4048
4049    pub fn is<T: 'static>(&self) -> bool {
4050        TypeId::of::<T>() == self.view_type
4051    }
4052
4053    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
4054        if self.is::<T>() {
4055            Some(ViewHandle {
4056                any_handle: self,
4057                view_type: PhantomData,
4058            })
4059        } else {
4060            None
4061        }
4062    }
4063
4064    pub fn downcast_ref<T: View>(&self) -> Option<&ViewHandle<T>> {
4065        if self.is::<T>() {
4066            Some(unsafe { mem::transmute(self) })
4067        } else {
4068            None
4069        }
4070    }
4071
4072    pub fn downgrade(&self) -> AnyWeakViewHandle {
4073        AnyWeakViewHandle {
4074            window_id: self.window_id,
4075            view_id: self.view_id,
4076            view_type: self.view_type,
4077        }
4078    }
4079
4080    pub fn view_type(&self) -> TypeId {
4081        self.view_type
4082    }
4083
4084    pub fn debug_json<'a, 'b>(&self, cx: &'b WindowContext<'a, 'b>) -> serde_json::Value {
4085        cx.views
4086            .get(&(self.window_id, self.view_id))
4087            .map_or_else(|| serde_json::Value::Null, |view| view.debug_json(cx))
4088    }
4089}
4090
4091impl Clone for AnyViewHandle {
4092    fn clone(&self) -> Self {
4093        Self::new(
4094            self.window_id,
4095            self.view_id,
4096            self.view_type,
4097            self.ref_counts.clone(),
4098        )
4099    }
4100}
4101
4102impl<T> PartialEq<ViewHandle<T>> for AnyViewHandle {
4103    fn eq(&self, other: &ViewHandle<T>) -> bool {
4104        self.window_id == other.window_id && self.view_id == other.view_id
4105    }
4106}
4107
4108impl Drop for AnyViewHandle {
4109    fn drop(&mut self) {
4110        self.ref_counts
4111            .lock()
4112            .dec_view(self.window_id, self.view_id);
4113        #[cfg(any(test, feature = "test-support"))]
4114        self.ref_counts
4115            .lock()
4116            .leak_detector
4117            .lock()
4118            .handle_dropped(self.view_id, self.handle_id);
4119    }
4120}
4121
4122pub struct AnyModelHandle {
4123    model_id: usize,
4124    model_type: TypeId,
4125    ref_counts: Arc<Mutex<RefCounts>>,
4126
4127    #[cfg(any(test, feature = "test-support"))]
4128    handle_id: usize,
4129}
4130
4131impl AnyModelHandle {
4132    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
4133        ref_counts.lock().inc_model(model_id);
4134
4135        #[cfg(any(test, feature = "test-support"))]
4136        let handle_id = ref_counts
4137            .lock()
4138            .leak_detector
4139            .lock()
4140            .handle_created(None, model_id);
4141
4142        Self {
4143            model_id,
4144            model_type,
4145            ref_counts,
4146
4147            #[cfg(any(test, feature = "test-support"))]
4148            handle_id,
4149        }
4150    }
4151
4152    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
4153        if self.is::<T>() {
4154            Some(ModelHandle {
4155                any_handle: self,
4156                model_type: PhantomData,
4157            })
4158        } else {
4159            None
4160        }
4161    }
4162
4163    pub fn downgrade(&self) -> AnyWeakModelHandle {
4164        AnyWeakModelHandle {
4165            model_id: self.model_id,
4166            model_type: self.model_type,
4167        }
4168    }
4169
4170    pub fn is<T: Entity>(&self) -> bool {
4171        self.model_type == TypeId::of::<T>()
4172    }
4173
4174    pub fn model_type(&self) -> TypeId {
4175        self.model_type
4176    }
4177}
4178
4179impl Clone for AnyModelHandle {
4180    fn clone(&self) -> Self {
4181        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
4182    }
4183}
4184
4185impl Drop for AnyModelHandle {
4186    fn drop(&mut self) {
4187        let mut ref_counts = self.ref_counts.lock();
4188        ref_counts.dec_model(self.model_id);
4189
4190        #[cfg(any(test, feature = "test-support"))]
4191        ref_counts
4192            .leak_detector
4193            .lock()
4194            .handle_dropped(self.model_id, self.handle_id);
4195    }
4196}
4197
4198#[derive(Hash, PartialEq, Eq, Debug, Clone, Copy)]
4199pub struct AnyWeakModelHandle {
4200    model_id: usize,
4201    model_type: TypeId,
4202}
4203
4204impl AnyWeakModelHandle {
4205    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
4206        cx.upgrade_any_model_handle(self)
4207    }
4208    pub fn model_type(&self) -> TypeId {
4209        self.model_type
4210    }
4211
4212    fn is<T: 'static>(&self) -> bool {
4213        TypeId::of::<T>() == self.model_type
4214    }
4215
4216    pub fn downcast<T: Entity>(self) -> Option<WeakModelHandle<T>> {
4217        if self.is::<T>() {
4218            let result = Some(WeakModelHandle {
4219                any_handle: self,
4220                model_type: PhantomData,
4221            });
4222
4223            result
4224        } else {
4225            None
4226        }
4227    }
4228}
4229
4230#[derive(Debug, Copy)]
4231pub struct WeakViewHandle<T> {
4232    any_handle: AnyWeakViewHandle,
4233    view_type: PhantomData<T>,
4234}
4235
4236impl<T> WeakHandle for WeakViewHandle<T> {
4237    fn id(&self) -> usize {
4238        self.view_id
4239    }
4240}
4241
4242impl<T: View> WeakViewHandle<T> {
4243    fn new(window_id: usize, view_id: usize) -> Self {
4244        Self {
4245            any_handle: AnyWeakViewHandle {
4246                window_id,
4247                view_id,
4248                view_type: TypeId::of::<T>(),
4249            },
4250            view_type: PhantomData,
4251        }
4252    }
4253
4254    pub fn id(&self) -> usize {
4255        self.view_id
4256    }
4257
4258    pub fn window_id(&self) -> usize {
4259        self.window_id
4260    }
4261
4262    pub fn into_any(self) -> AnyWeakViewHandle {
4263        self.any_handle
4264    }
4265
4266    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
4267        cx.upgrade_view_handle(self)
4268    }
4269}
4270
4271impl<T> Deref for WeakViewHandle<T> {
4272    type Target = AnyWeakViewHandle;
4273
4274    fn deref(&self) -> &Self::Target {
4275        &self.any_handle
4276    }
4277}
4278
4279impl<T> Clone for WeakViewHandle<T> {
4280    fn clone(&self) -> Self {
4281        Self {
4282            any_handle: self.any_handle.clone(),
4283            view_type: PhantomData,
4284        }
4285    }
4286}
4287
4288impl<T> PartialEq for WeakViewHandle<T> {
4289    fn eq(&self, other: &Self) -> bool {
4290        self.window_id == other.window_id && self.view_id == other.view_id
4291    }
4292}
4293
4294impl<T> Eq for WeakViewHandle<T> {}
4295
4296impl<T> Hash for WeakViewHandle<T> {
4297    fn hash<H: Hasher>(&self, state: &mut H) {
4298        self.any_handle.hash(state);
4299    }
4300}
4301
4302#[derive(Debug, Clone, Copy)]
4303pub struct AnyWeakViewHandle {
4304    window_id: usize,
4305    view_id: usize,
4306    view_type: TypeId,
4307}
4308
4309impl AnyWeakViewHandle {
4310    pub fn id(&self) -> usize {
4311        self.view_id
4312    }
4313
4314    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<AnyViewHandle> {
4315        cx.upgrade_any_view_handle(self)
4316    }
4317}
4318
4319impl Hash for AnyWeakViewHandle {
4320    fn hash<H: Hasher>(&self, state: &mut H) {
4321        self.window_id.hash(state);
4322        self.view_id.hash(state);
4323        self.view_type.hash(state);
4324    }
4325}
4326
4327#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4328pub struct ElementStateId {
4329    view_id: usize,
4330    element_id: usize,
4331    tag: TypeId,
4332}
4333
4334pub struct ElementStateHandle<T> {
4335    value_type: PhantomData<T>,
4336    id: ElementStateId,
4337    ref_counts: Weak<Mutex<RefCounts>>,
4338}
4339
4340impl<T: 'static> ElementStateHandle<T> {
4341    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4342        ref_counts.lock().inc_element_state(id, frame_id);
4343        Self {
4344            value_type: PhantomData,
4345            id,
4346            ref_counts: Arc::downgrade(ref_counts),
4347        }
4348    }
4349
4350    pub fn id(&self) -> ElementStateId {
4351        self.id
4352    }
4353
4354    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
4355        cx.element_states
4356            .get(&self.id)
4357            .unwrap()
4358            .downcast_ref()
4359            .unwrap()
4360    }
4361
4362    pub fn update<C, D, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
4363    where
4364        C: DerefMut<Target = D>,
4365        D: DerefMut<Target = AppContext>,
4366    {
4367        let mut element_state = cx.deref_mut().element_states.remove(&self.id).unwrap();
4368        let result = f(element_state.downcast_mut().unwrap(), cx);
4369        cx.deref_mut().element_states.insert(self.id, element_state);
4370        result
4371    }
4372}
4373
4374impl<T> Drop for ElementStateHandle<T> {
4375    fn drop(&mut self) {
4376        if let Some(ref_counts) = self.ref_counts.upgrade() {
4377            ref_counts.lock().dec_element_state(self.id);
4378        }
4379    }
4380}
4381
4382#[must_use]
4383pub enum Subscription {
4384    Subscription(callback_collection::Subscription<usize, SubscriptionCallback>),
4385    Observation(callback_collection::Subscription<usize, ObservationCallback>),
4386    GlobalSubscription(callback_collection::Subscription<TypeId, GlobalSubscriptionCallback>),
4387    GlobalObservation(callback_collection::Subscription<TypeId, GlobalObservationCallback>),
4388    FocusObservation(callback_collection::Subscription<usize, FocusObservationCallback>),
4389    WindowActivationObservation(callback_collection::Subscription<usize, WindowActivationCallback>),
4390    WindowFullscreenObservation(callback_collection::Subscription<usize, WindowFullscreenCallback>),
4391    WindowBoundsObservation(callback_collection::Subscription<usize, WindowBoundsCallback>),
4392    KeystrokeObservation(callback_collection::Subscription<usize, KeystrokeCallback>),
4393    ReleaseObservation(callback_collection::Subscription<usize, ReleaseObservationCallback>),
4394    ActionObservation(callback_collection::Subscription<(), ActionObservationCallback>),
4395    ActiveLabeledTasksObservation(
4396        callback_collection::Subscription<(), ActiveLabeledTasksCallback>,
4397    ),
4398}
4399
4400impl Subscription {
4401    pub fn id(&self) -> usize {
4402        match self {
4403            Subscription::Subscription(subscription) => subscription.id(),
4404            Subscription::Observation(subscription) => subscription.id(),
4405            Subscription::GlobalSubscription(subscription) => subscription.id(),
4406            Subscription::GlobalObservation(subscription) => subscription.id(),
4407            Subscription::FocusObservation(subscription) => subscription.id(),
4408            Subscription::WindowActivationObservation(subscription) => subscription.id(),
4409            Subscription::WindowFullscreenObservation(subscription) => subscription.id(),
4410            Subscription::WindowBoundsObservation(subscription) => subscription.id(),
4411            Subscription::KeystrokeObservation(subscription) => subscription.id(),
4412            Subscription::ReleaseObservation(subscription) => subscription.id(),
4413            Subscription::ActionObservation(subscription) => subscription.id(),
4414            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.id(),
4415        }
4416    }
4417
4418    pub fn detach(&mut self) {
4419        match self {
4420            Subscription::Subscription(subscription) => subscription.detach(),
4421            Subscription::GlobalSubscription(subscription) => subscription.detach(),
4422            Subscription::Observation(subscription) => subscription.detach(),
4423            Subscription::GlobalObservation(subscription) => subscription.detach(),
4424            Subscription::FocusObservation(subscription) => subscription.detach(),
4425            Subscription::KeystrokeObservation(subscription) => subscription.detach(),
4426            Subscription::WindowActivationObservation(subscription) => subscription.detach(),
4427            Subscription::WindowFullscreenObservation(subscription) => subscription.detach(),
4428            Subscription::WindowBoundsObservation(subscription) => subscription.detach(),
4429            Subscription::ReleaseObservation(subscription) => subscription.detach(),
4430            Subscription::ActionObservation(subscription) => subscription.detach(),
4431            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.detach(),
4432        }
4433    }
4434}
4435
4436#[cfg(test)]
4437mod tests {
4438    use super::*;
4439    use crate::{
4440        actions,
4441        elements::*,
4442        impl_actions,
4443        platform::{MouseButton, MouseButtonEvent},
4444        window::ChildView,
4445    };
4446    use itertools::Itertools;
4447    use postage::{sink::Sink, stream::Stream};
4448    use serde::Deserialize;
4449    use smol::future::poll_once;
4450    use std::{
4451        cell::Cell,
4452        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
4453    };
4454
4455    #[crate::test(self)]
4456    fn test_model_handles(cx: &mut AppContext) {
4457        struct Model {
4458            other: Option<ModelHandle<Model>>,
4459            events: Vec<String>,
4460        }
4461
4462        impl Entity for Model {
4463            type Event = usize;
4464        }
4465
4466        impl Model {
4467            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
4468                if let Some(other) = other.as_ref() {
4469                    cx.observe(other, |me, _, _| {
4470                        me.events.push("notified".into());
4471                    })
4472                    .detach();
4473                    cx.subscribe(other, |me, _, event, _| {
4474                        me.events.push(format!("observed event {}", event));
4475                    })
4476                    .detach();
4477                }
4478
4479                Self {
4480                    other,
4481                    events: Vec::new(),
4482                }
4483            }
4484        }
4485
4486        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
4487        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
4488        assert_eq!(cx.models.len(), 2);
4489
4490        handle_1.update(cx, |model, cx| {
4491            model.events.push("updated".into());
4492            cx.emit(1);
4493            cx.notify();
4494            cx.emit(2);
4495        });
4496        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4497        assert_eq!(
4498            handle_2.read(cx).events,
4499            vec![
4500                "observed event 1".to_string(),
4501                "notified".to_string(),
4502                "observed event 2".to_string(),
4503            ]
4504        );
4505
4506        handle_2.update(cx, |model, _| {
4507            drop(handle_1);
4508            model.other.take();
4509        });
4510
4511        assert_eq!(cx.models.len(), 1);
4512        assert!(cx.subscriptions.is_empty());
4513        assert!(cx.observations.is_empty());
4514    }
4515
4516    #[crate::test(self)]
4517    fn test_model_events(cx: &mut AppContext) {
4518        #[derive(Default)]
4519        struct Model {
4520            events: Vec<usize>,
4521        }
4522
4523        impl Entity for Model {
4524            type Event = usize;
4525        }
4526
4527        let handle_1 = cx.add_model(|_| Model::default());
4528        let handle_2 = cx.add_model(|_| Model::default());
4529
4530        handle_1.update(cx, |_, cx| {
4531            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
4532                model.events.push(*event);
4533
4534                cx.subscribe(&emitter, |model, _, event, _| {
4535                    model.events.push(*event * 2);
4536                })
4537                .detach();
4538            })
4539            .detach();
4540        });
4541
4542        handle_2.update(cx, |_, c| c.emit(7));
4543        assert_eq!(handle_1.read(cx).events, vec![7]);
4544
4545        handle_2.update(cx, |_, c| c.emit(5));
4546        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4547    }
4548
4549    #[crate::test(self)]
4550    fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
4551        #[derive(Default)]
4552        struct Model;
4553
4554        impl Entity for Model {
4555            type Event = ();
4556        }
4557
4558        let events = Rc::new(RefCell::new(Vec::new()));
4559        cx.add_model(|cx| {
4560            drop(cx.subscribe(&cx.handle(), {
4561                let events = events.clone();
4562                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
4563            }));
4564            cx.subscribe(&cx.handle(), {
4565                let events = events.clone();
4566                move |_, _, _, _| events.borrow_mut().push("before emit")
4567            })
4568            .detach();
4569            cx.emit(());
4570            cx.subscribe(&cx.handle(), {
4571                let events = events.clone();
4572                move |_, _, _, _| events.borrow_mut().push("after emit")
4573            })
4574            .detach();
4575            Model
4576        });
4577        assert_eq!(*events.borrow(), ["before emit"]);
4578    }
4579
4580    #[crate::test(self)]
4581    fn test_observe_and_notify_from_model(cx: &mut AppContext) {
4582        #[derive(Default)]
4583        struct Model {
4584            count: usize,
4585            events: Vec<usize>,
4586        }
4587
4588        impl Entity for Model {
4589            type Event = ();
4590        }
4591
4592        let handle_1 = cx.add_model(|_| Model::default());
4593        let handle_2 = cx.add_model(|_| Model::default());
4594
4595        handle_1.update(cx, |_, c| {
4596            c.observe(&handle_2, move |model, observed, c| {
4597                model.events.push(observed.read(c).count);
4598                c.observe(&observed, |model, observed, c| {
4599                    model.events.push(observed.read(c).count * 2);
4600                })
4601                .detach();
4602            })
4603            .detach();
4604        });
4605
4606        handle_2.update(cx, |model, c| {
4607            model.count = 7;
4608            c.notify()
4609        });
4610        assert_eq!(handle_1.read(cx).events, vec![7]);
4611
4612        handle_2.update(cx, |model, c| {
4613            model.count = 5;
4614            c.notify()
4615        });
4616        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
4617    }
4618
4619    #[crate::test(self)]
4620    fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
4621        #[derive(Default)]
4622        struct Model;
4623
4624        impl Entity for Model {
4625            type Event = ();
4626        }
4627
4628        let events = Rc::new(RefCell::new(Vec::new()));
4629        cx.add_model(|cx| {
4630            drop(cx.observe(&cx.handle(), {
4631                let events = events.clone();
4632                move |_, _, _| events.borrow_mut().push("dropped before flush")
4633            }));
4634            cx.observe(&cx.handle(), {
4635                let events = events.clone();
4636                move |_, _, _| events.borrow_mut().push("before notify")
4637            })
4638            .detach();
4639            cx.notify();
4640            cx.observe(&cx.handle(), {
4641                let events = events.clone();
4642                move |_, _, _| events.borrow_mut().push("after notify")
4643            })
4644            .detach();
4645            Model
4646        });
4647        assert_eq!(*events.borrow(), ["before notify"]);
4648    }
4649
4650    #[crate::test(self)]
4651    fn test_defer_and_after_window_update(cx: &mut AppContext) {
4652        struct View {
4653            render_count: usize,
4654        }
4655
4656        impl Entity for View {
4657            type Event = usize;
4658        }
4659
4660        impl super::View for View {
4661            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
4662                post_inc(&mut self.render_count);
4663                Empty::new().boxed()
4664            }
4665
4666            fn ui_name() -> &'static str {
4667                "View"
4668            }
4669        }
4670
4671        let (_, view) = cx.add_window(Default::default(), |_| View { render_count: 0 });
4672        let called_defer = Rc::new(AtomicBool::new(false));
4673        let called_after_window_update = Rc::new(AtomicBool::new(false));
4674
4675        view.update(cx, |this, cx| {
4676            assert_eq!(this.render_count, 1);
4677            cx.defer({
4678                let called_defer = called_defer.clone();
4679                move |this, _| {
4680                    assert_eq!(this.render_count, 1);
4681                    called_defer.store(true, SeqCst);
4682                }
4683            });
4684            cx.after_window_update({
4685                let called_after_window_update = called_after_window_update.clone();
4686                move |this, cx| {
4687                    assert_eq!(this.render_count, 2);
4688                    called_after_window_update.store(true, SeqCst);
4689                    cx.notify();
4690                }
4691            });
4692            assert!(!called_defer.load(SeqCst));
4693            assert!(!called_after_window_update.load(SeqCst));
4694            cx.notify();
4695        });
4696
4697        assert!(called_defer.load(SeqCst));
4698        assert!(called_after_window_update.load(SeqCst));
4699        assert_eq!(view.read(cx).render_count, 3);
4700    }
4701
4702    #[crate::test(self)]
4703    fn test_view_handles(cx: &mut AppContext) {
4704        struct View {
4705            other: Option<ViewHandle<View>>,
4706            events: Vec<String>,
4707        }
4708
4709        impl Entity for View {
4710            type Event = usize;
4711        }
4712
4713        impl super::View for View {
4714            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
4715                Empty::new().boxed()
4716            }
4717
4718            fn ui_name() -> &'static str {
4719                "View"
4720            }
4721        }
4722
4723        impl View {
4724            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
4725                if let Some(other) = other.as_ref() {
4726                    cx.subscribe(other, |me, _, event, _| {
4727                        me.events.push(format!("observed event {}", event));
4728                    })
4729                    .detach();
4730                }
4731                Self {
4732                    other,
4733                    events: Vec::new(),
4734                }
4735            }
4736        }
4737
4738        let (_, root_view) = cx.add_window(Default::default(), |cx| View::new(None, cx));
4739        let handle_1 = cx.add_view(&root_view, |cx| View::new(None, cx));
4740        let handle_2 = cx.add_view(&root_view, |cx| View::new(Some(handle_1.clone()), cx));
4741        assert_eq!(cx.views.len(), 3);
4742
4743        handle_1.update(cx, |view, cx| {
4744            view.events.push("updated".into());
4745            cx.emit(1);
4746            cx.emit(2);
4747        });
4748        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4749        assert_eq!(
4750            handle_2.read(cx).events,
4751            vec![
4752                "observed event 1".to_string(),
4753                "observed event 2".to_string(),
4754            ]
4755        );
4756
4757        handle_2.update(cx, |view, _| {
4758            drop(handle_1);
4759            view.other.take();
4760        });
4761
4762        assert_eq!(cx.views.len(), 2);
4763        assert!(cx.subscriptions.is_empty());
4764        assert!(cx.observations.is_empty());
4765    }
4766
4767    #[crate::test(self)]
4768    fn test_add_window(cx: &mut AppContext) {
4769        struct View {
4770            mouse_down_count: Arc<AtomicUsize>,
4771        }
4772
4773        impl Entity for View {
4774            type Event = ();
4775        }
4776
4777        impl super::View for View {
4778            fn render(&mut self, cx: &mut ViewContext<Self>) -> Element<Self> {
4779                enum Handler {}
4780                let mouse_down_count = self.mouse_down_count.clone();
4781                MouseEventHandler::<Handler, _>::new(0, cx, |_, _| Empty::new().boxed())
4782                    .on_down(MouseButton::Left, move |_, _, _| {
4783                        mouse_down_count.fetch_add(1, SeqCst);
4784                    })
4785                    .boxed()
4786            }
4787
4788            fn ui_name() -> &'static str {
4789                "View"
4790            }
4791        }
4792
4793        let mouse_down_count = Arc::new(AtomicUsize::new(0));
4794        let (window_id, _) = cx.add_window(Default::default(), |_| View {
4795            mouse_down_count: mouse_down_count.clone(),
4796        });
4797
4798        cx.update_window(window_id, |cx| {
4799            // Ensure window's root element is in a valid lifecycle state.
4800            cx.dispatch_event(
4801                Event::MouseDown(MouseButtonEvent {
4802                    position: Default::default(),
4803                    button: MouseButton::Left,
4804                    modifiers: Default::default(),
4805                    click_count: 1,
4806                }),
4807                false,
4808            );
4809            assert_eq!(mouse_down_count.load(SeqCst), 1);
4810        });
4811    }
4812
4813    #[crate::test(self)]
4814    fn test_entity_release_hooks(cx: &mut AppContext) {
4815        struct Model {
4816            released: Rc<Cell<bool>>,
4817        }
4818
4819        struct View {
4820            released: Rc<Cell<bool>>,
4821        }
4822
4823        impl Entity for Model {
4824            type Event = ();
4825
4826            fn release(&mut self, _: &mut AppContext) {
4827                self.released.set(true);
4828            }
4829        }
4830
4831        impl Entity for View {
4832            type Event = ();
4833
4834            fn release(&mut self, _: &mut AppContext) {
4835                self.released.set(true);
4836            }
4837        }
4838
4839        impl super::View for View {
4840            fn ui_name() -> &'static str {
4841                "View"
4842            }
4843
4844            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
4845                Empty::new().boxed()
4846            }
4847        }
4848
4849        let model_released = Rc::new(Cell::new(false));
4850        let model_release_observed = Rc::new(Cell::new(false));
4851        let view_released = Rc::new(Cell::new(false));
4852        let view_release_observed = Rc::new(Cell::new(false));
4853
4854        let model = cx.add_model(|_| Model {
4855            released: model_released.clone(),
4856        });
4857        let (window_id, view) = cx.add_window(Default::default(), |_| View {
4858            released: view_released.clone(),
4859        });
4860        assert!(!model_released.get());
4861        assert!(!view_released.get());
4862
4863        cx.observe_release(&model, {
4864            let model_release_observed = model_release_observed.clone();
4865            move |_, _| model_release_observed.set(true)
4866        })
4867        .detach();
4868        cx.observe_release(&view, {
4869            let view_release_observed = view_release_observed.clone();
4870            move |_, _| view_release_observed.set(true)
4871        })
4872        .detach();
4873
4874        cx.update(move |_| {
4875            drop(model);
4876        });
4877        assert!(model_released.get());
4878        assert!(model_release_observed.get());
4879
4880        drop(view);
4881        cx.remove_window(window_id);
4882        assert!(view_released.get());
4883        assert!(view_release_observed.get());
4884    }
4885
4886    #[crate::test(self)]
4887    fn test_view_events(cx: &mut AppContext) {
4888        struct Model;
4889
4890        impl Entity for Model {
4891            type Event = String;
4892        }
4893
4894        let (_, handle_1) = cx.add_window(Default::default(), |_| TestView::default());
4895        let handle_2 = cx.add_view(&handle_1, |_| TestView::default());
4896        let handle_3 = cx.add_model(|_| Model);
4897
4898        handle_1.update(cx, |_, cx| {
4899            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
4900                me.events.push(event.clone());
4901
4902                cx.subscribe(&emitter, |me, _, event, _| {
4903                    me.events.push(format!("{event} from inner"));
4904                })
4905                .detach();
4906            })
4907            .detach();
4908
4909            cx.subscribe(&handle_3, |me, _, event, _| {
4910                me.events.push(event.clone());
4911            })
4912            .detach();
4913        });
4914
4915        handle_2.update(cx, |_, c| c.emit("7".into()));
4916        assert_eq!(handle_1.read(cx).events, vec!["7"]);
4917
4918        handle_2.update(cx, |_, c| c.emit("5".into()));
4919        assert_eq!(handle_1.read(cx).events, vec!["7", "5", "5 from inner"]);
4920
4921        handle_3.update(cx, |_, c| c.emit("9".into()));
4922        assert_eq!(
4923            handle_1.read(cx).events,
4924            vec!["7", "5", "5 from inner", "9"]
4925        );
4926    }
4927
4928    #[crate::test(self)]
4929    fn test_global_events(cx: &mut AppContext) {
4930        #[derive(Clone, Debug, Eq, PartialEq)]
4931        struct GlobalEvent(u64);
4932
4933        let events = Rc::new(RefCell::new(Vec::new()));
4934        let first_subscription;
4935        let second_subscription;
4936
4937        {
4938            let events = events.clone();
4939            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
4940                events.borrow_mut().push(("First", e.clone()));
4941            });
4942        }
4943
4944        {
4945            let events = events.clone();
4946            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
4947                events.borrow_mut().push(("Second", e.clone()));
4948            });
4949        }
4950
4951        cx.update(|cx| {
4952            cx.emit_global(GlobalEvent(1));
4953            cx.emit_global(GlobalEvent(2));
4954        });
4955
4956        drop(first_subscription);
4957
4958        cx.update(|cx| {
4959            cx.emit_global(GlobalEvent(3));
4960        });
4961
4962        drop(second_subscription);
4963
4964        cx.update(|cx| {
4965            cx.emit_global(GlobalEvent(4));
4966        });
4967
4968        assert_eq!(
4969            &*events.borrow(),
4970            &[
4971                ("First", GlobalEvent(1)),
4972                ("Second", GlobalEvent(1)),
4973                ("First", GlobalEvent(2)),
4974                ("Second", GlobalEvent(2)),
4975                ("Second", GlobalEvent(3)),
4976            ]
4977        );
4978    }
4979
4980    #[crate::test(self)]
4981    fn test_global_events_emitted_before_subscription_in_same_update_cycle(cx: &mut AppContext) {
4982        let events = Rc::new(RefCell::new(Vec::new()));
4983        cx.update(|cx| {
4984            {
4985                let events = events.clone();
4986                drop(cx.subscribe_global(move |_: &(), _| {
4987                    events.borrow_mut().push("dropped before emit");
4988                }));
4989            }
4990
4991            {
4992                let events = events.clone();
4993                cx.subscribe_global(move |_: &(), _| {
4994                    events.borrow_mut().push("before emit");
4995                })
4996                .detach();
4997            }
4998
4999            cx.emit_global(());
5000
5001            {
5002                let events = events.clone();
5003                cx.subscribe_global(move |_: &(), _| {
5004                    events.borrow_mut().push("after emit");
5005                })
5006                .detach();
5007            }
5008        });
5009
5010        assert_eq!(*events.borrow(), ["before emit"]);
5011    }
5012
5013    #[crate::test(self)]
5014    fn test_global_nested_events(cx: &mut AppContext) {
5015        #[derive(Clone, Debug, Eq, PartialEq)]
5016        struct GlobalEvent(u64);
5017
5018        let events = Rc::new(RefCell::new(Vec::new()));
5019
5020        {
5021            let events = events.clone();
5022            cx.subscribe_global(move |e: &GlobalEvent, cx| {
5023                events.borrow_mut().push(("Outer", e.clone()));
5024
5025                if e.0 == 1 {
5026                    let events = events.clone();
5027                    cx.subscribe_global(move |e: &GlobalEvent, _| {
5028                        events.borrow_mut().push(("Inner", e.clone()));
5029                    })
5030                    .detach();
5031                }
5032            })
5033            .detach();
5034        }
5035
5036        cx.update(|cx| {
5037            cx.emit_global(GlobalEvent(1));
5038            cx.emit_global(GlobalEvent(2));
5039            cx.emit_global(GlobalEvent(3));
5040        });
5041        cx.update(|cx| {
5042            cx.emit_global(GlobalEvent(4));
5043        });
5044
5045        assert_eq!(
5046            &*events.borrow(),
5047            &[
5048                ("Outer", GlobalEvent(1)),
5049                ("Outer", GlobalEvent(2)),
5050                ("Outer", GlobalEvent(3)),
5051                ("Outer", GlobalEvent(4)),
5052                ("Inner", GlobalEvent(4)),
5053            ]
5054        );
5055    }
5056
5057    #[crate::test(self)]
5058    fn test_global(cx: &mut AppContext) {
5059        type Global = usize;
5060
5061        let observation_count = Rc::new(RefCell::new(0));
5062        let subscription = cx.observe_global::<Global, _>({
5063            let observation_count = observation_count.clone();
5064            move |_| {
5065                *observation_count.borrow_mut() += 1;
5066            }
5067        });
5068
5069        assert!(!cx.has_global::<Global>());
5070        assert_eq!(cx.default_global::<Global>(), &0);
5071        assert_eq!(*observation_count.borrow(), 1);
5072        assert!(cx.has_global::<Global>());
5073        assert_eq!(
5074            cx.update_global::<Global, _, _>(|global, _| {
5075                *global = 1;
5076                "Update Result"
5077            }),
5078            "Update Result"
5079        );
5080        assert_eq!(*observation_count.borrow(), 2);
5081        assert_eq!(cx.global::<Global>(), &1);
5082
5083        drop(subscription);
5084        cx.update_global::<Global, _, _>(|global, _| {
5085            *global = 2;
5086        });
5087        assert_eq!(*observation_count.borrow(), 2);
5088
5089        type OtherGlobal = f32;
5090
5091        let observation_count = Rc::new(RefCell::new(0));
5092        cx.observe_global::<OtherGlobal, _>({
5093            let observation_count = observation_count.clone();
5094            move |_| {
5095                *observation_count.borrow_mut() += 1;
5096            }
5097        })
5098        .detach();
5099
5100        assert_eq!(
5101            cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
5102                assert_eq!(global, &0.0);
5103                *global = 2.0;
5104                "Default update result"
5105            }),
5106            "Default update result"
5107        );
5108        assert_eq!(cx.global::<OtherGlobal>(), &2.0);
5109        assert_eq!(*observation_count.borrow(), 1);
5110    }
5111
5112    #[crate::test(self)]
5113    fn test_dropping_subscribers(cx: &mut AppContext) {
5114        struct Model;
5115
5116        impl Entity for Model {
5117            type Event = ();
5118        }
5119
5120        let (_, root_view) = cx.add_window(Default::default(), |_| TestView::default());
5121        let observing_view = cx.add_view(&root_view, |_| TestView::default());
5122        let emitting_view = cx.add_view(&root_view, |_| TestView::default());
5123        let observing_model = cx.add_model(|_| Model);
5124        let observed_model = cx.add_model(|_| Model);
5125
5126        observing_view.update(cx, |_, cx| {
5127            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
5128            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5129        });
5130        observing_model.update(cx, |_, cx| {
5131            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5132        });
5133
5134        cx.update(|_| {
5135            drop(observing_view);
5136            drop(observing_model);
5137        });
5138
5139        emitting_view.update(cx, |_, cx| cx.emit(Default::default()));
5140        observed_model.update(cx, |_, cx| cx.emit(()));
5141    }
5142
5143    #[crate::test(self)]
5144    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
5145        let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
5146            drop(cx.subscribe(&cx.handle(), {
5147                move |this, _, _, _| this.events.push("dropped before flush".into())
5148            }));
5149            cx.subscribe(&cx.handle(), {
5150                move |this, _, _, _| this.events.push("before emit".into())
5151            })
5152            .detach();
5153            cx.emit("the event".into());
5154            cx.subscribe(&cx.handle(), {
5155                move |this, _, _, _| this.events.push("after emit".into())
5156            })
5157            .detach();
5158            TestView { events: Vec::new() }
5159        });
5160
5161        assert_eq!(view.read(cx).events, ["before emit"]);
5162    }
5163
5164    #[crate::test(self)]
5165    fn test_observe_and_notify_from_view(cx: &mut AppContext) {
5166        #[derive(Default)]
5167        struct Model {
5168            state: String,
5169        }
5170
5171        impl Entity for Model {
5172            type Event = ();
5173        }
5174
5175        let (_, view) = cx.add_window(Default::default(), |_| TestView::default());
5176        let model = cx.add_model(|_| Model {
5177            state: "old-state".into(),
5178        });
5179
5180        view.update(cx, |_, c| {
5181            c.observe(&model, |me, observed, cx| {
5182                me.events.push(observed.read(cx).state.clone())
5183            })
5184            .detach();
5185        });
5186
5187        model.update(cx, |model, cx| {
5188            model.state = "new-state".into();
5189            cx.notify();
5190        });
5191        assert_eq!(view.read(cx).events, vec!["new-state"]);
5192    }
5193
5194    #[crate::test(self)]
5195    fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
5196        let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
5197            drop(cx.observe(&cx.handle(), {
5198                move |this, _, _| this.events.push("dropped before flush".into())
5199            }));
5200            cx.observe(&cx.handle(), {
5201                move |this, _, _| this.events.push("before notify".into())
5202            })
5203            .detach();
5204            cx.notify();
5205            cx.observe(&cx.handle(), {
5206                move |this, _, _| this.events.push("after notify".into())
5207            })
5208            .detach();
5209            TestView { events: Vec::new() }
5210        });
5211
5212        assert_eq!(view.read(cx).events, ["before notify"]);
5213    }
5214
5215    #[crate::test(self)]
5216    fn test_notify_and_drop_observe_subscription_in_same_update_cycle(cx: &mut AppContext) {
5217        struct Model;
5218        impl Entity for Model {
5219            type Event = ();
5220        }
5221
5222        let model = cx.add_model(|_| Model);
5223        let (_, view) = cx.add_window(Default::default(), |_| TestView::default());
5224
5225        view.update(cx, |_, cx| {
5226            model.update(cx, |_, cx| cx.notify());
5227            drop(cx.observe(&model, move |this, _, _| {
5228                this.events.push("model notified".into());
5229            }));
5230            model.update(cx, |_, cx| cx.notify());
5231        });
5232
5233        for _ in 0..3 {
5234            model.update(cx, |_, cx| cx.notify());
5235        }
5236
5237        assert_eq!(view.read(cx).events, Vec::<String>::new());
5238    }
5239
5240    #[crate::test(self)]
5241    fn test_dropping_observers(cx: &mut AppContext) {
5242        struct Model;
5243
5244        impl Entity for Model {
5245            type Event = ();
5246        }
5247
5248        let (_, root_view) = cx.add_window(Default::default(), |_| TestView::default());
5249        let observing_view = cx.add_view(&root_view, |_| TestView::default());
5250        let observing_model = cx.add_model(|_| Model);
5251        let observed_model = cx.add_model(|_| Model);
5252
5253        observing_view.update(cx, |_, cx| {
5254            cx.observe(&observed_model, |_, _, _| {}).detach();
5255        });
5256        observing_model.update(cx, |_, cx| {
5257            cx.observe(&observed_model, |_, _, _| {}).detach();
5258        });
5259
5260        cx.update(|_| {
5261            drop(observing_view);
5262            drop(observing_model);
5263        });
5264
5265        observed_model.update(cx, |_, cx| cx.notify());
5266    }
5267
5268    #[crate::test(self)]
5269    fn test_dropping_subscriptions_during_callback(cx: &mut AppContext) {
5270        struct Model;
5271
5272        impl Entity for Model {
5273            type Event = u64;
5274        }
5275
5276        // Events
5277        let observing_model = cx.add_model(|_| Model);
5278        let observed_model = cx.add_model(|_| Model);
5279
5280        let events = Rc::new(RefCell::new(Vec::new()));
5281
5282        observing_model.update(cx, |_, cx| {
5283            let events = events.clone();
5284            let subscription = Rc::new(RefCell::new(None));
5285            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
5286                let subscription = subscription.clone();
5287                move |_, _, e, _| {
5288                    subscription.borrow_mut().take();
5289                    events.borrow_mut().push(*e);
5290                }
5291            }));
5292        });
5293
5294        observed_model.update(cx, |_, cx| {
5295            cx.emit(1);
5296            cx.emit(2);
5297        });
5298
5299        assert_eq!(*events.borrow(), [1]);
5300
5301        // Global Events
5302        #[derive(Clone, Debug, Eq, PartialEq)]
5303        struct GlobalEvent(u64);
5304
5305        let events = Rc::new(RefCell::new(Vec::new()));
5306
5307        {
5308            let events = events.clone();
5309            let subscription = Rc::new(RefCell::new(None));
5310            *subscription.borrow_mut() = Some(cx.subscribe_global({
5311                let subscription = subscription.clone();
5312                move |e: &GlobalEvent, _| {
5313                    subscription.borrow_mut().take();
5314                    events.borrow_mut().push(e.clone());
5315                }
5316            }));
5317        }
5318
5319        cx.update(|cx| {
5320            cx.emit_global(GlobalEvent(1));
5321            cx.emit_global(GlobalEvent(2));
5322        });
5323
5324        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
5325
5326        // Model Observation
5327        let observing_model = cx.add_model(|_| Model);
5328        let observed_model = cx.add_model(|_| Model);
5329
5330        let observation_count = Rc::new(RefCell::new(0));
5331
5332        observing_model.update(cx, |_, cx| {
5333            let observation_count = observation_count.clone();
5334            let subscription = Rc::new(RefCell::new(None));
5335            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
5336                let subscription = subscription.clone();
5337                move |_, _, _| {
5338                    subscription.borrow_mut().take();
5339                    *observation_count.borrow_mut() += 1;
5340                }
5341            }));
5342        });
5343
5344        observed_model.update(cx, |_, cx| {
5345            cx.notify();
5346        });
5347
5348        observed_model.update(cx, |_, cx| {
5349            cx.notify();
5350        });
5351
5352        assert_eq!(*observation_count.borrow(), 1);
5353
5354        // View Observation
5355        struct View;
5356
5357        impl Entity for View {
5358            type Event = ();
5359        }
5360
5361        impl super::View for View {
5362            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5363                Empty::new().boxed()
5364            }
5365
5366            fn ui_name() -> &'static str {
5367                "View"
5368            }
5369        }
5370
5371        let (_, root_view) = cx.add_window(Default::default(), |_| View);
5372        let observing_view = cx.add_view(&root_view, |_| View);
5373        let observed_view = cx.add_view(&root_view, |_| View);
5374
5375        let observation_count = Rc::new(RefCell::new(0));
5376        observing_view.update(cx, |_, cx| {
5377            let observation_count = observation_count.clone();
5378            let subscription = Rc::new(RefCell::new(None));
5379            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
5380                let subscription = subscription.clone();
5381                move |_, _, _| {
5382                    subscription.borrow_mut().take();
5383                    *observation_count.borrow_mut() += 1;
5384                }
5385            }));
5386        });
5387
5388        observed_view.update(cx, |_, cx| {
5389            cx.notify();
5390        });
5391
5392        observed_view.update(cx, |_, cx| {
5393            cx.notify();
5394        });
5395
5396        assert_eq!(*observation_count.borrow(), 1);
5397
5398        // Global Observation
5399        let observation_count = Rc::new(RefCell::new(0));
5400        let subscription = Rc::new(RefCell::new(None));
5401        *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
5402            let observation_count = observation_count.clone();
5403            let subscription = subscription.clone();
5404            move |_| {
5405                subscription.borrow_mut().take();
5406                *observation_count.borrow_mut() += 1;
5407            }
5408        }));
5409
5410        cx.default_global::<()>();
5411        cx.set_global(());
5412        assert_eq!(*observation_count.borrow(), 1);
5413    }
5414
5415    #[crate::test(self)]
5416    fn test_focus(cx: &mut AppContext) {
5417        struct View {
5418            name: String,
5419            events: Arc<Mutex<Vec<String>>>,
5420        }
5421
5422        impl Entity for View {
5423            type Event = ();
5424        }
5425
5426        impl super::View for View {
5427            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5428                Empty::new().boxed()
5429            }
5430
5431            fn ui_name() -> &'static str {
5432                "View"
5433            }
5434
5435            fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
5436                if cx.handle().id() == focused.id() {
5437                    self.events.lock().push(format!("{} focused", &self.name));
5438                }
5439            }
5440
5441            fn focus_out(&mut self, blurred: AnyViewHandle, cx: &mut ViewContext<Self>) {
5442                if cx.handle().id() == blurred.id() {
5443                    self.events.lock().push(format!("{} blurred", &self.name));
5444                }
5445            }
5446        }
5447
5448        let view_events: Arc<Mutex<Vec<String>>> = Default::default();
5449        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
5450            events: view_events.clone(),
5451            name: "view 1".to_string(),
5452        });
5453        let view_2 = cx.add_view(&view_1, |_| View {
5454            events: view_events.clone(),
5455            name: "view 2".to_string(),
5456        });
5457
5458        let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
5459        view_1.update(cx, |_, cx| {
5460            cx.observe_focus(&view_2, {
5461                let observed_events = observed_events.clone();
5462                move |this, view, focused, cx| {
5463                    let label = if focused { "focus" } else { "blur" };
5464                    observed_events.lock().push(format!(
5465                        "{} observed {}'s {}",
5466                        this.name,
5467                        view.read(cx).name,
5468                        label
5469                    ))
5470                }
5471            })
5472            .detach();
5473        });
5474        view_2.update(cx, |_, cx| {
5475            cx.observe_focus(&view_1, {
5476                let observed_events = observed_events.clone();
5477                move |this, view, focused, cx| {
5478                    let label = if focused { "focus" } else { "blur" };
5479                    observed_events.lock().push(format!(
5480                        "{} observed {}'s {}",
5481                        this.name,
5482                        view.read(cx).name,
5483                        label
5484                    ))
5485                }
5486            })
5487            .detach();
5488        });
5489        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
5490        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
5491
5492        view_1.update(cx, |_, cx| {
5493            // Ensure focus events are sent for all intermediate focuses
5494            cx.focus(&view_2);
5495            cx.focus(&view_1);
5496            cx.focus(&view_2);
5497        });
5498
5499        cx.read_window(window_id, |cx| {
5500            assert!(cx.is_child_focused(&view_1));
5501            assert!(!cx.is_child_focused(&view_2));
5502        });
5503        assert_eq!(
5504            mem::take(&mut *view_events.lock()),
5505            [
5506                "view 1 blurred",
5507                "view 2 focused",
5508                "view 2 blurred",
5509                "view 1 focused",
5510                "view 1 blurred",
5511                "view 2 focused"
5512            ],
5513        );
5514        assert_eq!(
5515            mem::take(&mut *observed_events.lock()),
5516            [
5517                "view 2 observed view 1's blur",
5518                "view 1 observed view 2's focus",
5519                "view 1 observed view 2's blur",
5520                "view 2 observed view 1's focus",
5521                "view 2 observed view 1's blur",
5522                "view 1 observed view 2's focus"
5523            ]
5524        );
5525
5526        view_1.update(cx, |_, cx| cx.focus(&view_1));
5527        cx.read_window(window_id, |cx| {
5528            assert!(!cx.is_child_focused(&view_1));
5529            assert!(!cx.is_child_focused(&view_2));
5530        });
5531        assert_eq!(
5532            mem::take(&mut *view_events.lock()),
5533            ["view 2 blurred", "view 1 focused"],
5534        );
5535        assert_eq!(
5536            mem::take(&mut *observed_events.lock()),
5537            [
5538                "view 1 observed view 2's blur",
5539                "view 2 observed view 1's focus"
5540            ]
5541        );
5542
5543        view_1.update(cx, |_, cx| cx.focus(&view_2));
5544        assert_eq!(
5545            mem::take(&mut *view_events.lock()),
5546            ["view 1 blurred", "view 2 focused"],
5547        );
5548        assert_eq!(
5549            mem::take(&mut *observed_events.lock()),
5550            [
5551                "view 2 observed view 1's blur",
5552                "view 1 observed view 2's focus"
5553            ]
5554        );
5555
5556        view_1.update(cx, |_, _| drop(view_2));
5557        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
5558        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
5559    }
5560
5561    #[crate::test(self)]
5562    fn test_deserialize_actions(cx: &mut AppContext) {
5563        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
5564        pub struct ComplexAction {
5565            arg: String,
5566            count: usize,
5567        }
5568
5569        actions!(test::something, [SimpleAction]);
5570        impl_actions!(test::something, [ComplexAction]);
5571
5572        cx.add_global_action(move |_: &SimpleAction, _: &mut AppContext| {});
5573        cx.add_global_action(move |_: &ComplexAction, _: &mut AppContext| {});
5574
5575        let action1 = cx
5576            .deserialize_action(
5577                "test::something::ComplexAction",
5578                Some(r#"{"arg": "a", "count": 5}"#),
5579            )
5580            .unwrap();
5581        let action2 = cx
5582            .deserialize_action("test::something::SimpleAction", None)
5583            .unwrap();
5584        assert_eq!(
5585            action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
5586            &ComplexAction {
5587                arg: "a".to_string(),
5588                count: 5,
5589            }
5590        );
5591        assert_eq!(
5592            action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
5593            &SimpleAction
5594        );
5595    }
5596
5597    #[crate::test(self)]
5598    fn test_dispatch_action(cx: &mut AppContext) {
5599        struct ViewA {
5600            id: usize,
5601        }
5602
5603        impl Entity for ViewA {
5604            type Event = ();
5605        }
5606
5607        impl View for ViewA {
5608            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5609                Empty::new().boxed()
5610            }
5611
5612            fn ui_name() -> &'static str {
5613                "View"
5614            }
5615        }
5616
5617        struct ViewB {
5618            id: usize,
5619        }
5620
5621        impl Entity for ViewB {
5622            type Event = ();
5623        }
5624
5625        impl View for ViewB {
5626            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5627                Empty::new().boxed()
5628            }
5629
5630            fn ui_name() -> &'static str {
5631                "View"
5632            }
5633        }
5634
5635        #[derive(Clone, Default, Deserialize, PartialEq)]
5636        pub struct Action(pub String);
5637
5638        impl_actions!(test, [Action]);
5639
5640        let actions = Rc::new(RefCell::new(Vec::new()));
5641
5642        cx.add_global_action({
5643            let actions = actions.clone();
5644            move |_: &Action, _: &mut AppContext| {
5645                actions.borrow_mut().push("global".to_string());
5646            }
5647        });
5648
5649        cx.add_action({
5650            let actions = actions.clone();
5651            move |view: &mut ViewA, action: &Action, cx| {
5652                assert_eq!(action.0, "bar");
5653                cx.propagate_action();
5654                actions.borrow_mut().push(format!("{} a", view.id));
5655            }
5656        });
5657
5658        cx.add_action({
5659            let actions = actions.clone();
5660            move |view: &mut ViewA, _: &Action, cx| {
5661                if view.id != 1 {
5662                    cx.add_view(|cx| {
5663                        cx.propagate_action(); // Still works on a nested ViewContext
5664                        ViewB { id: 5 }
5665                    });
5666                }
5667                actions.borrow_mut().push(format!("{} b", view.id));
5668            }
5669        });
5670
5671        cx.add_action({
5672            let actions = actions.clone();
5673            move |view: &mut ViewB, _: &Action, cx| {
5674                cx.propagate_action();
5675                actions.borrow_mut().push(format!("{} c", view.id));
5676            }
5677        });
5678
5679        cx.add_action({
5680            let actions = actions.clone();
5681            move |view: &mut ViewB, _: &Action, cx| {
5682                cx.propagate_action();
5683                actions.borrow_mut().push(format!("{} d", view.id));
5684            }
5685        });
5686
5687        cx.capture_action({
5688            let actions = actions.clone();
5689            move |view: &mut ViewA, _: &Action, cx| {
5690                cx.propagate_action();
5691                actions.borrow_mut().push(format!("{} capture", view.id));
5692            }
5693        });
5694
5695        let observed_actions = Rc::new(RefCell::new(Vec::new()));
5696        cx.observe_actions({
5697            let observed_actions = observed_actions.clone();
5698            move |action_id, _| observed_actions.borrow_mut().push(action_id)
5699        })
5700        .detach();
5701
5702        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
5703        let view_2 = cx.add_view(&view_1, |_| ViewB { id: 2 });
5704        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
5705        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
5706
5707        cx.update_window(window_id, |cx| {
5708            cx.handle_dispatch_action_from_effect(Some(view_4.id()), &Action("bar".to_string()))
5709        });
5710
5711        assert_eq!(
5712            *actions.borrow(),
5713            vec![
5714                "1 capture",
5715                "3 capture",
5716                "4 d",
5717                "4 c",
5718                "3 b",
5719                "3 a",
5720                "2 d",
5721                "2 c",
5722                "1 b"
5723            ]
5724        );
5725        assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
5726
5727        // Remove view_1, which doesn't propagate the action
5728
5729        let (window_id, view_2) = cx.add_window(Default::default(), |_| ViewB { id: 2 });
5730        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
5731        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
5732
5733        actions.borrow_mut().clear();
5734        cx.update_window(window_id, |cx| {
5735            cx.handle_dispatch_action_from_effect(Some(view_4.id()), &Action("bar".to_string()))
5736        });
5737
5738        assert_eq!(
5739            *actions.borrow(),
5740            vec![
5741                "3 capture",
5742                "4 d",
5743                "4 c",
5744                "3 b",
5745                "3 a",
5746                "2 d",
5747                "2 c",
5748                "global"
5749            ]
5750        );
5751        assert_eq!(
5752            *observed_actions.borrow(),
5753            [Action::default().id(), Action::default().id()]
5754        );
5755    }
5756
5757    #[crate::test(self)]
5758    fn test_dispatch_keystroke(cx: &mut AppContext) {
5759        #[derive(Clone, Deserialize, PartialEq)]
5760        pub struct Action(String);
5761
5762        impl_actions!(test, [Action]);
5763
5764        struct View {
5765            id: usize,
5766            keymap_context: KeymapContext,
5767        }
5768
5769        impl Entity for View {
5770            type Event = ();
5771        }
5772
5773        impl super::View for View {
5774            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5775                Empty::new().boxed()
5776            }
5777
5778            fn ui_name() -> &'static str {
5779                "View"
5780            }
5781
5782            fn keymap_context(&self, _: &AppContext) -> KeymapContext {
5783                self.keymap_context.clone()
5784            }
5785        }
5786
5787        impl View {
5788            fn new(id: usize) -> Self {
5789                View {
5790                    id,
5791                    keymap_context: KeymapContext::default(),
5792                }
5793            }
5794        }
5795
5796        let mut view_1 = View::new(1);
5797        let mut view_2 = View::new(2);
5798        let mut view_3 = View::new(3);
5799        view_1.keymap_context.add_identifier("a");
5800        view_2.keymap_context.add_identifier("a");
5801        view_2.keymap_context.add_identifier("b");
5802        view_3.keymap_context.add_identifier("a");
5803        view_3.keymap_context.add_identifier("b");
5804        view_3.keymap_context.add_identifier("c");
5805
5806        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
5807        let view_2 = cx.add_view(&view_1, |_| view_2);
5808        let _view_3 = cx.add_view(&view_2, |cx| {
5809            cx.focus_self();
5810            view_3
5811        });
5812
5813        // This binding only dispatches an action on view 2 because that view will have
5814        // "a" and "b" in its context, but not "c".
5815        cx.add_bindings(vec![Binding::new(
5816            "a",
5817            Action("a".to_string()),
5818            Some("a && b && !c"),
5819        )]);
5820
5821        cx.add_bindings(vec![Binding::new("b", Action("b".to_string()), None)]);
5822
5823        // This binding only dispatches an action on views 2 and 3, because they have
5824        // a parent view with a in its context
5825        cx.add_bindings(vec![Binding::new(
5826            "c",
5827            Action("c".to_string()),
5828            Some("b > c"),
5829        )]);
5830
5831        // This binding only dispatches an action on view 2, because they have
5832        // a parent view with a in its context
5833        cx.add_bindings(vec![Binding::new(
5834            "d",
5835            Action("d".to_string()),
5836            Some("a && !b > b"),
5837        )]);
5838
5839        let actions = Rc::new(RefCell::new(Vec::new()));
5840        cx.add_action({
5841            let actions = actions.clone();
5842            move |view: &mut View, action: &Action, cx| {
5843                actions
5844                    .borrow_mut()
5845                    .push(format!("{} {}", view.id, action.0));
5846
5847                if action.0 == "b" {
5848                    cx.propagate_action();
5849                }
5850            }
5851        });
5852
5853        cx.add_global_action({
5854            let actions = actions.clone();
5855            move |action: &Action, _| {
5856                actions.borrow_mut().push(format!("global {}", action.0));
5857            }
5858        });
5859
5860        cx.update_window(window_id, |cx| {
5861            cx.dispatch_keystroke(&Keystroke::parse("a").unwrap())
5862        });
5863        assert_eq!(&*actions.borrow(), &["2 a"]);
5864        actions.borrow_mut().clear();
5865
5866        cx.update_window(window_id, |cx| {
5867            cx.dispatch_keystroke(&Keystroke::parse("b").unwrap());
5868        });
5869
5870        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
5871        actions.borrow_mut().clear();
5872
5873        cx.update_window(window_id, |cx| {
5874            cx.dispatch_keystroke(&Keystroke::parse("c").unwrap());
5875        });
5876        assert_eq!(&*actions.borrow(), &["3 c"]);
5877        actions.borrow_mut().clear();
5878
5879        cx.update_window(window_id, |cx| {
5880            cx.dispatch_keystroke(&Keystroke::parse("d").unwrap());
5881        });
5882        assert_eq!(&*actions.borrow(), &["2 d"]);
5883        actions.borrow_mut().clear();
5884    }
5885
5886    #[crate::test(self)]
5887    fn test_keystrokes_for_action(cx: &mut AppContext) {
5888        actions!(test, [Action1, Action2, GlobalAction]);
5889
5890        struct View1 {}
5891        struct View2 {}
5892
5893        impl Entity for View1 {
5894            type Event = ();
5895        }
5896        impl Entity for View2 {
5897            type Event = ();
5898        }
5899
5900        impl super::View for View1 {
5901            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5902                Empty::new().boxed()
5903            }
5904            fn ui_name() -> &'static str {
5905                "View1"
5906            }
5907        }
5908        impl super::View for View2 {
5909            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
5910                Empty::new().boxed()
5911            }
5912            fn ui_name() -> &'static str {
5913                "View2"
5914            }
5915        }
5916
5917        let (window_id, view_1) = cx.add_window(Default::default(), |_| View1 {});
5918        let view_2 = cx.add_view(&view_1, |cx| {
5919            cx.focus_self();
5920            View2 {}
5921        });
5922
5923        cx.add_action(|_: &mut View1, _: &Action1, _cx| {});
5924        cx.add_action(|_: &mut View2, _: &Action2, _cx| {});
5925        cx.add_global_action(|_: &GlobalAction, _| {});
5926
5927        cx.add_bindings(vec![
5928            Binding::new("a", Action1, Some("View1")),
5929            Binding::new("b", Action2, Some("View1 > View2")),
5930            Binding::new("c", GlobalAction, Some("View3")), // View 3 does not exist
5931        ]);
5932
5933        cx.update_window(window_id, |cx| {
5934            // Sanity check
5935            assert_eq!(
5936                cx.keystrokes_for_action(view_1.id(), &Action1)
5937                    .unwrap()
5938                    .as_slice(),
5939                &[Keystroke::parse("a").unwrap()]
5940            );
5941            assert_eq!(
5942                cx.keystrokes_for_action(view_2.id(), &Action2)
5943                    .unwrap()
5944                    .as_slice(),
5945                &[Keystroke::parse("b").unwrap()]
5946            );
5947
5948            // The 'a' keystroke propagates up the view tree from view_2
5949            // to view_1. The action, Action1, is handled by view_1.
5950            assert_eq!(
5951                cx.keystrokes_for_action(view_2.id(), &Action1)
5952                    .unwrap()
5953                    .as_slice(),
5954                &[Keystroke::parse("a").unwrap()]
5955            );
5956
5957            // Actions that are handled below the current view don't have bindings
5958            assert_eq!(cx.keystrokes_for_action(view_1.id(), &Action2), None);
5959
5960            // Actions that are handled in other branches of the tree should not have a binding
5961            assert_eq!(cx.keystrokes_for_action(view_2.id(), &GlobalAction), None);
5962
5963            // Check that global actions do not have a binding, even if a binding does exist in another view
5964            assert_eq!(
5965                &available_actions(view_1.id(), cx),
5966                &[
5967                    ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
5968                    ("test::GlobalAction", vec![])
5969                ],
5970            );
5971
5972            // Check that view 1 actions and bindings are available even when called from view 2
5973            assert_eq!(
5974                &available_actions(view_2.id(), cx),
5975                &[
5976                    ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
5977                    ("test::Action2", vec![Keystroke::parse("b").unwrap()]),
5978                    ("test::GlobalAction", vec![]),
5979                ],
5980            );
5981        });
5982
5983        // Produces a list of actions and key bindings
5984        fn available_actions(
5985            view_id: usize,
5986            cx: &WindowContext,
5987        ) -> Vec<(&'static str, Vec<Keystroke>)> {
5988            cx.available_actions(view_id)
5989                .map(|(action_name, _, bindings)| {
5990                    (
5991                        action_name,
5992                        bindings
5993                            .iter()
5994                            .map(|binding| binding.keystrokes()[0].clone())
5995                            .collect::<Vec<_>>(),
5996                    )
5997                })
5998                .sorted_by(|(name1, _), (name2, _)| name1.cmp(name2))
5999                .collect()
6000        }
6001    }
6002
6003    #[crate::test(self)]
6004    async fn test_model_condition(cx: &mut TestAppContext) {
6005        struct Counter(usize);
6006
6007        impl super::Entity for Counter {
6008            type Event = ();
6009        }
6010
6011        impl Counter {
6012            fn inc(&mut self, cx: &mut ModelContext<Self>) {
6013                self.0 += 1;
6014                cx.notify();
6015            }
6016        }
6017
6018        let model = cx.add_model(|_| Counter(0));
6019
6020        let condition1 = model.condition(cx, |model, _| model.0 == 2);
6021        let condition2 = model.condition(cx, |model, _| model.0 == 3);
6022        smol::pin!(condition1, condition2);
6023
6024        model.update(cx, |model, cx| model.inc(cx));
6025        assert_eq!(poll_once(&mut condition1).await, None);
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 condition1).await, Some(()));
6030        assert_eq!(poll_once(&mut condition2).await, None);
6031
6032        model.update(cx, |model, cx| model.inc(cx));
6033        assert_eq!(poll_once(&mut condition2).await, Some(()));
6034
6035        model.update(cx, |_, cx| cx.notify());
6036    }
6037
6038    #[crate::test(self)]
6039    #[should_panic]
6040    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
6041        struct Model;
6042
6043        impl super::Entity for Model {
6044            type Event = ();
6045        }
6046
6047        let model = cx.add_model(|_| Model);
6048        model.condition(cx, |_, _| false).await;
6049    }
6050
6051    #[crate::test(self)]
6052    #[should_panic(expected = "model dropped with pending condition")]
6053    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
6054        struct Model;
6055
6056        impl super::Entity for Model {
6057            type Event = ();
6058        }
6059
6060        let model = cx.add_model(|_| Model);
6061        let condition = model.condition(cx, |_, _| false);
6062        cx.update(|_| drop(model));
6063        condition.await;
6064    }
6065
6066    #[crate::test(self)]
6067    async fn test_view_condition(cx: &mut TestAppContext) {
6068        struct Counter(usize);
6069
6070        impl super::Entity for Counter {
6071            type Event = ();
6072        }
6073
6074        impl super::View for Counter {
6075            fn ui_name() -> &'static str {
6076                "test view"
6077            }
6078
6079            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6080                Empty::new().boxed()
6081            }
6082        }
6083
6084        impl Counter {
6085            fn inc(&mut self, cx: &mut ViewContext<Self>) {
6086                self.0 += 1;
6087                cx.notify();
6088            }
6089        }
6090
6091        let (_, view) = cx.add_window(|_| Counter(0));
6092
6093        let condition1 = view.condition(cx, |view, _| view.0 == 2);
6094        let condition2 = view.condition(cx, |view, _| view.0 == 3);
6095        smol::pin!(condition1, condition2);
6096
6097        view.update(cx, |view, cx| view.inc(cx));
6098        assert_eq!(poll_once(&mut condition1).await, None);
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 condition1).await, Some(()));
6103        assert_eq!(poll_once(&mut condition2).await, None);
6104
6105        view.update(cx, |view, cx| view.inc(cx));
6106        assert_eq!(poll_once(&mut condition2).await, Some(()));
6107        view.update(cx, |_, cx| cx.notify());
6108    }
6109
6110    #[crate::test(self)]
6111    #[should_panic]
6112    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
6113        let (_, view) = cx.add_window(|_| TestView::default());
6114        view.condition(cx, |_, _| false).await;
6115    }
6116
6117    #[crate::test(self)]
6118    #[should_panic(expected = "view dropped with pending condition")]
6119    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
6120        let (_, root_view) = cx.add_window(|_| TestView::default());
6121        let view = cx.add_view(&root_view, |_| TestView::default());
6122
6123        let condition = view.condition(cx, |_, _| false);
6124        cx.update(|_| drop(view));
6125        condition.await;
6126    }
6127
6128    #[crate::test(self)]
6129    fn test_refresh_windows(cx: &mut AppContext) {
6130        struct View(usize);
6131
6132        impl super::Entity for View {
6133            type Event = ();
6134        }
6135
6136        impl super::View for View {
6137            fn ui_name() -> &'static str {
6138                "test view"
6139            }
6140
6141            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6142                Empty::new().named(format!("render count: {}", post_inc(&mut self.0)))
6143            }
6144        }
6145
6146        let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
6147        cx.update_window(window_id, |cx| {
6148            assert_eq!(
6149                cx.window.rendered_views[&root_view.id()].name(),
6150                Some("render count: 0")
6151            );
6152        });
6153
6154        let view = cx.add_view(&root_view, |cx| {
6155            cx.refresh_windows();
6156            View(0)
6157        });
6158
6159        cx.update_window(window_id, |cx| {
6160            assert_eq!(
6161                cx.window.rendered_views[&root_view.id()].name(),
6162                Some("render count: 1")
6163            );
6164            assert_eq!(
6165                cx.window.rendered_views[&view.id()].name(),
6166                Some("render count: 0")
6167            );
6168        });
6169
6170        cx.update(|cx| cx.refresh_windows());
6171
6172        cx.update_window(window_id, |cx| {
6173            assert_eq!(
6174                cx.window.rendered_views[&root_view.id()].name(),
6175                Some("render count: 2")
6176            );
6177            assert_eq!(
6178                cx.window.rendered_views[&view.id()].name(),
6179                Some("render count: 1")
6180            );
6181        });
6182
6183        cx.update(|cx| {
6184            cx.refresh_windows();
6185            drop(view);
6186        });
6187
6188        cx.update_window(window_id, |cx| {
6189            assert_eq!(
6190                cx.window.rendered_views[&root_view.id()].name(),
6191                Some("render count: 3")
6192            );
6193            assert_eq!(cx.window.rendered_views.len(), 1);
6194        });
6195    }
6196
6197    #[crate::test(self)]
6198    async fn test_labeled_tasks(cx: &mut TestAppContext) {
6199        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6200        let (mut sender, mut reciever) = postage::oneshot::channel::<()>();
6201        let task = cx
6202            .update(|cx| cx.spawn_labeled("Test Label", |_| async move { reciever.recv().await }));
6203
6204        assert_eq!(
6205            Some("Test Label"),
6206            cx.update(|cx| cx.active_labeled_tasks().next())
6207        );
6208        sender
6209            .send(())
6210            .await
6211            .expect("Could not send message to complete task");
6212        task.await;
6213
6214        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6215    }
6216
6217    #[crate::test(self)]
6218    async fn test_window_activation(cx: &mut TestAppContext) {
6219        struct View(&'static str);
6220
6221        impl super::Entity for View {
6222            type Event = ();
6223        }
6224
6225        impl super::View for View {
6226            fn ui_name() -> &'static str {
6227                "test view"
6228            }
6229
6230            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6231                Empty::new().boxed()
6232            }
6233        }
6234
6235        let events = Rc::new(RefCell::new(Vec::new()));
6236        let (window_1, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6237            cx.observe_window_activation({
6238                let events = events.clone();
6239                move |this, active, _| events.borrow_mut().push((this.0, active))
6240            })
6241            .detach();
6242            View("window 1")
6243        });
6244        assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
6245
6246        let (window_2, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6247            cx.observe_window_activation({
6248                let events = events.clone();
6249                move |this, active, _| events.borrow_mut().push((this.0, active))
6250            })
6251            .detach();
6252            View("window 2")
6253        });
6254        assert_eq!(
6255            mem::take(&mut *events.borrow_mut()),
6256            [("window 1", false), ("window 2", true)]
6257        );
6258
6259        let (window_3, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6260            cx.observe_window_activation({
6261                let events = events.clone();
6262                move |this, active, _| events.borrow_mut().push((this.0, active))
6263            })
6264            .detach();
6265            View("window 3")
6266        });
6267        assert_eq!(
6268            mem::take(&mut *events.borrow_mut()),
6269            [("window 2", false), ("window 3", true)]
6270        );
6271
6272        cx.simulate_window_activation(Some(window_2));
6273        assert_eq!(
6274            mem::take(&mut *events.borrow_mut()),
6275            [("window 3", false), ("window 2", true)]
6276        );
6277
6278        cx.simulate_window_activation(Some(window_1));
6279        assert_eq!(
6280            mem::take(&mut *events.borrow_mut()),
6281            [("window 2", false), ("window 1", true)]
6282        );
6283
6284        cx.simulate_window_activation(Some(window_3));
6285        assert_eq!(
6286            mem::take(&mut *events.borrow_mut()),
6287            [("window 1", false), ("window 3", true)]
6288        );
6289
6290        cx.simulate_window_activation(Some(window_3));
6291        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6292    }
6293
6294    #[crate::test(self)]
6295    fn test_child_view(cx: &mut AppContext) {
6296        struct Child {
6297            rendered: Rc<Cell<bool>>,
6298            dropped: Rc<Cell<bool>>,
6299        }
6300
6301        impl super::Entity for Child {
6302            type Event = ();
6303        }
6304
6305        impl super::View for Child {
6306            fn ui_name() -> &'static str {
6307                "child view"
6308            }
6309
6310            fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6311                self.rendered.set(true);
6312                Empty::new().boxed()
6313            }
6314        }
6315
6316        impl Drop for Child {
6317            fn drop(&mut self) {
6318                self.dropped.set(true);
6319            }
6320        }
6321
6322        struct Parent {
6323            child: Option<ViewHandle<Child>>,
6324        }
6325
6326        impl super::Entity for Parent {
6327            type Event = ();
6328        }
6329
6330        impl super::View for Parent {
6331            fn ui_name() -> &'static str {
6332                "parent view"
6333            }
6334
6335            fn render(&mut self, cx: &mut ViewContext<Self>) -> Element<Self> {
6336                if let Some(child) = self.child.as_ref() {
6337                    ChildView::new(child, cx).boxed()
6338                } else {
6339                    Empty::new().boxed()
6340                }
6341            }
6342        }
6343
6344        let child_rendered = Rc::new(Cell::new(false));
6345        let child_dropped = Rc::new(Cell::new(false));
6346        let (_, root_view) = cx.add_window(Default::default(), |cx| Parent {
6347            child: Some(cx.add_view(|_| Child {
6348                rendered: child_rendered.clone(),
6349                dropped: child_dropped.clone(),
6350            })),
6351        });
6352        assert!(child_rendered.take());
6353        assert!(!child_dropped.take());
6354
6355        root_view.update(cx, |view, cx| {
6356            view.child.take();
6357            cx.notify();
6358        });
6359        assert!(!child_rendered.take());
6360        assert!(child_dropped.take());
6361    }
6362
6363    #[derive(Default)]
6364    struct TestView {
6365        events: Vec<String>,
6366    }
6367
6368    impl Entity for TestView {
6369        type Event = String;
6370    }
6371
6372    impl View for TestView {
6373        fn ui_name() -> &'static str {
6374            "TestView"
6375        }
6376
6377        fn render(&mut self, _: &mut ViewContext<Self>) -> Element<Self> {
6378            Empty::new().boxed()
6379        }
6380    }
6381}