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