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