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