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