app.rs

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