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, Copy, Default)]
3778pub struct MouseState {
3779    pub hovered: bool,
3780    pub clicked: Option<MouseButton>,
3781}
3782
3783impl<'a, V: View> RenderContext<'a, V> {
3784    fn new(params: RenderParams, app: &'a mut MutableAppContext) -> Self {
3785        Self {
3786            app,
3787            window_id: params.window_id,
3788            view_id: params.view_id,
3789            view_type: PhantomData,
3790            titlebar_height: params.titlebar_height,
3791            hovered_region_ids: params.hovered_region_ids.clone(),
3792            clicked_region_ids: params.clicked_region_ids.clone(),
3793            refreshing: params.refreshing,
3794            appearance: params.appearance,
3795        }
3796    }
3797
3798    pub fn handle(&self) -> WeakViewHandle<V> {
3799        WeakViewHandle::new(self.window_id, self.view_id)
3800    }
3801
3802    pub fn window_id(&self) -> usize {
3803        self.window_id
3804    }
3805
3806    pub fn view_id(&self) -> usize {
3807        self.view_id
3808    }
3809
3810    pub fn mouse_state<Tag: 'static>(&self, region_id: usize) -> MouseState {
3811        let region_id = MouseRegionId::new::<Tag>(self.view_id, region_id);
3812        MouseState {
3813            hovered: self.hovered_region_ids.contains(&region_id),
3814            clicked: self.clicked_region_ids.as_ref().and_then(|(ids, button)| {
3815                if ids.contains(&region_id) {
3816                    Some(*button)
3817                } else {
3818                    None
3819                }
3820            }),
3821        }
3822    }
3823
3824    pub fn element_state<Tag: 'static, T: 'static>(
3825        &mut self,
3826        element_id: usize,
3827        initial: T,
3828    ) -> ElementStateHandle<T> {
3829        let id = ElementStateId {
3830            view_id: self.view_id(),
3831            element_id,
3832            tag: TypeId::of::<Tag>(),
3833        };
3834        self.cx
3835            .element_states
3836            .entry(id)
3837            .or_insert_with(|| Box::new(initial));
3838        ElementStateHandle::new(id, self.frame_count, &self.cx.ref_counts)
3839    }
3840
3841    pub fn default_element_state<Tag: 'static, T: 'static + Default>(
3842        &mut self,
3843        element_id: usize,
3844    ) -> ElementStateHandle<T> {
3845        self.element_state::<Tag, T>(element_id, T::default())
3846    }
3847}
3848
3849impl AsRef<AppContext> for &AppContext {
3850    fn as_ref(&self) -> &AppContext {
3851        self
3852    }
3853}
3854
3855impl<V: View> Deref for RenderContext<'_, V> {
3856    type Target = MutableAppContext;
3857
3858    fn deref(&self) -> &Self::Target {
3859        self.app
3860    }
3861}
3862
3863impl<V: View> DerefMut for RenderContext<'_, V> {
3864    fn deref_mut(&mut self) -> &mut Self::Target {
3865        self.app
3866    }
3867}
3868
3869impl<V: View> ReadModel for RenderContext<'_, V> {
3870    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
3871        self.app.read_model(handle)
3872    }
3873}
3874
3875impl<V: View> UpdateModel for RenderContext<'_, V> {
3876    fn update_model<T: Entity, O>(
3877        &mut self,
3878        handle: &ModelHandle<T>,
3879        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
3880    ) -> O {
3881        self.app.update_model(handle, update)
3882    }
3883}
3884
3885impl<V: View> ReadView for RenderContext<'_, V> {
3886    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
3887        self.app.read_view(handle)
3888    }
3889}
3890
3891impl<M> AsRef<AppContext> for ViewContext<'_, M> {
3892    fn as_ref(&self) -> &AppContext {
3893        &self.app.cx
3894    }
3895}
3896
3897impl<M> Deref for ViewContext<'_, M> {
3898    type Target = MutableAppContext;
3899
3900    fn deref(&self) -> &Self::Target {
3901        self.app
3902    }
3903}
3904
3905impl<M> DerefMut for ViewContext<'_, M> {
3906    fn deref_mut(&mut self) -> &mut Self::Target {
3907        &mut self.app
3908    }
3909}
3910
3911impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
3912    fn as_mut(&mut self) -> &mut MutableAppContext {
3913        self.app
3914    }
3915}
3916
3917impl<V> ReadModel for ViewContext<'_, V> {
3918    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
3919        self.app.read_model(handle)
3920    }
3921}
3922
3923impl<V> UpgradeModelHandle for ViewContext<'_, V> {
3924    fn upgrade_model_handle<T: Entity>(
3925        &self,
3926        handle: &WeakModelHandle<T>,
3927    ) -> Option<ModelHandle<T>> {
3928        self.cx.upgrade_model_handle(handle)
3929    }
3930
3931    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
3932        self.cx.model_handle_is_upgradable(handle)
3933    }
3934
3935    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
3936        self.cx.upgrade_any_model_handle(handle)
3937    }
3938}
3939
3940impl<V> UpgradeViewHandle for ViewContext<'_, V> {
3941    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
3942        self.cx.upgrade_view_handle(handle)
3943    }
3944
3945    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
3946        self.cx.upgrade_any_view_handle(handle)
3947    }
3948}
3949
3950impl<V: View> UpgradeViewHandle for RenderContext<'_, V> {
3951    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
3952        self.cx.upgrade_view_handle(handle)
3953    }
3954
3955    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
3956        self.cx.upgrade_any_view_handle(handle)
3957    }
3958}
3959
3960impl<V: View> UpdateModel for ViewContext<'_, V> {
3961    fn update_model<T: Entity, O>(
3962        &mut self,
3963        handle: &ModelHandle<T>,
3964        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
3965    ) -> O {
3966        self.app.update_model(handle, update)
3967    }
3968}
3969
3970impl<V: View> ReadView for ViewContext<'_, V> {
3971    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
3972        self.app.read_view(handle)
3973    }
3974}
3975
3976impl<V: View> UpdateView for ViewContext<'_, V> {
3977    fn update_view<T, S>(
3978        &mut self,
3979        handle: &ViewHandle<T>,
3980        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
3981    ) -> S
3982    where
3983        T: View,
3984    {
3985        self.app.update_view(handle, update)
3986    }
3987}
3988
3989pub trait Handle<T> {
3990    type Weak: 'static;
3991    fn id(&self) -> usize;
3992    fn location(&self) -> EntityLocation;
3993    fn downgrade(&self) -> Self::Weak;
3994    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3995    where
3996        Self: Sized;
3997}
3998
3999pub trait WeakHandle {
4000    fn id(&self) -> usize;
4001}
4002
4003#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
4004pub enum EntityLocation {
4005    Model(usize),
4006    View(usize, usize),
4007}
4008
4009pub struct ModelHandle<T: Entity> {
4010    model_id: usize,
4011    model_type: PhantomData<T>,
4012    ref_counts: Arc<Mutex<RefCounts>>,
4013
4014    #[cfg(any(test, feature = "test-support"))]
4015    handle_id: usize,
4016}
4017
4018impl<T: Entity> ModelHandle<T> {
4019    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4020        ref_counts.lock().inc_model(model_id);
4021
4022        #[cfg(any(test, feature = "test-support"))]
4023        let handle_id = ref_counts
4024            .lock()
4025            .leak_detector
4026            .lock()
4027            .handle_created(Some(type_name::<T>()), model_id);
4028
4029        Self {
4030            model_id,
4031            model_type: PhantomData,
4032            ref_counts: ref_counts.clone(),
4033
4034            #[cfg(any(test, feature = "test-support"))]
4035            handle_id,
4036        }
4037    }
4038
4039    pub fn downgrade(&self) -> WeakModelHandle<T> {
4040        WeakModelHandle::new(self.model_id)
4041    }
4042
4043    pub fn id(&self) -> usize {
4044        self.model_id
4045    }
4046
4047    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
4048        cx.read_model(self)
4049    }
4050
4051    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
4052    where
4053        C: ReadModelWith,
4054        F: FnOnce(&T, &AppContext) -> S,
4055    {
4056        let mut read = Some(read);
4057        cx.read_model_with(self, &mut |model, cx| {
4058            let read = read.take().unwrap();
4059            read(model, cx)
4060        })
4061    }
4062
4063    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
4064    where
4065        C: UpdateModel,
4066        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
4067    {
4068        let mut update = Some(update);
4069        cx.update_model(self, &mut |model, cx| {
4070            let update = update.take().unwrap();
4071            update(model, cx)
4072        })
4073    }
4074}
4075
4076impl<T: Entity> Clone for ModelHandle<T> {
4077    fn clone(&self) -> Self {
4078        Self::new(self.model_id, &self.ref_counts)
4079    }
4080}
4081
4082impl<T: Entity> PartialEq for ModelHandle<T> {
4083    fn eq(&self, other: &Self) -> bool {
4084        self.model_id == other.model_id
4085    }
4086}
4087
4088impl<T: Entity> Eq for ModelHandle<T> {}
4089
4090impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
4091    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
4092        self.model_id == other.model_id
4093    }
4094}
4095
4096impl<T: Entity> Hash for ModelHandle<T> {
4097    fn hash<H: Hasher>(&self, state: &mut H) {
4098        self.model_id.hash(state);
4099    }
4100}
4101
4102impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
4103    fn borrow(&self) -> &usize {
4104        &self.model_id
4105    }
4106}
4107
4108impl<T: Entity> Debug for ModelHandle<T> {
4109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4110        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
4111            .field(&self.model_id)
4112            .finish()
4113    }
4114}
4115
4116unsafe impl<T: Entity> Send for ModelHandle<T> {}
4117unsafe impl<T: Entity> Sync for ModelHandle<T> {}
4118
4119impl<T: Entity> Drop for ModelHandle<T> {
4120    fn drop(&mut self) {
4121        let mut ref_counts = self.ref_counts.lock();
4122        ref_counts.dec_model(self.model_id);
4123
4124        #[cfg(any(test, feature = "test-support"))]
4125        ref_counts
4126            .leak_detector
4127            .lock()
4128            .handle_dropped(self.model_id, self.handle_id);
4129    }
4130}
4131
4132impl<T: Entity> Handle<T> for ModelHandle<T> {
4133    type Weak = WeakModelHandle<T>;
4134
4135    fn id(&self) -> usize {
4136        self.model_id
4137    }
4138
4139    fn location(&self) -> EntityLocation {
4140        EntityLocation::Model(self.model_id)
4141    }
4142
4143    fn downgrade(&self) -> Self::Weak {
4144        self.downgrade()
4145    }
4146
4147    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4148    where
4149        Self: Sized,
4150    {
4151        weak.upgrade(cx)
4152    }
4153}
4154
4155pub struct WeakModelHandle<T> {
4156    model_id: usize,
4157    model_type: PhantomData<T>,
4158}
4159
4160impl<T> WeakHandle for WeakModelHandle<T> {
4161    fn id(&self) -> usize {
4162        self.model_id
4163    }
4164}
4165
4166unsafe impl<T> Send for WeakModelHandle<T> {}
4167unsafe impl<T> Sync for WeakModelHandle<T> {}
4168
4169impl<T: Entity> WeakModelHandle<T> {
4170    fn new(model_id: usize) -> Self {
4171        Self {
4172            model_id,
4173            model_type: PhantomData,
4174        }
4175    }
4176
4177    pub fn id(&self) -> usize {
4178        self.model_id
4179    }
4180
4181    pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
4182        cx.model_handle_is_upgradable(self)
4183    }
4184
4185    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
4186        cx.upgrade_model_handle(self)
4187    }
4188}
4189
4190impl<T> Hash for WeakModelHandle<T> {
4191    fn hash<H: Hasher>(&self, state: &mut H) {
4192        self.model_id.hash(state)
4193    }
4194}
4195
4196impl<T> PartialEq for WeakModelHandle<T> {
4197    fn eq(&self, other: &Self) -> bool {
4198        self.model_id == other.model_id
4199    }
4200}
4201
4202impl<T> Eq for WeakModelHandle<T> {}
4203
4204impl<T: Entity> PartialEq<ModelHandle<T>> for WeakModelHandle<T> {
4205    fn eq(&self, other: &ModelHandle<T>) -> bool {
4206        self.model_id == other.model_id
4207    }
4208}
4209
4210impl<T> Clone for WeakModelHandle<T> {
4211    fn clone(&self) -> Self {
4212        Self {
4213            model_id: self.model_id,
4214            model_type: PhantomData,
4215        }
4216    }
4217}
4218
4219impl<T> Copy for WeakModelHandle<T> {}
4220
4221pub struct ViewHandle<T> {
4222    window_id: usize,
4223    view_id: usize,
4224    view_type: PhantomData<T>,
4225    ref_counts: Arc<Mutex<RefCounts>>,
4226    #[cfg(any(test, feature = "test-support"))]
4227    handle_id: usize,
4228}
4229
4230impl<T: View> ViewHandle<T> {
4231    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4232        ref_counts.lock().inc_view(window_id, view_id);
4233        #[cfg(any(test, feature = "test-support"))]
4234        let handle_id = ref_counts
4235            .lock()
4236            .leak_detector
4237            .lock()
4238            .handle_created(Some(type_name::<T>()), view_id);
4239
4240        Self {
4241            window_id,
4242            view_id,
4243            view_type: PhantomData,
4244            ref_counts: ref_counts.clone(),
4245
4246            #[cfg(any(test, feature = "test-support"))]
4247            handle_id,
4248        }
4249    }
4250
4251    pub fn downgrade(&self) -> WeakViewHandle<T> {
4252        WeakViewHandle::new(self.window_id, self.view_id)
4253    }
4254
4255    pub fn window_id(&self) -> usize {
4256        self.window_id
4257    }
4258
4259    pub fn id(&self) -> usize {
4260        self.view_id
4261    }
4262
4263    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
4264        cx.read_view(self)
4265    }
4266
4267    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
4268    where
4269        C: ReadViewWith,
4270        F: FnOnce(&T, &AppContext) -> S,
4271    {
4272        let mut read = Some(read);
4273        cx.read_view_with(self, &mut |view, cx| {
4274            let read = read.take().unwrap();
4275            read(view, cx)
4276        })
4277    }
4278
4279    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
4280    where
4281        C: UpdateView,
4282        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
4283    {
4284        let mut update = Some(update);
4285        cx.update_view(self, &mut |view, cx| {
4286            let update = update.take().unwrap();
4287            update(view, cx)
4288        })
4289    }
4290
4291    pub fn defer<C, F>(&self, cx: &mut C, update: F)
4292    where
4293        C: AsMut<MutableAppContext>,
4294        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
4295    {
4296        let this = self.clone();
4297        cx.as_mut().defer(move |cx| {
4298            this.update(cx, |view, cx| update(view, cx));
4299        });
4300    }
4301
4302    pub fn is_focused(&self, cx: &AppContext) -> bool {
4303        cx.focused_view_id(self.window_id)
4304            .map_or(false, |focused_id| focused_id == self.view_id)
4305    }
4306}
4307
4308impl<T: View> Clone for ViewHandle<T> {
4309    fn clone(&self) -> Self {
4310        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
4311    }
4312}
4313
4314impl<T> PartialEq for ViewHandle<T> {
4315    fn eq(&self, other: &Self) -> bool {
4316        self.window_id == other.window_id && self.view_id == other.view_id
4317    }
4318}
4319
4320impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
4321    fn eq(&self, other: &WeakViewHandle<T>) -> bool {
4322        self.window_id == other.window_id && self.view_id == other.view_id
4323    }
4324}
4325
4326impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
4327    fn eq(&self, other: &ViewHandle<T>) -> bool {
4328        self.window_id == other.window_id && self.view_id == other.view_id
4329    }
4330}
4331
4332impl<T> Eq for ViewHandle<T> {}
4333
4334impl<T> Hash for ViewHandle<T> {
4335    fn hash<H: Hasher>(&self, state: &mut H) {
4336        self.window_id.hash(state);
4337        self.view_id.hash(state);
4338    }
4339}
4340
4341impl<T> Debug for ViewHandle<T> {
4342    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4343        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
4344            .field("window_id", &self.window_id)
4345            .field("view_id", &self.view_id)
4346            .finish()
4347    }
4348}
4349
4350impl<T> Drop for ViewHandle<T> {
4351    fn drop(&mut self) {
4352        self.ref_counts
4353            .lock()
4354            .dec_view(self.window_id, self.view_id);
4355        #[cfg(any(test, feature = "test-support"))]
4356        self.ref_counts
4357            .lock()
4358            .leak_detector
4359            .lock()
4360            .handle_dropped(self.view_id, self.handle_id);
4361    }
4362}
4363
4364impl<T: View> Handle<T> for ViewHandle<T> {
4365    type Weak = WeakViewHandle<T>;
4366
4367    fn id(&self) -> usize {
4368        self.view_id
4369    }
4370
4371    fn location(&self) -> EntityLocation {
4372        EntityLocation::View(self.window_id, self.view_id)
4373    }
4374
4375    fn downgrade(&self) -> Self::Weak {
4376        self.downgrade()
4377    }
4378
4379    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4380    where
4381        Self: Sized,
4382    {
4383        weak.upgrade(cx)
4384    }
4385}
4386
4387pub struct AnyViewHandle {
4388    window_id: usize,
4389    view_id: usize,
4390    view_type: TypeId,
4391    ref_counts: Arc<Mutex<RefCounts>>,
4392
4393    #[cfg(any(test, feature = "test-support"))]
4394    handle_id: usize,
4395}
4396
4397impl AnyViewHandle {
4398    fn new(
4399        window_id: usize,
4400        view_id: usize,
4401        view_type: TypeId,
4402        ref_counts: Arc<Mutex<RefCounts>>,
4403    ) -> Self {
4404        ref_counts.lock().inc_view(window_id, view_id);
4405
4406        #[cfg(any(test, feature = "test-support"))]
4407        let handle_id = ref_counts
4408            .lock()
4409            .leak_detector
4410            .lock()
4411            .handle_created(None, view_id);
4412
4413        Self {
4414            window_id,
4415            view_id,
4416            view_type,
4417            ref_counts,
4418            #[cfg(any(test, feature = "test-support"))]
4419            handle_id,
4420        }
4421    }
4422
4423    pub fn window_id(&self) -> usize {
4424        self.window_id
4425    }
4426
4427    pub fn id(&self) -> usize {
4428        self.view_id
4429    }
4430
4431    pub fn is<T: 'static>(&self) -> bool {
4432        TypeId::of::<T>() == self.view_type
4433    }
4434
4435    pub fn is_focused(&self, cx: &AppContext) -> bool {
4436        cx.focused_view_id(self.window_id)
4437            .map_or(false, |focused_id| focused_id == self.view_id)
4438    }
4439
4440    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
4441        if self.is::<T>() {
4442            let result = Some(ViewHandle {
4443                window_id: self.window_id,
4444                view_id: self.view_id,
4445                ref_counts: self.ref_counts.clone(),
4446                view_type: PhantomData,
4447                #[cfg(any(test, feature = "test-support"))]
4448                handle_id: self.handle_id,
4449            });
4450            unsafe {
4451                Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
4452            }
4453            std::mem::forget(self);
4454            result
4455        } else {
4456            None
4457        }
4458    }
4459
4460    pub fn downgrade(&self) -> AnyWeakViewHandle {
4461        AnyWeakViewHandle {
4462            window_id: self.window_id,
4463            view_id: self.view_id,
4464            view_type: self.view_type,
4465        }
4466    }
4467
4468    pub fn view_type(&self) -> TypeId {
4469        self.view_type
4470    }
4471
4472    pub fn debug_json(&self, cx: &AppContext) -> serde_json::Value {
4473        cx.views
4474            .get(&(self.window_id, self.view_id))
4475            .map_or_else(|| serde_json::Value::Null, |view| view.debug_json(cx))
4476    }
4477}
4478
4479impl Clone for AnyViewHandle {
4480    fn clone(&self) -> Self {
4481        Self::new(
4482            self.window_id,
4483            self.view_id,
4484            self.view_type,
4485            self.ref_counts.clone(),
4486        )
4487    }
4488}
4489
4490impl From<&AnyViewHandle> for AnyViewHandle {
4491    fn from(handle: &AnyViewHandle) -> Self {
4492        handle.clone()
4493    }
4494}
4495
4496impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
4497    fn from(handle: &ViewHandle<T>) -> Self {
4498        Self::new(
4499            handle.window_id,
4500            handle.view_id,
4501            TypeId::of::<T>(),
4502            handle.ref_counts.clone(),
4503        )
4504    }
4505}
4506
4507impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
4508    fn from(handle: ViewHandle<T>) -> Self {
4509        let any_handle = AnyViewHandle {
4510            window_id: handle.window_id,
4511            view_id: handle.view_id,
4512            view_type: TypeId::of::<T>(),
4513            ref_counts: handle.ref_counts.clone(),
4514            #[cfg(any(test, feature = "test-support"))]
4515            handle_id: handle.handle_id,
4516        };
4517
4518        unsafe {
4519            Arc::decrement_strong_count(Arc::as_ptr(&handle.ref_counts));
4520        }
4521        std::mem::forget(handle);
4522        any_handle
4523    }
4524}
4525
4526impl Drop for AnyViewHandle {
4527    fn drop(&mut self) {
4528        self.ref_counts
4529            .lock()
4530            .dec_view(self.window_id, self.view_id);
4531        #[cfg(any(test, feature = "test-support"))]
4532        self.ref_counts
4533            .lock()
4534            .leak_detector
4535            .lock()
4536            .handle_dropped(self.view_id, self.handle_id);
4537    }
4538}
4539
4540pub struct AnyModelHandle {
4541    model_id: usize,
4542    model_type: TypeId,
4543    ref_counts: Arc<Mutex<RefCounts>>,
4544
4545    #[cfg(any(test, feature = "test-support"))]
4546    handle_id: usize,
4547}
4548
4549impl AnyModelHandle {
4550    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
4551        ref_counts.lock().inc_model(model_id);
4552
4553        #[cfg(any(test, feature = "test-support"))]
4554        let handle_id = ref_counts
4555            .lock()
4556            .leak_detector
4557            .lock()
4558            .handle_created(None, model_id);
4559
4560        Self {
4561            model_id,
4562            model_type,
4563            ref_counts,
4564
4565            #[cfg(any(test, feature = "test-support"))]
4566            handle_id,
4567        }
4568    }
4569
4570    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
4571        if self.is::<T>() {
4572            let result = Some(ModelHandle {
4573                model_id: self.model_id,
4574                model_type: PhantomData,
4575                ref_counts: self.ref_counts.clone(),
4576
4577                #[cfg(any(test, feature = "test-support"))]
4578                handle_id: self.handle_id,
4579            });
4580            unsafe {
4581                Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
4582            }
4583            std::mem::forget(self);
4584            result
4585        } else {
4586            None
4587        }
4588    }
4589
4590    pub fn downgrade(&self) -> AnyWeakModelHandle {
4591        AnyWeakModelHandle {
4592            model_id: self.model_id,
4593            model_type: self.model_type,
4594        }
4595    }
4596
4597    pub fn is<T: Entity>(&self) -> bool {
4598        self.model_type == TypeId::of::<T>()
4599    }
4600
4601    pub fn model_type(&self) -> TypeId {
4602        self.model_type
4603    }
4604}
4605
4606impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
4607    fn from(handle: ModelHandle<T>) -> Self {
4608        Self::new(
4609            handle.model_id,
4610            TypeId::of::<T>(),
4611            handle.ref_counts.clone(),
4612        )
4613    }
4614}
4615
4616impl Clone for AnyModelHandle {
4617    fn clone(&self) -> Self {
4618        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
4619    }
4620}
4621
4622impl Drop for AnyModelHandle {
4623    fn drop(&mut self) {
4624        let mut ref_counts = self.ref_counts.lock();
4625        ref_counts.dec_model(self.model_id);
4626
4627        #[cfg(any(test, feature = "test-support"))]
4628        ref_counts
4629            .leak_detector
4630            .lock()
4631            .handle_dropped(self.model_id, self.handle_id);
4632    }
4633}
4634
4635#[derive(Hash, PartialEq, Eq, Debug)]
4636pub struct AnyWeakModelHandle {
4637    model_id: usize,
4638    model_type: TypeId,
4639}
4640
4641impl AnyWeakModelHandle {
4642    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
4643        cx.upgrade_any_model_handle(self)
4644    }
4645    pub fn model_type(&self) -> TypeId {
4646        self.model_type
4647    }
4648
4649    fn is<T: 'static>(&self) -> bool {
4650        TypeId::of::<T>() == self.model_type
4651    }
4652
4653    pub fn downcast<T: Entity>(&self) -> Option<WeakModelHandle<T>> {
4654        if self.is::<T>() {
4655            let result = Some(WeakModelHandle {
4656                model_id: self.model_id,
4657                model_type: PhantomData,
4658            });
4659
4660            result
4661        } else {
4662            None
4663        }
4664    }
4665}
4666
4667impl<T: Entity> From<WeakModelHandle<T>> for AnyWeakModelHandle {
4668    fn from(handle: WeakModelHandle<T>) -> Self {
4669        AnyWeakModelHandle {
4670            model_id: handle.model_id,
4671            model_type: TypeId::of::<T>(),
4672        }
4673    }
4674}
4675
4676#[derive(Debug)]
4677pub struct WeakViewHandle<T> {
4678    window_id: usize,
4679    view_id: usize,
4680    view_type: PhantomData<T>,
4681}
4682
4683impl<T> WeakHandle for WeakViewHandle<T> {
4684    fn id(&self) -> usize {
4685        self.view_id
4686    }
4687}
4688
4689impl<T: View> WeakViewHandle<T> {
4690    fn new(window_id: usize, view_id: usize) -> Self {
4691        Self {
4692            window_id,
4693            view_id,
4694            view_type: PhantomData,
4695        }
4696    }
4697
4698    pub fn id(&self) -> usize {
4699        self.view_id
4700    }
4701
4702    pub fn window_id(&self) -> usize {
4703        self.window_id
4704    }
4705
4706    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
4707        cx.upgrade_view_handle(self)
4708    }
4709}
4710
4711impl<T> Clone for WeakViewHandle<T> {
4712    fn clone(&self) -> Self {
4713        Self {
4714            window_id: self.window_id,
4715            view_id: self.view_id,
4716            view_type: PhantomData,
4717        }
4718    }
4719}
4720
4721impl<T> PartialEq for WeakViewHandle<T> {
4722    fn eq(&self, other: &Self) -> bool {
4723        self.window_id == other.window_id && self.view_id == other.view_id
4724    }
4725}
4726
4727impl<T> Eq for WeakViewHandle<T> {}
4728
4729impl<T> Hash for WeakViewHandle<T> {
4730    fn hash<H: Hasher>(&self, state: &mut H) {
4731        self.window_id.hash(state);
4732        self.view_id.hash(state);
4733    }
4734}
4735
4736pub struct AnyWeakViewHandle {
4737    window_id: usize,
4738    view_id: usize,
4739    view_type: TypeId,
4740}
4741
4742impl AnyWeakViewHandle {
4743    pub fn id(&self) -> usize {
4744        self.view_id
4745    }
4746
4747    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<AnyViewHandle> {
4748        cx.upgrade_any_view_handle(self)
4749    }
4750}
4751
4752impl<T: View> From<WeakViewHandle<T>> for AnyWeakViewHandle {
4753    fn from(handle: WeakViewHandle<T>) -> Self {
4754        AnyWeakViewHandle {
4755            window_id: handle.window_id,
4756            view_id: handle.view_id,
4757            view_type: TypeId::of::<T>(),
4758        }
4759    }
4760}
4761
4762#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4763pub struct ElementStateId {
4764    view_id: usize,
4765    element_id: usize,
4766    tag: TypeId,
4767}
4768
4769pub struct ElementStateHandle<T> {
4770    value_type: PhantomData<T>,
4771    id: ElementStateId,
4772    ref_counts: Weak<Mutex<RefCounts>>,
4773}
4774
4775impl<T: 'static> ElementStateHandle<T> {
4776    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4777        ref_counts.lock().inc_element_state(id, frame_id);
4778        Self {
4779            value_type: PhantomData,
4780            id,
4781            ref_counts: Arc::downgrade(ref_counts),
4782        }
4783    }
4784
4785    pub fn id(&self) -> ElementStateId {
4786        self.id
4787    }
4788
4789    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
4790        cx.element_states
4791            .get(&self.id)
4792            .unwrap()
4793            .downcast_ref()
4794            .unwrap()
4795    }
4796
4797    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
4798    where
4799        C: DerefMut<Target = MutableAppContext>,
4800    {
4801        let mut element_state = cx.deref_mut().cx.element_states.remove(&self.id).unwrap();
4802        let result = f(element_state.downcast_mut().unwrap(), cx);
4803        cx.deref_mut()
4804            .cx
4805            .element_states
4806            .insert(self.id, element_state);
4807        result
4808    }
4809}
4810
4811impl<T> Drop for ElementStateHandle<T> {
4812    fn drop(&mut self) {
4813        if let Some(ref_counts) = self.ref_counts.upgrade() {
4814            ref_counts.lock().dec_element_state(self.id);
4815        }
4816    }
4817}
4818
4819#[must_use]
4820pub enum Subscription {
4821    Subscription {
4822        id: usize,
4823        entity_id: usize,
4824        subscriptions: Option<Weak<Mapping<usize, SubscriptionCallback>>>,
4825    },
4826    GlobalSubscription {
4827        id: usize,
4828        type_id: TypeId,
4829        subscriptions: Option<Weak<Mapping<TypeId, GlobalSubscriptionCallback>>>,
4830    },
4831    Observation {
4832        id: usize,
4833        entity_id: usize,
4834        observations: Option<Weak<Mapping<usize, ObservationCallback>>>,
4835    },
4836    GlobalObservation {
4837        id: usize,
4838        type_id: TypeId,
4839        observations: Option<Weak<Mapping<TypeId, GlobalObservationCallback>>>,
4840    },
4841    FocusObservation {
4842        id: usize,
4843        view_id: usize,
4844        observations: Option<Weak<Mapping<usize, FocusObservationCallback>>>,
4845    },
4846    WindowActivationObservation {
4847        id: usize,
4848        window_id: usize,
4849        observations: Option<Weak<Mapping<usize, WindowActivationCallback>>>,
4850    },
4851    WindowFullscreenObservation {
4852        id: usize,
4853        window_id: usize,
4854        observations: Option<Weak<Mapping<usize, WindowFullscreenCallback>>>,
4855    },
4856
4857    ReleaseObservation {
4858        id: usize,
4859        entity_id: usize,
4860        #[allow(clippy::type_complexity)]
4861        observations:
4862            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>>,
4863    },
4864    ActionObservation {
4865        id: usize,
4866        observations: Option<Weak<Mutex<BTreeMap<usize, ActionObservationCallback>>>>,
4867    },
4868}
4869
4870impl Subscription {
4871    pub fn detach(&mut self) {
4872        match self {
4873            Subscription::Subscription { subscriptions, .. } => {
4874                subscriptions.take();
4875            }
4876            Subscription::GlobalSubscription { subscriptions, .. } => {
4877                subscriptions.take();
4878            }
4879            Subscription::Observation { observations, .. } => {
4880                observations.take();
4881            }
4882            Subscription::GlobalObservation { observations, .. } => {
4883                observations.take();
4884            }
4885            Subscription::ReleaseObservation { observations, .. } => {
4886                observations.take();
4887            }
4888            Subscription::FocusObservation { observations, .. } => {
4889                observations.take();
4890            }
4891            Subscription::ActionObservation { observations, .. } => {
4892                observations.take();
4893            }
4894            Subscription::WindowActivationObservation { observations, .. } => {
4895                observations.take();
4896            }
4897            Subscription::WindowFullscreenObservation { observations, .. } => {
4898                observations.take();
4899            }
4900        }
4901    }
4902}
4903
4904impl Drop for Subscription {
4905    fn drop(&mut self) {
4906        match self {
4907            Subscription::Subscription {
4908                id,
4909                entity_id,
4910                subscriptions,
4911            } => {
4912                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
4913                    match subscriptions
4914                        .lock()
4915                        .entry(*entity_id)
4916                        .or_default()
4917                        .entry(*id)
4918                    {
4919                        btree_map::Entry::Vacant(entry) => {
4920                            entry.insert(None);
4921                        }
4922                        btree_map::Entry::Occupied(entry) => {
4923                            entry.remove();
4924                        }
4925                    }
4926                }
4927            }
4928            Subscription::GlobalSubscription {
4929                id,
4930                type_id,
4931                subscriptions,
4932            } => {
4933                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
4934                    match subscriptions.lock().entry(*type_id).or_default().entry(*id) {
4935                        btree_map::Entry::Vacant(entry) => {
4936                            entry.insert(None);
4937                        }
4938                        btree_map::Entry::Occupied(entry) => {
4939                            entry.remove();
4940                        }
4941                    }
4942                }
4943            }
4944            Subscription::Observation {
4945                id,
4946                entity_id,
4947                observations,
4948            } => {
4949                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4950                    match observations
4951                        .lock()
4952                        .entry(*entity_id)
4953                        .or_default()
4954                        .entry(*id)
4955                    {
4956                        btree_map::Entry::Vacant(entry) => {
4957                            entry.insert(None);
4958                        }
4959                        btree_map::Entry::Occupied(entry) => {
4960                            entry.remove();
4961                        }
4962                    }
4963                }
4964            }
4965            Subscription::GlobalObservation {
4966                id,
4967                type_id,
4968                observations,
4969            } => {
4970                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4971                    match observations.lock().entry(*type_id).or_default().entry(*id) {
4972                        collections::btree_map::Entry::Vacant(entry) => {
4973                            entry.insert(None);
4974                        }
4975                        collections::btree_map::Entry::Occupied(entry) => {
4976                            entry.remove();
4977                        }
4978                    }
4979                }
4980            }
4981            Subscription::ReleaseObservation {
4982                id,
4983                entity_id,
4984                observations,
4985            } => {
4986                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4987                    if let Some(observations) = observations.lock().get_mut(entity_id) {
4988                        observations.remove(id);
4989                    }
4990                }
4991            }
4992            Subscription::FocusObservation {
4993                id,
4994                view_id,
4995                observations,
4996            } => {
4997                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4998                    match observations.lock().entry(*view_id).or_default().entry(*id) {
4999                        btree_map::Entry::Vacant(entry) => {
5000                            entry.insert(None);
5001                        }
5002                        btree_map::Entry::Occupied(entry) => {
5003                            entry.remove();
5004                        }
5005                    }
5006                }
5007            }
5008            Subscription::ActionObservation { id, observations } => {
5009                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5010                    observations.lock().remove(id);
5011                }
5012            }
5013            Subscription::WindowActivationObservation {
5014                id,
5015                window_id,
5016                observations,
5017            } => {
5018                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5019                    match observations
5020                        .lock()
5021                        .entry(*window_id)
5022                        .or_default()
5023                        .entry(*id)
5024                    {
5025                        btree_map::Entry::Vacant(entry) => {
5026                            entry.insert(None);
5027                        }
5028                        btree_map::Entry::Occupied(entry) => {
5029                            entry.remove();
5030                        }
5031                    }
5032                }
5033            }
5034            Subscription::WindowFullscreenObservation {
5035                id,
5036                window_id,
5037                observations,
5038            } => {
5039                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5040                    match observations
5041                        .lock()
5042                        .entry(*window_id)
5043                        .or_default()
5044                        .entry(*id)
5045                    {
5046                        btree_map::Entry::Vacant(entry) => {
5047                            entry.insert(None);
5048                        }
5049                        btree_map::Entry::Occupied(entry) => {
5050                            entry.remove();
5051                        }
5052                    }
5053                }
5054            }
5055        }
5056    }
5057}
5058
5059lazy_static! {
5060    static ref LEAK_BACKTRACE: bool =
5061        std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty());
5062}
5063
5064#[cfg(any(test, feature = "test-support"))]
5065#[derive(Default)]
5066pub struct LeakDetector {
5067    next_handle_id: usize,
5068    #[allow(clippy::type_complexity)]
5069    handle_backtraces: HashMap<
5070        usize,
5071        (
5072            Option<&'static str>,
5073            HashMap<usize, Option<backtrace::Backtrace>>,
5074        ),
5075    >,
5076}
5077
5078#[cfg(any(test, feature = "test-support"))]
5079impl LeakDetector {
5080    fn handle_created(&mut self, type_name: Option<&'static str>, entity_id: usize) -> usize {
5081        let handle_id = post_inc(&mut self.next_handle_id);
5082        let entry = self.handle_backtraces.entry(entity_id).or_default();
5083        let backtrace = if *LEAK_BACKTRACE {
5084            Some(backtrace::Backtrace::new_unresolved())
5085        } else {
5086            None
5087        };
5088        if let Some(type_name) = type_name {
5089            entry.0.get_or_insert(type_name);
5090        }
5091        entry.1.insert(handle_id, backtrace);
5092        handle_id
5093    }
5094
5095    fn handle_dropped(&mut self, entity_id: usize, handle_id: usize) {
5096        if let Some((_, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
5097            assert!(backtraces.remove(&handle_id).is_some());
5098            if backtraces.is_empty() {
5099                self.handle_backtraces.remove(&entity_id);
5100            }
5101        }
5102    }
5103
5104    pub fn assert_dropped(&mut self, entity_id: usize) {
5105        if let Some((type_name, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
5106            for trace in backtraces.values_mut().flatten() {
5107                trace.resolve();
5108                eprintln!("{:?}", crate::util::CwdBacktrace(trace));
5109            }
5110
5111            let hint = if *LEAK_BACKTRACE {
5112                ""
5113            } else {
5114                " – set LEAK_BACKTRACE=1 for more information"
5115            };
5116
5117            panic!(
5118                "{} handles to {} {} still exist{}",
5119                backtraces.len(),
5120                type_name.unwrap_or("entity"),
5121                entity_id,
5122                hint
5123            );
5124        }
5125    }
5126
5127    pub fn detect(&mut self) {
5128        let mut found_leaks = false;
5129        for (id, (type_name, backtraces)) in self.handle_backtraces.iter_mut() {
5130            eprintln!(
5131                "leaked {} handles to {} {}",
5132                backtraces.len(),
5133                type_name.unwrap_or("entity"),
5134                id
5135            );
5136            for trace in backtraces.values_mut().flatten() {
5137                trace.resolve();
5138                eprintln!("{:?}", crate::util::CwdBacktrace(trace));
5139            }
5140            found_leaks = true;
5141        }
5142
5143        let hint = if *LEAK_BACKTRACE {
5144            ""
5145        } else {
5146            " – set LEAK_BACKTRACE=1 for more information"
5147        };
5148        assert!(!found_leaks, "detected leaked handles{}", hint);
5149    }
5150}
5151
5152#[derive(Default)]
5153struct RefCounts {
5154    entity_counts: HashMap<usize, usize>,
5155    element_state_counts: HashMap<ElementStateId, ElementStateRefCount>,
5156    dropped_models: HashSet<usize>,
5157    dropped_views: HashSet<(usize, usize)>,
5158    dropped_element_states: HashSet<ElementStateId>,
5159
5160    #[cfg(any(test, feature = "test-support"))]
5161    leak_detector: Arc<Mutex<LeakDetector>>,
5162}
5163
5164struct ElementStateRefCount {
5165    ref_count: usize,
5166    frame_id: usize,
5167}
5168
5169impl RefCounts {
5170    fn inc_model(&mut self, model_id: usize) {
5171        match self.entity_counts.entry(model_id) {
5172            Entry::Occupied(mut entry) => {
5173                *entry.get_mut() += 1;
5174            }
5175            Entry::Vacant(entry) => {
5176                entry.insert(1);
5177                self.dropped_models.remove(&model_id);
5178            }
5179        }
5180    }
5181
5182    fn inc_view(&mut self, window_id: usize, view_id: usize) {
5183        match self.entity_counts.entry(view_id) {
5184            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
5185            Entry::Vacant(entry) => {
5186                entry.insert(1);
5187                self.dropped_views.remove(&(window_id, view_id));
5188            }
5189        }
5190    }
5191
5192    fn inc_element_state(&mut self, id: ElementStateId, frame_id: usize) {
5193        match self.element_state_counts.entry(id) {
5194            Entry::Occupied(mut entry) => {
5195                let entry = entry.get_mut();
5196                if entry.frame_id == frame_id || entry.ref_count >= 2 {
5197                    panic!("used the same element state more than once in the same frame");
5198                }
5199                entry.ref_count += 1;
5200                entry.frame_id = frame_id;
5201            }
5202            Entry::Vacant(entry) => {
5203                entry.insert(ElementStateRefCount {
5204                    ref_count: 1,
5205                    frame_id,
5206                });
5207                self.dropped_element_states.remove(&id);
5208            }
5209        }
5210    }
5211
5212    fn dec_model(&mut self, model_id: usize) {
5213        let count = self.entity_counts.get_mut(&model_id).unwrap();
5214        *count -= 1;
5215        if *count == 0 {
5216            self.entity_counts.remove(&model_id);
5217            self.dropped_models.insert(model_id);
5218        }
5219    }
5220
5221    fn dec_view(&mut self, window_id: usize, view_id: usize) {
5222        let count = self.entity_counts.get_mut(&view_id).unwrap();
5223        *count -= 1;
5224        if *count == 0 {
5225            self.entity_counts.remove(&view_id);
5226            self.dropped_views.insert((window_id, view_id));
5227        }
5228    }
5229
5230    fn dec_element_state(&mut self, id: ElementStateId) {
5231        let entry = self.element_state_counts.get_mut(&id).unwrap();
5232        entry.ref_count -= 1;
5233        if entry.ref_count == 0 {
5234            self.element_state_counts.remove(&id);
5235            self.dropped_element_states.insert(id);
5236        }
5237    }
5238
5239    fn is_entity_alive(&self, entity_id: usize) -> bool {
5240        self.entity_counts.contains_key(&entity_id)
5241    }
5242
5243    fn take_dropped(
5244        &mut self,
5245    ) -> (
5246        HashSet<usize>,
5247        HashSet<(usize, usize)>,
5248        HashSet<ElementStateId>,
5249    ) {
5250        (
5251            std::mem::take(&mut self.dropped_models),
5252            std::mem::take(&mut self.dropped_views),
5253            std::mem::take(&mut self.dropped_element_states),
5254        )
5255    }
5256}
5257
5258#[cfg(test)]
5259mod tests {
5260    use super::*;
5261    use crate::{actions, elements::*, impl_actions, MouseButton, MouseButtonEvent};
5262    use serde::Deserialize;
5263    use smol::future::poll_once;
5264    use std::{
5265        cell::Cell,
5266        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
5267    };
5268
5269    #[crate::test(self)]
5270    fn test_model_handles(cx: &mut MutableAppContext) {
5271        struct Model {
5272            other: Option<ModelHandle<Model>>,
5273            events: Vec<String>,
5274        }
5275
5276        impl Entity for Model {
5277            type Event = usize;
5278        }
5279
5280        impl Model {
5281            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
5282                if let Some(other) = other.as_ref() {
5283                    cx.observe(other, |me, _, _| {
5284                        me.events.push("notified".into());
5285                    })
5286                    .detach();
5287                    cx.subscribe(other, |me, _, event, _| {
5288                        me.events.push(format!("observed event {}", event));
5289                    })
5290                    .detach();
5291                }
5292
5293                Self {
5294                    other,
5295                    events: Vec::new(),
5296                }
5297            }
5298        }
5299
5300        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
5301        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
5302        assert_eq!(cx.cx.models.len(), 2);
5303
5304        handle_1.update(cx, |model, cx| {
5305            model.events.push("updated".into());
5306            cx.emit(1);
5307            cx.notify();
5308            cx.emit(2);
5309        });
5310        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5311        assert_eq!(
5312            handle_2.read(cx).events,
5313            vec![
5314                "observed event 1".to_string(),
5315                "notified".to_string(),
5316                "observed event 2".to_string(),
5317            ]
5318        );
5319
5320        handle_2.update(cx, |model, _| {
5321            drop(handle_1);
5322            model.other.take();
5323        });
5324
5325        assert_eq!(cx.cx.models.len(), 1);
5326        assert!(cx.subscriptions.is_empty());
5327        assert!(cx.observations.is_empty());
5328    }
5329
5330    #[crate::test(self)]
5331    fn test_model_events(cx: &mut MutableAppContext) {
5332        #[derive(Default)]
5333        struct Model {
5334            events: Vec<usize>,
5335        }
5336
5337        impl Entity for Model {
5338            type Event = usize;
5339        }
5340
5341        let handle_1 = cx.add_model(|_| Model::default());
5342        let handle_2 = cx.add_model(|_| Model::default());
5343
5344        handle_1.update(cx, |_, cx| {
5345            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
5346                model.events.push(*event);
5347
5348                cx.subscribe(&emitter, |model, _, event, _| {
5349                    model.events.push(*event * 2);
5350                })
5351                .detach();
5352            })
5353            .detach();
5354        });
5355
5356        handle_2.update(cx, |_, c| c.emit(7));
5357        assert_eq!(handle_1.read(cx).events, vec![7]);
5358
5359        handle_2.update(cx, |_, c| c.emit(5));
5360        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
5361    }
5362
5363    #[crate::test(self)]
5364    fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
5365        #[derive(Default)]
5366        struct Model;
5367
5368        impl Entity for Model {
5369            type Event = ();
5370        }
5371
5372        let events = Rc::new(RefCell::new(Vec::new()));
5373        cx.add_model(|cx| {
5374            drop(cx.subscribe(&cx.handle(), {
5375                let events = events.clone();
5376                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
5377            }));
5378            cx.subscribe(&cx.handle(), {
5379                let events = events.clone();
5380                move |_, _, _, _| events.borrow_mut().push("before emit")
5381            })
5382            .detach();
5383            cx.emit(());
5384            cx.subscribe(&cx.handle(), {
5385                let events = events.clone();
5386                move |_, _, _, _| events.borrow_mut().push("after emit")
5387            })
5388            .detach();
5389            Model
5390        });
5391        assert_eq!(*events.borrow(), ["before emit"]);
5392    }
5393
5394    #[crate::test(self)]
5395    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
5396        #[derive(Default)]
5397        struct Model {
5398            count: usize,
5399            events: Vec<usize>,
5400        }
5401
5402        impl Entity for Model {
5403            type Event = ();
5404        }
5405
5406        let handle_1 = cx.add_model(|_| Model::default());
5407        let handle_2 = cx.add_model(|_| Model::default());
5408
5409        handle_1.update(cx, |_, c| {
5410            c.observe(&handle_2, move |model, observed, c| {
5411                model.events.push(observed.read(c).count);
5412                c.observe(&observed, |model, observed, c| {
5413                    model.events.push(observed.read(c).count * 2);
5414                })
5415                .detach();
5416            })
5417            .detach();
5418        });
5419
5420        handle_2.update(cx, |model, c| {
5421            model.count = 7;
5422            c.notify()
5423        });
5424        assert_eq!(handle_1.read(cx).events, vec![7]);
5425
5426        handle_2.update(cx, |model, c| {
5427            model.count = 5;
5428            c.notify()
5429        });
5430        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
5431    }
5432
5433    #[crate::test(self)]
5434    fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
5435        #[derive(Default)]
5436        struct Model;
5437
5438        impl Entity for Model {
5439            type Event = ();
5440        }
5441
5442        let events = Rc::new(RefCell::new(Vec::new()));
5443        cx.add_model(|cx| {
5444            drop(cx.observe(&cx.handle(), {
5445                let events = events.clone();
5446                move |_, _, _| events.borrow_mut().push("dropped before flush")
5447            }));
5448            cx.observe(&cx.handle(), {
5449                let events = events.clone();
5450                move |_, _, _| events.borrow_mut().push("before notify")
5451            })
5452            .detach();
5453            cx.notify();
5454            cx.observe(&cx.handle(), {
5455                let events = events.clone();
5456                move |_, _, _| events.borrow_mut().push("after notify")
5457            })
5458            .detach();
5459            Model
5460        });
5461        assert_eq!(*events.borrow(), ["before notify"]);
5462    }
5463
5464    #[crate::test(self)]
5465    fn test_defer_and_after_window_update(cx: &mut MutableAppContext) {
5466        struct View {
5467            render_count: usize,
5468        }
5469
5470        impl Entity for View {
5471            type Event = usize;
5472        }
5473
5474        impl super::View for View {
5475            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5476                post_inc(&mut self.render_count);
5477                Empty::new().boxed()
5478            }
5479
5480            fn ui_name() -> &'static str {
5481                "View"
5482            }
5483        }
5484
5485        let (_, view) = cx.add_window(Default::default(), |_| View { render_count: 0 });
5486        let called_defer = Rc::new(AtomicBool::new(false));
5487        let called_after_window_update = Rc::new(AtomicBool::new(false));
5488
5489        view.update(cx, |this, cx| {
5490            assert_eq!(this.render_count, 1);
5491            cx.defer({
5492                let called_defer = called_defer.clone();
5493                move |this, _| {
5494                    assert_eq!(this.render_count, 1);
5495                    called_defer.store(true, SeqCst);
5496                }
5497            });
5498            cx.after_window_update({
5499                let called_after_window_update = called_after_window_update.clone();
5500                move |this, cx| {
5501                    assert_eq!(this.render_count, 2);
5502                    called_after_window_update.store(true, SeqCst);
5503                    cx.notify();
5504                }
5505            });
5506            assert!(!called_defer.load(SeqCst));
5507            assert!(!called_after_window_update.load(SeqCst));
5508            cx.notify();
5509        });
5510
5511        assert!(called_defer.load(SeqCst));
5512        assert!(called_after_window_update.load(SeqCst));
5513        assert_eq!(view.read(cx).render_count, 3);
5514    }
5515
5516    #[crate::test(self)]
5517    fn test_view_handles(cx: &mut MutableAppContext) {
5518        struct View {
5519            other: Option<ViewHandle<View>>,
5520            events: Vec<String>,
5521        }
5522
5523        impl Entity for View {
5524            type Event = usize;
5525        }
5526
5527        impl super::View for View {
5528            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5529                Empty::new().boxed()
5530            }
5531
5532            fn ui_name() -> &'static str {
5533                "View"
5534            }
5535        }
5536
5537        impl View {
5538            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
5539                if let Some(other) = other.as_ref() {
5540                    cx.subscribe(other, |me, _, event, _| {
5541                        me.events.push(format!("observed event {}", event));
5542                    })
5543                    .detach();
5544                }
5545                Self {
5546                    other,
5547                    events: Vec::new(),
5548                }
5549            }
5550        }
5551
5552        let (_, root_view) = cx.add_window(Default::default(), |cx| View::new(None, cx));
5553        let handle_1 = cx.add_view(&root_view, |cx| View::new(None, cx));
5554        let handle_2 = cx.add_view(&root_view, |cx| View::new(Some(handle_1.clone()), cx));
5555        assert_eq!(cx.cx.views.len(), 3);
5556
5557        handle_1.update(cx, |view, cx| {
5558            view.events.push("updated".into());
5559            cx.emit(1);
5560            cx.emit(2);
5561        });
5562        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5563        assert_eq!(
5564            handle_2.read(cx).events,
5565            vec![
5566                "observed event 1".to_string(),
5567                "observed event 2".to_string(),
5568            ]
5569        );
5570
5571        handle_2.update(cx, |view, _| {
5572            drop(handle_1);
5573            view.other.take();
5574        });
5575
5576        assert_eq!(cx.cx.views.len(), 2);
5577        assert!(cx.subscriptions.is_empty());
5578        assert!(cx.observations.is_empty());
5579    }
5580
5581    #[crate::test(self)]
5582    fn test_add_window(cx: &mut MutableAppContext) {
5583        struct View {
5584            mouse_down_count: Arc<AtomicUsize>,
5585        }
5586
5587        impl Entity for View {
5588            type Event = ();
5589        }
5590
5591        impl super::View for View {
5592            fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
5593                enum Handler {}
5594                let mouse_down_count = self.mouse_down_count.clone();
5595                MouseEventHandler::<Handler>::new(0, cx, |_, _| Empty::new().boxed())
5596                    .on_down(MouseButton::Left, move |_, _| {
5597                        mouse_down_count.fetch_add(1, SeqCst);
5598                    })
5599                    .boxed()
5600            }
5601
5602            fn ui_name() -> &'static str {
5603                "View"
5604            }
5605        }
5606
5607        let mouse_down_count = Arc::new(AtomicUsize::new(0));
5608        let (window_id, _) = cx.add_window(Default::default(), |_| View {
5609            mouse_down_count: mouse_down_count.clone(),
5610        });
5611        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
5612        // Ensure window's root element is in a valid lifecycle state.
5613        presenter.borrow_mut().dispatch_event(
5614            Event::MouseDown(MouseButtonEvent {
5615                position: Default::default(),
5616                button: MouseButton::Left,
5617                ctrl: false,
5618                alt: false,
5619                shift: false,
5620                cmd: false,
5621                click_count: 1,
5622            }),
5623            false,
5624            cx,
5625        );
5626        assert_eq!(mouse_down_count.load(SeqCst), 1);
5627    }
5628
5629    #[crate::test(self)]
5630    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
5631        struct Model {
5632            released: Rc<Cell<bool>>,
5633        }
5634
5635        struct View {
5636            released: Rc<Cell<bool>>,
5637        }
5638
5639        impl Entity for Model {
5640            type Event = ();
5641
5642            fn release(&mut self, _: &mut MutableAppContext) {
5643                self.released.set(true);
5644            }
5645        }
5646
5647        impl Entity for View {
5648            type Event = ();
5649
5650            fn release(&mut self, _: &mut MutableAppContext) {
5651                self.released.set(true);
5652            }
5653        }
5654
5655        impl super::View for View {
5656            fn ui_name() -> &'static str {
5657                "View"
5658            }
5659
5660            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5661                Empty::new().boxed()
5662            }
5663        }
5664
5665        let model_released = Rc::new(Cell::new(false));
5666        let model_release_observed = Rc::new(Cell::new(false));
5667        let view_released = Rc::new(Cell::new(false));
5668        let view_release_observed = Rc::new(Cell::new(false));
5669
5670        let model = cx.add_model(|_| Model {
5671            released: model_released.clone(),
5672        });
5673        let (window_id, view) = cx.add_window(Default::default(), |_| View {
5674            released: view_released.clone(),
5675        });
5676        assert!(!model_released.get());
5677        assert!(!view_released.get());
5678
5679        cx.observe_release(&model, {
5680            let model_release_observed = model_release_observed.clone();
5681            move |_, _| model_release_observed.set(true)
5682        })
5683        .detach();
5684        cx.observe_release(&view, {
5685            let view_release_observed = view_release_observed.clone();
5686            move |_, _| view_release_observed.set(true)
5687        })
5688        .detach();
5689
5690        cx.update(move |_| {
5691            drop(model);
5692        });
5693        assert!(model_released.get());
5694        assert!(model_release_observed.get());
5695
5696        drop(view);
5697        cx.remove_window(window_id);
5698        assert!(view_released.get());
5699        assert!(view_release_observed.get());
5700    }
5701
5702    #[crate::test(self)]
5703    fn test_view_events(cx: &mut MutableAppContext) {
5704        #[derive(Default)]
5705        struct View {
5706            events: Vec<usize>,
5707        }
5708
5709        impl Entity for View {
5710            type Event = usize;
5711        }
5712
5713        impl super::View for View {
5714            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5715                Empty::new().boxed()
5716            }
5717
5718            fn ui_name() -> &'static str {
5719                "View"
5720            }
5721        }
5722
5723        struct Model;
5724
5725        impl Entity for Model {
5726            type Event = usize;
5727        }
5728
5729        let (_, handle_1) = cx.add_window(Default::default(), |_| View::default());
5730        let handle_2 = cx.add_view(&handle_1, |_| View::default());
5731        let handle_3 = cx.add_model(|_| Model);
5732
5733        handle_1.update(cx, |_, cx| {
5734            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
5735                me.events.push(*event);
5736
5737                cx.subscribe(&emitter, |me, _, event, _| {
5738                    me.events.push(*event * 2);
5739                })
5740                .detach();
5741            })
5742            .detach();
5743
5744            cx.subscribe(&handle_3, |me, _, event, _| {
5745                me.events.push(*event);
5746            })
5747            .detach();
5748        });
5749
5750        handle_2.update(cx, |_, c| c.emit(7));
5751        assert_eq!(handle_1.read(cx).events, vec![7]);
5752
5753        handle_2.update(cx, |_, c| c.emit(5));
5754        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
5755
5756        handle_3.update(cx, |_, c| c.emit(9));
5757        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
5758    }
5759
5760    #[crate::test(self)]
5761    fn test_global_events(cx: &mut MutableAppContext) {
5762        #[derive(Clone, Debug, Eq, PartialEq)]
5763        struct GlobalEvent(u64);
5764
5765        let events = Rc::new(RefCell::new(Vec::new()));
5766        let first_subscription;
5767        let second_subscription;
5768
5769        {
5770            let events = events.clone();
5771            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5772                events.borrow_mut().push(("First", e.clone()));
5773            });
5774        }
5775
5776        {
5777            let events = events.clone();
5778            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5779                events.borrow_mut().push(("Second", e.clone()));
5780            });
5781        }
5782
5783        cx.update(|cx| {
5784            cx.emit_global(GlobalEvent(1));
5785            cx.emit_global(GlobalEvent(2));
5786        });
5787
5788        drop(first_subscription);
5789
5790        cx.update(|cx| {
5791            cx.emit_global(GlobalEvent(3));
5792        });
5793
5794        drop(second_subscription);
5795
5796        cx.update(|cx| {
5797            cx.emit_global(GlobalEvent(4));
5798        });
5799
5800        assert_eq!(
5801            &*events.borrow(),
5802            &[
5803                ("First", GlobalEvent(1)),
5804                ("Second", GlobalEvent(1)),
5805                ("First", GlobalEvent(2)),
5806                ("Second", GlobalEvent(2)),
5807                ("Second", GlobalEvent(3)),
5808            ]
5809        );
5810    }
5811
5812    #[crate::test(self)]
5813    fn test_global_events_emitted_before_subscription_in_same_update_cycle(
5814        cx: &mut MutableAppContext,
5815    ) {
5816        let events = Rc::new(RefCell::new(Vec::new()));
5817        cx.update(|cx| {
5818            {
5819                let events = events.clone();
5820                drop(cx.subscribe_global(move |_: &(), _| {
5821                    events.borrow_mut().push("dropped before emit");
5822                }));
5823            }
5824
5825            {
5826                let events = events.clone();
5827                cx.subscribe_global(move |_: &(), _| {
5828                    events.borrow_mut().push("before emit");
5829                })
5830                .detach();
5831            }
5832
5833            cx.emit_global(());
5834
5835            {
5836                let events = events.clone();
5837                cx.subscribe_global(move |_: &(), _| {
5838                    events.borrow_mut().push("after emit");
5839                })
5840                .detach();
5841            }
5842        });
5843
5844        assert_eq!(*events.borrow(), ["before emit"]);
5845    }
5846
5847    #[crate::test(self)]
5848    fn test_global_nested_events(cx: &mut MutableAppContext) {
5849        #[derive(Clone, Debug, Eq, PartialEq)]
5850        struct GlobalEvent(u64);
5851
5852        let events = Rc::new(RefCell::new(Vec::new()));
5853
5854        {
5855            let events = events.clone();
5856            cx.subscribe_global(move |e: &GlobalEvent, cx| {
5857                events.borrow_mut().push(("Outer", e.clone()));
5858
5859                if e.0 == 1 {
5860                    let events = events.clone();
5861                    cx.subscribe_global(move |e: &GlobalEvent, _| {
5862                        events.borrow_mut().push(("Inner", e.clone()));
5863                    })
5864                    .detach();
5865                }
5866            })
5867            .detach();
5868        }
5869
5870        cx.update(|cx| {
5871            cx.emit_global(GlobalEvent(1));
5872            cx.emit_global(GlobalEvent(2));
5873            cx.emit_global(GlobalEvent(3));
5874        });
5875        cx.update(|cx| {
5876            cx.emit_global(GlobalEvent(4));
5877        });
5878
5879        assert_eq!(
5880            &*events.borrow(),
5881            &[
5882                ("Outer", GlobalEvent(1)),
5883                ("Outer", GlobalEvent(2)),
5884                ("Outer", GlobalEvent(3)),
5885                ("Outer", GlobalEvent(4)),
5886                ("Inner", GlobalEvent(4)),
5887            ]
5888        );
5889    }
5890
5891    #[crate::test(self)]
5892    fn test_global(cx: &mut MutableAppContext) {
5893        type Global = usize;
5894
5895        let observation_count = Rc::new(RefCell::new(0));
5896        let subscription = cx.observe_global::<Global, _>({
5897            let observation_count = observation_count.clone();
5898            move |_| {
5899                *observation_count.borrow_mut() += 1;
5900            }
5901        });
5902
5903        assert!(!cx.has_global::<Global>());
5904        assert_eq!(cx.default_global::<Global>(), &0);
5905        assert_eq!(*observation_count.borrow(), 1);
5906        assert!(cx.has_global::<Global>());
5907        assert_eq!(
5908            cx.update_global::<Global, _, _>(|global, _| {
5909                *global = 1;
5910                "Update Result"
5911            }),
5912            "Update Result"
5913        );
5914        assert_eq!(*observation_count.borrow(), 2);
5915        assert_eq!(cx.global::<Global>(), &1);
5916
5917        drop(subscription);
5918        cx.update_global::<Global, _, _>(|global, _| {
5919            *global = 2;
5920        });
5921        assert_eq!(*observation_count.borrow(), 2);
5922
5923        type OtherGlobal = f32;
5924
5925        let observation_count = Rc::new(RefCell::new(0));
5926        cx.observe_global::<OtherGlobal, _>({
5927            let observation_count = observation_count.clone();
5928            move |_| {
5929                *observation_count.borrow_mut() += 1;
5930            }
5931        })
5932        .detach();
5933
5934        assert_eq!(
5935            cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
5936                assert_eq!(global, &0.0);
5937                *global = 2.0;
5938                "Default update result"
5939            }),
5940            "Default update result"
5941        );
5942        assert_eq!(cx.global::<OtherGlobal>(), &2.0);
5943        assert_eq!(*observation_count.borrow(), 1);
5944    }
5945
5946    #[crate::test(self)]
5947    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
5948        struct View;
5949
5950        impl Entity for View {
5951            type Event = ();
5952        }
5953
5954        impl super::View for View {
5955            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5956                Empty::new().boxed()
5957            }
5958
5959            fn ui_name() -> &'static str {
5960                "View"
5961            }
5962        }
5963
5964        struct Model;
5965
5966        impl Entity for Model {
5967            type Event = ();
5968        }
5969
5970        let (_, root_view) = cx.add_window(Default::default(), |_| View);
5971        let observing_view = cx.add_view(&root_view, |_| View);
5972        let emitting_view = cx.add_view(&root_view, |_| View);
5973        let observing_model = cx.add_model(|_| Model);
5974        let observed_model = cx.add_model(|_| Model);
5975
5976        observing_view.update(cx, |_, cx| {
5977            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
5978            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5979        });
5980        observing_model.update(cx, |_, cx| {
5981            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5982        });
5983
5984        cx.update(|_| {
5985            drop(observing_view);
5986            drop(observing_model);
5987        });
5988
5989        emitting_view.update(cx, |_, cx| cx.emit(()));
5990        observed_model.update(cx, |_, cx| cx.emit(()));
5991    }
5992
5993    #[crate::test(self)]
5994    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
5995        #[derive(Default)]
5996        struct TestView;
5997
5998        impl Entity for TestView {
5999            type Event = ();
6000        }
6001
6002        impl View for TestView {
6003            fn ui_name() -> &'static str {
6004                "TestView"
6005            }
6006
6007            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6008                Empty::new().boxed()
6009            }
6010        }
6011
6012        let events = Rc::new(RefCell::new(Vec::new()));
6013        cx.add_window(Default::default(), |cx| {
6014            drop(cx.subscribe(&cx.handle(), {
6015                let events = events.clone();
6016                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
6017            }));
6018            cx.subscribe(&cx.handle(), {
6019                let events = events.clone();
6020                move |_, _, _, _| events.borrow_mut().push("before emit")
6021            })
6022            .detach();
6023            cx.emit(());
6024            cx.subscribe(&cx.handle(), {
6025                let events = events.clone();
6026                move |_, _, _, _| events.borrow_mut().push("after emit")
6027            })
6028            .detach();
6029            TestView
6030        });
6031        assert_eq!(*events.borrow(), ["before emit"]);
6032    }
6033
6034    #[crate::test(self)]
6035    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
6036        #[derive(Default)]
6037        struct View {
6038            events: Vec<usize>,
6039        }
6040
6041        impl Entity for View {
6042            type Event = usize;
6043        }
6044
6045        impl super::View for View {
6046            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6047                Empty::new().boxed()
6048            }
6049
6050            fn ui_name() -> &'static str {
6051                "View"
6052            }
6053        }
6054
6055        #[derive(Default)]
6056        struct Model {
6057            count: usize,
6058        }
6059
6060        impl Entity for Model {
6061            type Event = ();
6062        }
6063
6064        let (_, view) = cx.add_window(Default::default(), |_| View::default());
6065        let model = cx.add_model(|_| Model::default());
6066
6067        view.update(cx, |_, c| {
6068            c.observe(&model, |me, observed, c| {
6069                me.events.push(observed.read(c).count)
6070            })
6071            .detach();
6072        });
6073
6074        model.update(cx, |model, c| {
6075            model.count = 11;
6076            c.notify();
6077        });
6078        assert_eq!(view.read(cx).events, vec![11]);
6079    }
6080
6081    #[crate::test(self)]
6082    fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
6083        #[derive(Default)]
6084        struct TestView;
6085
6086        impl Entity for TestView {
6087            type Event = ();
6088        }
6089
6090        impl View for TestView {
6091            fn ui_name() -> &'static str {
6092                "TestView"
6093            }
6094
6095            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6096                Empty::new().boxed()
6097            }
6098        }
6099
6100        let events = Rc::new(RefCell::new(Vec::new()));
6101        cx.add_window(Default::default(), |cx| {
6102            drop(cx.observe(&cx.handle(), {
6103                let events = events.clone();
6104                move |_, _, _| events.borrow_mut().push("dropped before flush")
6105            }));
6106            cx.observe(&cx.handle(), {
6107                let events = events.clone();
6108                move |_, _, _| events.borrow_mut().push("before notify")
6109            })
6110            .detach();
6111            cx.notify();
6112            cx.observe(&cx.handle(), {
6113                let events = events.clone();
6114                move |_, _, _| events.borrow_mut().push("after notify")
6115            })
6116            .detach();
6117            TestView
6118        });
6119        assert_eq!(*events.borrow(), ["before notify"]);
6120    }
6121
6122    #[crate::test(self)]
6123    fn test_dropping_observers(cx: &mut MutableAppContext) {
6124        struct View;
6125
6126        impl Entity for View {
6127            type Event = ();
6128        }
6129
6130        impl super::View for View {
6131            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6132                Empty::new().boxed()
6133            }
6134
6135            fn ui_name() -> &'static str {
6136                "View"
6137            }
6138        }
6139
6140        struct Model;
6141
6142        impl Entity for Model {
6143            type Event = ();
6144        }
6145
6146        let (_, root_view) = cx.add_window(Default::default(), |_| View);
6147        let observing_view = cx.add_view(root_view, |_| View);
6148        let observing_model = cx.add_model(|_| Model);
6149        let observed_model = cx.add_model(|_| Model);
6150
6151        observing_view.update(cx, |_, cx| {
6152            cx.observe(&observed_model, |_, _, _| {}).detach();
6153        });
6154        observing_model.update(cx, |_, cx| {
6155            cx.observe(&observed_model, |_, _, _| {}).detach();
6156        });
6157
6158        cx.update(|_| {
6159            drop(observing_view);
6160            drop(observing_model);
6161        });
6162
6163        observed_model.update(cx, |_, cx| cx.notify());
6164    }
6165
6166    #[crate::test(self)]
6167    fn test_dropping_subscriptions_during_callback(cx: &mut MutableAppContext) {
6168        struct Model;
6169
6170        impl Entity for Model {
6171            type Event = u64;
6172        }
6173
6174        // Events
6175        let observing_model = cx.add_model(|_| Model);
6176        let observed_model = cx.add_model(|_| Model);
6177
6178        let events = Rc::new(RefCell::new(Vec::new()));
6179
6180        observing_model.update(cx, |_, cx| {
6181            let events = events.clone();
6182            let subscription = Rc::new(RefCell::new(None));
6183            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
6184                let subscription = subscription.clone();
6185                move |_, _, e, _| {
6186                    subscription.borrow_mut().take();
6187                    events.borrow_mut().push(*e);
6188                }
6189            }));
6190        });
6191
6192        observed_model.update(cx, |_, cx| {
6193            cx.emit(1);
6194            cx.emit(2);
6195        });
6196
6197        assert_eq!(*events.borrow(), [1]);
6198
6199        // Global Events
6200        #[derive(Clone, Debug, Eq, PartialEq)]
6201        struct GlobalEvent(u64);
6202
6203        let events = Rc::new(RefCell::new(Vec::new()));
6204
6205        {
6206            let events = events.clone();
6207            let subscription = Rc::new(RefCell::new(None));
6208            *subscription.borrow_mut() = Some(cx.subscribe_global({
6209                let subscription = subscription.clone();
6210                move |e: &GlobalEvent, _| {
6211                    subscription.borrow_mut().take();
6212                    events.borrow_mut().push(e.clone());
6213                }
6214            }));
6215        }
6216
6217        cx.update(|cx| {
6218            cx.emit_global(GlobalEvent(1));
6219            cx.emit_global(GlobalEvent(2));
6220        });
6221
6222        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
6223
6224        // Model Observation
6225        let observing_model = cx.add_model(|_| Model);
6226        let observed_model = cx.add_model(|_| Model);
6227
6228        let observation_count = Rc::new(RefCell::new(0));
6229
6230        observing_model.update(cx, |_, cx| {
6231            let observation_count = observation_count.clone();
6232            let subscription = Rc::new(RefCell::new(None));
6233            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
6234                let subscription = subscription.clone();
6235                move |_, _, _| {
6236                    subscription.borrow_mut().take();
6237                    *observation_count.borrow_mut() += 1;
6238                }
6239            }));
6240        });
6241
6242        observed_model.update(cx, |_, cx| {
6243            cx.notify();
6244        });
6245
6246        observed_model.update(cx, |_, cx| {
6247            cx.notify();
6248        });
6249
6250        assert_eq!(*observation_count.borrow(), 1);
6251
6252        // View Observation
6253        struct View;
6254
6255        impl Entity for View {
6256            type Event = ();
6257        }
6258
6259        impl super::View for View {
6260            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6261                Empty::new().boxed()
6262            }
6263
6264            fn ui_name() -> &'static str {
6265                "View"
6266            }
6267        }
6268
6269        let (_, root_view) = cx.add_window(Default::default(), |_| View);
6270        let observing_view = cx.add_view(&root_view, |_| View);
6271        let observed_view = cx.add_view(&root_view, |_| View);
6272
6273        let observation_count = Rc::new(RefCell::new(0));
6274        observing_view.update(cx, |_, cx| {
6275            let observation_count = observation_count.clone();
6276            let subscription = Rc::new(RefCell::new(None));
6277            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
6278                let subscription = subscription.clone();
6279                move |_, _, _| {
6280                    subscription.borrow_mut().take();
6281                    *observation_count.borrow_mut() += 1;
6282                }
6283            }));
6284        });
6285
6286        observed_view.update(cx, |_, cx| {
6287            cx.notify();
6288        });
6289
6290        observed_view.update(cx, |_, cx| {
6291            cx.notify();
6292        });
6293
6294        assert_eq!(*observation_count.borrow(), 1);
6295
6296        // Global Observation
6297        let observation_count = Rc::new(RefCell::new(0));
6298        let subscription = Rc::new(RefCell::new(None));
6299        *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
6300            let observation_count = observation_count.clone();
6301            let subscription = subscription.clone();
6302            move |_| {
6303                subscription.borrow_mut().take();
6304                *observation_count.borrow_mut() += 1;
6305            }
6306        }));
6307
6308        cx.default_global::<()>();
6309        cx.set_global(());
6310        assert_eq!(*observation_count.borrow(), 1);
6311    }
6312
6313    #[crate::test(self)]
6314    fn test_focus(cx: &mut MutableAppContext) {
6315        struct View {
6316            name: String,
6317            events: Arc<Mutex<Vec<String>>>,
6318        }
6319
6320        impl Entity for View {
6321            type Event = ();
6322        }
6323
6324        impl super::View for View {
6325            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6326                Empty::new().boxed()
6327            }
6328
6329            fn ui_name() -> &'static str {
6330                "View"
6331            }
6332
6333            fn on_focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
6334                if cx.handle().id() == focused.id() {
6335                    self.events.lock().push(format!("{} focused", &self.name));
6336                }
6337            }
6338
6339            fn on_focus_out(&mut self, blurred: AnyViewHandle, cx: &mut ViewContext<Self>) {
6340                if cx.handle().id() == blurred.id() {
6341                    self.events.lock().push(format!("{} blurred", &self.name));
6342                }
6343            }
6344        }
6345
6346        let view_events: Arc<Mutex<Vec<String>>> = Default::default();
6347        let (_, view_1) = cx.add_window(Default::default(), |_| View {
6348            events: view_events.clone(),
6349            name: "view 1".to_string(),
6350        });
6351        let view_2 = cx.add_view(&view_1, |_| View {
6352            events: view_events.clone(),
6353            name: "view 2".to_string(),
6354        });
6355
6356        let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
6357        view_1.update(cx, |_, cx| {
6358            cx.observe_focus(&view_2, {
6359                let observed_events = observed_events.clone();
6360                move |this, view, focused, cx| {
6361                    let label = if focused { "focus" } else { "blur" };
6362                    observed_events.lock().push(format!(
6363                        "{} observed {}'s {}",
6364                        this.name,
6365                        view.read(cx).name,
6366                        label
6367                    ))
6368                }
6369            })
6370            .detach();
6371        });
6372        view_2.update(cx, |_, cx| {
6373            cx.observe_focus(&view_1, {
6374                let observed_events = observed_events.clone();
6375                move |this, view, focused, cx| {
6376                    let label = if focused { "focus" } else { "blur" };
6377                    observed_events.lock().push(format!(
6378                        "{} observed {}'s {}",
6379                        this.name,
6380                        view.read(cx).name,
6381                        label
6382                    ))
6383                }
6384            })
6385            .detach();
6386        });
6387        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6388        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6389
6390        view_1.update(cx, |_, cx| {
6391            // Ensure focus events are sent for all intermediate focuses
6392            cx.focus(&view_2);
6393            cx.focus(&view_1);
6394            cx.focus(&view_2);
6395        });
6396        assert_eq!(
6397            mem::take(&mut *view_events.lock()),
6398            [
6399                "view 1 blurred",
6400                "view 2 focused",
6401                "view 2 blurred",
6402                "view 1 focused",
6403                "view 1 blurred",
6404                "view 2 focused"
6405            ],
6406        );
6407        assert_eq!(
6408            mem::take(&mut *observed_events.lock()),
6409            [
6410                "view 2 observed view 1's blur",
6411                "view 1 observed view 2's focus",
6412                "view 1 observed view 2's blur",
6413                "view 2 observed view 1's focus",
6414                "view 2 observed view 1's blur",
6415                "view 1 observed view 2's focus"
6416            ]
6417        );
6418
6419        view_1.update(cx, |_, cx| cx.focus(&view_1));
6420        assert_eq!(
6421            mem::take(&mut *view_events.lock()),
6422            ["view 2 blurred", "view 1 focused"],
6423        );
6424        assert_eq!(
6425            mem::take(&mut *observed_events.lock()),
6426            [
6427                "view 1 observed view 2's blur",
6428                "view 2 observed view 1's focus"
6429            ]
6430        );
6431
6432        view_1.update(cx, |_, cx| cx.focus(&view_2));
6433        assert_eq!(
6434            mem::take(&mut *view_events.lock()),
6435            ["view 1 blurred", "view 2 focused"],
6436        );
6437        assert_eq!(
6438            mem::take(&mut *observed_events.lock()),
6439            [
6440                "view 2 observed view 1's blur",
6441                "view 1 observed view 2's focus"
6442            ]
6443        );
6444
6445        view_1.update(cx, |_, _| drop(view_2));
6446        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6447        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6448    }
6449
6450    #[crate::test(self)]
6451    fn test_deserialize_actions(cx: &mut MutableAppContext) {
6452        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6453        pub struct ComplexAction {
6454            arg: String,
6455            count: usize,
6456        }
6457
6458        actions!(test::something, [SimpleAction]);
6459        impl_actions!(test::something, [ComplexAction]);
6460
6461        cx.add_global_action(move |_: &SimpleAction, _: &mut MutableAppContext| {});
6462        cx.add_global_action(move |_: &ComplexAction, _: &mut MutableAppContext| {});
6463
6464        let action1 = cx
6465            .deserialize_action(
6466                "test::something::ComplexAction",
6467                Some(r#"{"arg": "a", "count": 5}"#),
6468            )
6469            .unwrap();
6470        let action2 = cx
6471            .deserialize_action("test::something::SimpleAction", None)
6472            .unwrap();
6473        assert_eq!(
6474            action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
6475            &ComplexAction {
6476                arg: "a".to_string(),
6477                count: 5,
6478            }
6479        );
6480        assert_eq!(
6481            action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
6482            &SimpleAction
6483        );
6484    }
6485
6486    #[crate::test(self)]
6487    fn test_dispatch_action(cx: &mut MutableAppContext) {
6488        struct ViewA {
6489            id: usize,
6490        }
6491
6492        impl Entity for ViewA {
6493            type Event = ();
6494        }
6495
6496        impl View for ViewA {
6497            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6498                Empty::new().boxed()
6499            }
6500
6501            fn ui_name() -> &'static str {
6502                "View"
6503            }
6504        }
6505
6506        struct ViewB {
6507            id: usize,
6508        }
6509
6510        impl Entity for ViewB {
6511            type Event = ();
6512        }
6513
6514        impl View for ViewB {
6515            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6516                Empty::new().boxed()
6517            }
6518
6519            fn ui_name() -> &'static str {
6520                "View"
6521            }
6522        }
6523
6524        #[derive(Clone, Default, Deserialize, PartialEq)]
6525        pub struct Action(pub String);
6526
6527        impl_actions!(test, [Action]);
6528
6529        let actions = Rc::new(RefCell::new(Vec::new()));
6530
6531        cx.add_global_action({
6532            let actions = actions.clone();
6533            move |_: &Action, _: &mut MutableAppContext| {
6534                actions.borrow_mut().push("global".to_string());
6535            }
6536        });
6537
6538        cx.add_action({
6539            let actions = actions.clone();
6540            move |view: &mut ViewA, action: &Action, cx| {
6541                assert_eq!(action.0, "bar");
6542                cx.propagate_action();
6543                actions.borrow_mut().push(format!("{} a", view.id));
6544            }
6545        });
6546
6547        cx.add_action({
6548            let actions = actions.clone();
6549            move |view: &mut ViewA, _: &Action, cx| {
6550                if view.id != 1 {
6551                    cx.add_view(|cx| {
6552                        cx.propagate_action(); // Still works on a nested ViewContext
6553                        ViewB { id: 5 }
6554                    });
6555                }
6556                actions.borrow_mut().push(format!("{} b", view.id));
6557            }
6558        });
6559
6560        cx.add_action({
6561            let actions = actions.clone();
6562            move |view: &mut ViewB, _: &Action, cx| {
6563                cx.propagate_action();
6564                actions.borrow_mut().push(format!("{} c", view.id));
6565            }
6566        });
6567
6568        cx.add_action({
6569            let actions = actions.clone();
6570            move |view: &mut ViewB, _: &Action, cx| {
6571                cx.propagate_action();
6572                actions.borrow_mut().push(format!("{} d", view.id));
6573            }
6574        });
6575
6576        cx.capture_action({
6577            let actions = actions.clone();
6578            move |view: &mut ViewA, _: &Action, cx| {
6579                cx.propagate_action();
6580                actions.borrow_mut().push(format!("{} capture", view.id));
6581            }
6582        });
6583
6584        let observed_actions = Rc::new(RefCell::new(Vec::new()));
6585        cx.observe_actions({
6586            let observed_actions = observed_actions.clone();
6587            move |action_id, _| observed_actions.borrow_mut().push(action_id)
6588        })
6589        .detach();
6590
6591        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
6592        let view_2 = cx.add_view(&view_1, |_| ViewB { id: 2 });
6593        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
6594        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
6595
6596        cx.handle_dispatch_action_from_effect(
6597            window_id,
6598            Some(view_4.id()),
6599            &Action("bar".to_string()),
6600        );
6601
6602        assert_eq!(
6603            *actions.borrow(),
6604            vec![
6605                "1 capture",
6606                "3 capture",
6607                "4 d",
6608                "4 c",
6609                "3 b",
6610                "3 a",
6611                "2 d",
6612                "2 c",
6613                "1 b"
6614            ]
6615        );
6616        assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
6617
6618        // Remove view_1, which doesn't propagate the action
6619
6620        let (window_id, view_2) = cx.add_window(Default::default(), |_| ViewB { id: 2 });
6621        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
6622        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
6623
6624        actions.borrow_mut().clear();
6625        cx.handle_dispatch_action_from_effect(
6626            window_id,
6627            Some(view_4.id()),
6628            &Action("bar".to_string()),
6629        );
6630
6631        assert_eq!(
6632            *actions.borrow(),
6633            vec![
6634                "3 capture",
6635                "4 d",
6636                "4 c",
6637                "3 b",
6638                "3 a",
6639                "2 d",
6640                "2 c",
6641                "global"
6642            ]
6643        );
6644        assert_eq!(
6645            *observed_actions.borrow(),
6646            [Action::default().id(), Action::default().id()]
6647        );
6648    }
6649
6650    #[crate::test(self)]
6651    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
6652        #[derive(Clone, Deserialize, PartialEq)]
6653        pub struct Action(String);
6654
6655        impl_actions!(test, [Action]);
6656
6657        struct View {
6658            id: usize,
6659            keymap_context: keymap::Context,
6660        }
6661
6662        impl Entity for View {
6663            type Event = ();
6664        }
6665
6666        impl super::View for View {
6667            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6668                Empty::new().boxed()
6669            }
6670
6671            fn ui_name() -> &'static str {
6672                "View"
6673            }
6674
6675            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
6676                self.keymap_context.clone()
6677            }
6678        }
6679
6680        impl View {
6681            fn new(id: usize) -> Self {
6682                View {
6683                    id,
6684                    keymap_context: keymap::Context::default(),
6685                }
6686            }
6687        }
6688
6689        let mut view_1 = View::new(1);
6690        let mut view_2 = View::new(2);
6691        let mut view_3 = View::new(3);
6692        view_1.keymap_context.set.insert("a".into());
6693        view_2.keymap_context.set.insert("a".into());
6694        view_2.keymap_context.set.insert("b".into());
6695        view_3.keymap_context.set.insert("a".into());
6696        view_3.keymap_context.set.insert("b".into());
6697        view_3.keymap_context.set.insert("c".into());
6698
6699        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
6700        let view_2 = cx.add_view(&view_1, |_| view_2);
6701        let _view_3 = cx.add_view(&view_2, |cx| {
6702            cx.focus_self();
6703            view_3
6704        });
6705
6706        // This keymap's only binding dispatches an action on view 2 because that view will have
6707        // "a" and "b" in its context, but not "c".
6708        cx.add_bindings(vec![keymap::Binding::new(
6709            "a",
6710            Action("a".to_string()),
6711            Some("a && b && !c"),
6712        )]);
6713
6714        cx.add_bindings(vec![keymap::Binding::new(
6715            "b",
6716            Action("b".to_string()),
6717            None,
6718        )]);
6719
6720        let actions = Rc::new(RefCell::new(Vec::new()));
6721        cx.add_action({
6722            let actions = actions.clone();
6723            move |view: &mut View, action: &Action, cx| {
6724                if action.0 == "a" {
6725                    actions.borrow_mut().push(format!("{} a", view.id));
6726                } else {
6727                    actions
6728                        .borrow_mut()
6729                        .push(format!("{} {}", view.id, action.0));
6730                    cx.propagate_action();
6731                }
6732            }
6733        });
6734
6735        cx.add_global_action({
6736            let actions = actions.clone();
6737            move |action: &Action, _| {
6738                actions.borrow_mut().push(format!("global {}", action.0));
6739            }
6740        });
6741
6742        cx.dispatch_keystroke(window_id, &Keystroke::parse("a").unwrap());
6743
6744        assert_eq!(&*actions.borrow(), &["2 a"]);
6745
6746        actions.borrow_mut().clear();
6747
6748        cx.dispatch_keystroke(window_id, &Keystroke::parse("b").unwrap());
6749
6750        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
6751    }
6752
6753    #[crate::test(self)]
6754    async fn test_model_condition(cx: &mut TestAppContext) {
6755        struct Counter(usize);
6756
6757        impl super::Entity for Counter {
6758            type Event = ();
6759        }
6760
6761        impl Counter {
6762            fn inc(&mut self, cx: &mut ModelContext<Self>) {
6763                self.0 += 1;
6764                cx.notify();
6765            }
6766        }
6767
6768        let model = cx.add_model(|_| Counter(0));
6769
6770        let condition1 = model.condition(cx, |model, _| model.0 == 2);
6771        let condition2 = model.condition(cx, |model, _| model.0 == 3);
6772        smol::pin!(condition1, condition2);
6773
6774        model.update(cx, |model, cx| model.inc(cx));
6775        assert_eq!(poll_once(&mut condition1).await, None);
6776        assert_eq!(poll_once(&mut condition2).await, None);
6777
6778        model.update(cx, |model, cx| model.inc(cx));
6779        assert_eq!(poll_once(&mut condition1).await, Some(()));
6780        assert_eq!(poll_once(&mut condition2).await, None);
6781
6782        model.update(cx, |model, cx| model.inc(cx));
6783        assert_eq!(poll_once(&mut condition2).await, Some(()));
6784
6785        model.update(cx, |_, cx| cx.notify());
6786    }
6787
6788    #[crate::test(self)]
6789    #[should_panic]
6790    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
6791        struct Model;
6792
6793        impl super::Entity for Model {
6794            type Event = ();
6795        }
6796
6797        let model = cx.add_model(|_| Model);
6798        model.condition(cx, |_, _| false).await;
6799    }
6800
6801    #[crate::test(self)]
6802    #[should_panic(expected = "model dropped with pending condition")]
6803    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
6804        struct Model;
6805
6806        impl super::Entity for Model {
6807            type Event = ();
6808        }
6809
6810        let model = cx.add_model(|_| Model);
6811        let condition = model.condition(cx, |_, _| false);
6812        cx.update(|_| drop(model));
6813        condition.await;
6814    }
6815
6816    #[crate::test(self)]
6817    async fn test_view_condition(cx: &mut TestAppContext) {
6818        struct Counter(usize);
6819
6820        impl super::Entity for Counter {
6821            type Event = ();
6822        }
6823
6824        impl super::View for Counter {
6825            fn ui_name() -> &'static str {
6826                "test view"
6827            }
6828
6829            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6830                Empty::new().boxed()
6831            }
6832        }
6833
6834        impl Counter {
6835            fn inc(&mut self, cx: &mut ViewContext<Self>) {
6836                self.0 += 1;
6837                cx.notify();
6838            }
6839        }
6840
6841        let (_, view) = cx.add_window(|_| Counter(0));
6842
6843        let condition1 = view.condition(cx, |view, _| view.0 == 2);
6844        let condition2 = view.condition(cx, |view, _| view.0 == 3);
6845        smol::pin!(condition1, condition2);
6846
6847        view.update(cx, |view, cx| view.inc(cx));
6848        assert_eq!(poll_once(&mut condition1).await, None);
6849        assert_eq!(poll_once(&mut condition2).await, None);
6850
6851        view.update(cx, |view, cx| view.inc(cx));
6852        assert_eq!(poll_once(&mut condition1).await, Some(()));
6853        assert_eq!(poll_once(&mut condition2).await, None);
6854
6855        view.update(cx, |view, cx| view.inc(cx));
6856        assert_eq!(poll_once(&mut condition2).await, Some(()));
6857        view.update(cx, |_, cx| cx.notify());
6858    }
6859
6860    #[crate::test(self)]
6861    #[should_panic]
6862    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
6863        struct View;
6864
6865        impl super::Entity for View {
6866            type Event = ();
6867        }
6868
6869        impl super::View for View {
6870            fn ui_name() -> &'static str {
6871                "test view"
6872            }
6873
6874            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6875                Empty::new().boxed()
6876            }
6877        }
6878
6879        let (_, view) = cx.add_window(|_| View);
6880        view.condition(cx, |_, _| false).await;
6881    }
6882
6883    #[crate::test(self)]
6884    #[should_panic(expected = "view dropped with pending condition")]
6885    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
6886        struct View;
6887
6888        impl super::Entity for View {
6889            type Event = ();
6890        }
6891
6892        impl super::View for View {
6893            fn ui_name() -> &'static str {
6894                "test view"
6895            }
6896
6897            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6898                Empty::new().boxed()
6899            }
6900        }
6901
6902        let (_, root_view) = cx.add_window(|_| View);
6903        let view = cx.add_view(&root_view, |_| View);
6904
6905        let condition = view.condition(cx, |_, _| false);
6906        cx.update(|_| drop(view));
6907        condition.await;
6908    }
6909
6910    #[crate::test(self)]
6911    fn test_refresh_windows(cx: &mut MutableAppContext) {
6912        struct View(usize);
6913
6914        impl super::Entity for View {
6915            type Event = ();
6916        }
6917
6918        impl super::View for View {
6919            fn ui_name() -> &'static str {
6920                "test view"
6921            }
6922
6923            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6924                Empty::new().named(format!("render count: {}", post_inc(&mut self.0)))
6925            }
6926        }
6927
6928        let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
6929        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
6930
6931        assert_eq!(
6932            presenter.borrow().rendered_views[&root_view.id()].name(),
6933            Some("render count: 0")
6934        );
6935
6936        let view = cx.add_view(&root_view, |cx| {
6937            cx.refresh_windows();
6938            View(0)
6939        });
6940
6941        assert_eq!(
6942            presenter.borrow().rendered_views[&root_view.id()].name(),
6943            Some("render count: 1")
6944        );
6945        assert_eq!(
6946            presenter.borrow().rendered_views[&view.id()].name(),
6947            Some("render count: 0")
6948        );
6949
6950        cx.update(|cx| cx.refresh_windows());
6951        assert_eq!(
6952            presenter.borrow().rendered_views[&root_view.id()].name(),
6953            Some("render count: 2")
6954        );
6955        assert_eq!(
6956            presenter.borrow().rendered_views[&view.id()].name(),
6957            Some("render count: 1")
6958        );
6959
6960        cx.update(|cx| {
6961            cx.refresh_windows();
6962            drop(view);
6963        });
6964        assert_eq!(
6965            presenter.borrow().rendered_views[&root_view.id()].name(),
6966            Some("render count: 3")
6967        );
6968        assert_eq!(presenter.borrow().rendered_views.len(), 1);
6969    }
6970
6971    #[crate::test(self)]
6972    async fn test_window_activation(cx: &mut TestAppContext) {
6973        struct View(&'static str);
6974
6975        impl super::Entity for View {
6976            type Event = ();
6977        }
6978
6979        impl super::View for View {
6980            fn ui_name() -> &'static str {
6981                "test view"
6982            }
6983
6984            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6985                Empty::new().boxed()
6986            }
6987        }
6988
6989        let events = Rc::new(RefCell::new(Vec::new()));
6990        let (window_1, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6991            cx.observe_window_activation({
6992                let events = events.clone();
6993                move |this, active, _| events.borrow_mut().push((this.0, active))
6994            })
6995            .detach();
6996            View("window 1")
6997        });
6998        assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
6999
7000        let (window_2, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7001            cx.observe_window_activation({
7002                let events = events.clone();
7003                move |this, active, _| events.borrow_mut().push((this.0, active))
7004            })
7005            .detach();
7006            View("window 2")
7007        });
7008        assert_eq!(
7009            mem::take(&mut *events.borrow_mut()),
7010            [("window 1", false), ("window 2", true)]
7011        );
7012
7013        let (window_3, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7014            cx.observe_window_activation({
7015                let events = events.clone();
7016                move |this, active, _| events.borrow_mut().push((this.0, active))
7017            })
7018            .detach();
7019            View("window 3")
7020        });
7021        assert_eq!(
7022            mem::take(&mut *events.borrow_mut()),
7023            [("window 2", false), ("window 3", true)]
7024        );
7025
7026        cx.simulate_window_activation(Some(window_2));
7027        assert_eq!(
7028            mem::take(&mut *events.borrow_mut()),
7029            [("window 3", false), ("window 2", true)]
7030        );
7031
7032        cx.simulate_window_activation(Some(window_1));
7033        assert_eq!(
7034            mem::take(&mut *events.borrow_mut()),
7035            [("window 2", false), ("window 1", true)]
7036        );
7037
7038        cx.simulate_window_activation(Some(window_3));
7039        assert_eq!(
7040            mem::take(&mut *events.borrow_mut()),
7041            [("window 1", false), ("window 3", true)]
7042        );
7043
7044        cx.simulate_window_activation(Some(window_3));
7045        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
7046    }
7047
7048    #[crate::test(self)]
7049    fn test_child_view(cx: &mut MutableAppContext) {
7050        struct Child {
7051            rendered: Rc<Cell<bool>>,
7052            dropped: Rc<Cell<bool>>,
7053        }
7054
7055        impl super::Entity for Child {
7056            type Event = ();
7057        }
7058
7059        impl super::View for Child {
7060            fn ui_name() -> &'static str {
7061                "child view"
7062            }
7063
7064            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7065                self.rendered.set(true);
7066                Empty::new().boxed()
7067            }
7068        }
7069
7070        impl Drop for Child {
7071            fn drop(&mut self) {
7072                self.dropped.set(true);
7073            }
7074        }
7075
7076        struct Parent {
7077            child: Option<ViewHandle<Child>>,
7078        }
7079
7080        impl super::Entity for Parent {
7081            type Event = ();
7082        }
7083
7084        impl super::View for Parent {
7085            fn ui_name() -> &'static str {
7086                "parent view"
7087            }
7088
7089            fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
7090                if let Some(child) = self.child.as_ref() {
7091                    ChildView::new(child, cx).boxed()
7092                } else {
7093                    Empty::new().boxed()
7094                }
7095            }
7096        }
7097
7098        let child_rendered = Rc::new(Cell::new(false));
7099        let child_dropped = Rc::new(Cell::new(false));
7100        let (_, root_view) = cx.add_window(Default::default(), |cx| Parent {
7101            child: Some(cx.add_view(|_| Child {
7102                rendered: child_rendered.clone(),
7103                dropped: child_dropped.clone(),
7104            })),
7105        });
7106        assert!(child_rendered.take());
7107        assert!(!child_dropped.take());
7108
7109        root_view.update(cx, |view, cx| {
7110            view.child.take();
7111            cx.notify();
7112        });
7113        assert!(!child_rendered.take());
7114        assert!(child_dropped.take());
7115    }
7116}