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