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