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 background(&self) -> &Arc<executor::Background> {
2575        &self.background
2576    }
2577
2578    pub fn font_cache(&self) -> &Arc<FontCache> {
2579        &self.font_cache
2580    }
2581
2582    pub fn platform(&self) -> &Arc<dyn Platform> {
2583        &self.platform
2584    }
2585
2586    pub fn has_global<T: 'static>(&self) -> bool {
2587        self.globals.contains_key(&TypeId::of::<T>())
2588    }
2589
2590    pub fn global<T: 'static>(&self) -> &T {
2591        if let Some(global) = self.globals.get(&TypeId::of::<T>()) {
2592            global.downcast_ref().unwrap()
2593        } else {
2594            panic!("no global has been added for {}", type_name::<T>());
2595        }
2596    }
2597}
2598
2599impl ReadModel for AppContext {
2600    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2601        if let Some(model) = self.models.get(&handle.model_id) {
2602            model
2603                .as_any()
2604                .downcast_ref()
2605                .expect("downcast should be type safe")
2606        } else {
2607            panic!("circular model reference");
2608        }
2609    }
2610}
2611
2612impl UpgradeModelHandle for AppContext {
2613    fn upgrade_model_handle<T: Entity>(
2614        &self,
2615        handle: &WeakModelHandle<T>,
2616    ) -> Option<ModelHandle<T>> {
2617        if self.models.contains_key(&handle.model_id) {
2618            Some(ModelHandle::new(handle.model_id, &self.ref_counts))
2619        } else {
2620            None
2621        }
2622    }
2623
2624    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2625        self.models.contains_key(&handle.model_id)
2626    }
2627
2628    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2629        if self.models.contains_key(&handle.model_id) {
2630            Some(AnyModelHandle::new(
2631                handle.model_id,
2632                handle.model_type,
2633                self.ref_counts.clone(),
2634            ))
2635        } else {
2636            None
2637        }
2638    }
2639}
2640
2641impl UpgradeViewHandle for AppContext {
2642    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2643        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2644            Some(ViewHandle::new(
2645                handle.window_id,
2646                handle.view_id,
2647                &self.ref_counts,
2648            ))
2649        } else {
2650            None
2651        }
2652    }
2653
2654    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
2655        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2656            Some(AnyViewHandle::new(
2657                handle.window_id,
2658                handle.view_id,
2659                handle.view_type,
2660                self.ref_counts.clone(),
2661            ))
2662        } else {
2663            None
2664        }
2665    }
2666}
2667
2668impl ReadView for AppContext {
2669    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2670        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
2671            view.as_any()
2672                .downcast_ref()
2673                .expect("downcast should be type safe")
2674        } else {
2675            panic!("circular view reference");
2676        }
2677    }
2678}
2679
2680struct Window {
2681    root_view: AnyViewHandle,
2682    focused_view_id: Option<usize>,
2683    is_active: bool,
2684    is_fullscreen: bool,
2685    invalidation: Option<WindowInvalidation>,
2686}
2687
2688#[derive(Default, Clone)]
2689pub struct WindowInvalidation {
2690    pub updated: HashSet<usize>,
2691    pub removed: Vec<usize>,
2692}
2693
2694pub enum Effect {
2695    Subscription {
2696        entity_id: usize,
2697        subscription_id: usize,
2698        callback: SubscriptionCallback,
2699    },
2700    Event {
2701        entity_id: usize,
2702        payload: Box<dyn Any>,
2703    },
2704    GlobalSubscription {
2705        type_id: TypeId,
2706        subscription_id: usize,
2707        callback: GlobalSubscriptionCallback,
2708    },
2709    GlobalEvent {
2710        payload: Box<dyn Any>,
2711    },
2712    Observation {
2713        entity_id: usize,
2714        subscription_id: usize,
2715        callback: ObservationCallback,
2716    },
2717    ModelNotification {
2718        model_id: usize,
2719    },
2720    ViewNotification {
2721        window_id: usize,
2722        view_id: usize,
2723    },
2724    Deferred {
2725        callback: Box<dyn FnOnce(&mut MutableAppContext)>,
2726        after_window_update: bool,
2727    },
2728    GlobalNotification {
2729        type_id: TypeId,
2730    },
2731    ModelRelease {
2732        model_id: usize,
2733        model: Box<dyn AnyModel>,
2734    },
2735    ViewRelease {
2736        view_id: usize,
2737        view: Box<dyn AnyView>,
2738    },
2739    Focus {
2740        window_id: usize,
2741        view_id: Option<usize>,
2742    },
2743    FocusObservation {
2744        view_id: usize,
2745        subscription_id: usize,
2746        callback: FocusObservationCallback,
2747    },
2748    ResizeWindow {
2749        window_id: usize,
2750    },
2751    FullscreenWindow {
2752        window_id: usize,
2753        is_fullscreen: bool,
2754    },
2755    ActivateWindow {
2756        window_id: usize,
2757        is_active: bool,
2758    },
2759    WindowActivationObservation {
2760        window_id: usize,
2761        subscription_id: usize,
2762        callback: WindowActivationCallback,
2763    },
2764    WindowFullscreenObservation {
2765        window_id: usize,
2766        subscription_id: usize,
2767        callback: WindowFullscreenCallback,
2768    },
2769    RefreshWindows,
2770    DispatchActionFrom {
2771        window_id: usize,
2772        view_id: usize,
2773        action: Box<dyn Action>,
2774    },
2775    ActionDispatchNotification {
2776        action_id: TypeId,
2777    },
2778    WindowShouldCloseSubscription {
2779        window_id: usize,
2780        callback: WindowShouldCloseSubscriptionCallback,
2781    },
2782}
2783
2784impl Debug for Effect {
2785    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2786        match self {
2787            Effect::Subscription {
2788                entity_id,
2789                subscription_id,
2790                ..
2791            } => f
2792                .debug_struct("Effect::Subscribe")
2793                .field("entity_id", entity_id)
2794                .field("subscription_id", subscription_id)
2795                .finish(),
2796            Effect::Event { entity_id, .. } => f
2797                .debug_struct("Effect::Event")
2798                .field("entity_id", entity_id)
2799                .finish(),
2800            Effect::GlobalSubscription {
2801                type_id,
2802                subscription_id,
2803                ..
2804            } => f
2805                .debug_struct("Effect::Subscribe")
2806                .field("type_id", type_id)
2807                .field("subscription_id", subscription_id)
2808                .finish(),
2809            Effect::GlobalEvent { payload, .. } => f
2810                .debug_struct("Effect::GlobalEvent")
2811                .field("type_id", &(&*payload).type_id())
2812                .finish(),
2813            Effect::Observation {
2814                entity_id,
2815                subscription_id,
2816                ..
2817            } => f
2818                .debug_struct("Effect::Observation")
2819                .field("entity_id", entity_id)
2820                .field("subscription_id", subscription_id)
2821                .finish(),
2822            Effect::ModelNotification { model_id } => f
2823                .debug_struct("Effect::ModelNotification")
2824                .field("model_id", model_id)
2825                .finish(),
2826            Effect::ViewNotification { window_id, view_id } => f
2827                .debug_struct("Effect::ViewNotification")
2828                .field("window_id", window_id)
2829                .field("view_id", view_id)
2830                .finish(),
2831            Effect::GlobalNotification { type_id } => f
2832                .debug_struct("Effect::GlobalNotification")
2833                .field("type_id", type_id)
2834                .finish(),
2835            Effect::Deferred { .. } => f.debug_struct("Effect::Deferred").finish(),
2836            Effect::ModelRelease { model_id, .. } => f
2837                .debug_struct("Effect::ModelRelease")
2838                .field("model_id", model_id)
2839                .finish(),
2840            Effect::ViewRelease { view_id, .. } => f
2841                .debug_struct("Effect::ViewRelease")
2842                .field("view_id", view_id)
2843                .finish(),
2844            Effect::Focus { window_id, view_id } => f
2845                .debug_struct("Effect::Focus")
2846                .field("window_id", window_id)
2847                .field("view_id", view_id)
2848                .finish(),
2849            Effect::FocusObservation {
2850                view_id,
2851                subscription_id,
2852                ..
2853            } => f
2854                .debug_struct("Effect::FocusObservation")
2855                .field("view_id", view_id)
2856                .field("subscription_id", subscription_id)
2857                .finish(),
2858            Effect::DispatchActionFrom {
2859                window_id, view_id, ..
2860            } => f
2861                .debug_struct("Effect::DispatchActionFrom")
2862                .field("window_id", window_id)
2863                .field("view_id", view_id)
2864                .finish(),
2865            Effect::ActionDispatchNotification { action_id, .. } => f
2866                .debug_struct("Effect::ActionDispatchNotification")
2867                .field("action_id", action_id)
2868                .finish(),
2869            Effect::ResizeWindow { window_id } => f
2870                .debug_struct("Effect::RefreshWindow")
2871                .field("window_id", window_id)
2872                .finish(),
2873            Effect::WindowActivationObservation {
2874                window_id,
2875                subscription_id,
2876                ..
2877            } => f
2878                .debug_struct("Effect::WindowActivationObservation")
2879                .field("window_id", window_id)
2880                .field("subscription_id", subscription_id)
2881                .finish(),
2882            Effect::ActivateWindow {
2883                window_id,
2884                is_active,
2885            } => f
2886                .debug_struct("Effect::ActivateWindow")
2887                .field("window_id", window_id)
2888                .field("is_active", is_active)
2889                .finish(),
2890            Effect::FullscreenWindow {
2891                window_id,
2892                is_fullscreen,
2893            } => f
2894                .debug_struct("Effect::FullscreenWindow")
2895                .field("window_id", window_id)
2896                .field("is_fullscreen", is_fullscreen)
2897                .finish(),
2898            Effect::WindowFullscreenObservation {
2899                window_id,
2900                subscription_id,
2901                callback: _,
2902            } => f
2903                .debug_struct("Effect::WindowFullscreenObservation")
2904                .field("window_id", window_id)
2905                .field("subscription_id", subscription_id)
2906                .finish(),
2907            Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
2908            Effect::WindowShouldCloseSubscription { window_id, .. } => f
2909                .debug_struct("Effect::WindowShouldCloseSubscription")
2910                .field("window_id", window_id)
2911                .finish(),
2912        }
2913    }
2914}
2915
2916pub trait AnyModel {
2917    fn as_any(&self) -> &dyn Any;
2918    fn as_any_mut(&mut self) -> &mut dyn Any;
2919    fn release(&mut self, cx: &mut MutableAppContext);
2920    fn app_will_quit(
2921        &mut self,
2922        cx: &mut MutableAppContext,
2923    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2924}
2925
2926impl<T> AnyModel for T
2927where
2928    T: Entity,
2929{
2930    fn as_any(&self) -> &dyn Any {
2931        self
2932    }
2933
2934    fn as_any_mut(&mut self) -> &mut dyn Any {
2935        self
2936    }
2937
2938    fn release(&mut self, cx: &mut MutableAppContext) {
2939        self.release(cx);
2940    }
2941
2942    fn app_will_quit(
2943        &mut self,
2944        cx: &mut MutableAppContext,
2945    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2946        self.app_will_quit(cx)
2947    }
2948}
2949
2950pub trait AnyView {
2951    fn as_any(&self) -> &dyn Any;
2952    fn as_any_mut(&mut self) -> &mut dyn Any;
2953    fn release(&mut self, cx: &mut MutableAppContext);
2954    fn app_will_quit(
2955        &mut self,
2956        cx: &mut MutableAppContext,
2957    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2958    fn ui_name(&self) -> &'static str;
2959    fn render(&mut self, params: RenderParams, cx: &mut MutableAppContext) -> ElementBox;
2960    fn on_focus_in(
2961        &mut self,
2962        cx: &mut MutableAppContext,
2963        window_id: usize,
2964        view_id: usize,
2965        focused_id: usize,
2966    );
2967    fn on_focus_out(
2968        &mut self,
2969        cx: &mut MutableAppContext,
2970        window_id: usize,
2971        view_id: usize,
2972        focused_id: usize,
2973    );
2974    fn keymap_context(&self, cx: &AppContext) -> keymap::Context;
2975    fn debug_json(&self, cx: &AppContext) -> serde_json::Value;
2976
2977    fn text_for_range(&self, range: Range<usize>, cx: &AppContext) -> Option<String>;
2978    fn selected_text_range(&self, cx: &AppContext) -> Option<Range<usize>>;
2979    fn marked_text_range(&self, cx: &AppContext) -> Option<Range<usize>>;
2980    fn unmark_text(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
2981    fn replace_text_in_range(
2982        &mut self,
2983        range: Option<Range<usize>>,
2984        text: &str,
2985        cx: &mut MutableAppContext,
2986        window_id: usize,
2987        view_id: usize,
2988    );
2989    fn replace_and_mark_text_in_range(
2990        &mut self,
2991        range: Option<Range<usize>>,
2992        new_text: &str,
2993        new_selected_range: Option<Range<usize>>,
2994        cx: &mut MutableAppContext,
2995        window_id: usize,
2996        view_id: usize,
2997    );
2998    fn any_handle(&self, window_id: usize, view_id: usize, cx: &AppContext) -> AnyViewHandle {
2999        AnyViewHandle::new(
3000            window_id,
3001            view_id,
3002            self.as_any().type_id(),
3003            cx.ref_counts.clone(),
3004        )
3005    }
3006}
3007
3008impl<T> AnyView for T
3009where
3010    T: View,
3011{
3012    fn as_any(&self) -> &dyn Any {
3013        self
3014    }
3015
3016    fn as_any_mut(&mut self) -> &mut dyn Any {
3017        self
3018    }
3019
3020    fn release(&mut self, cx: &mut MutableAppContext) {
3021        self.release(cx);
3022    }
3023
3024    fn app_will_quit(
3025        &mut self,
3026        cx: &mut MutableAppContext,
3027    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
3028        self.app_will_quit(cx)
3029    }
3030
3031    fn ui_name(&self) -> &'static str {
3032        T::ui_name()
3033    }
3034
3035    fn render(&mut self, params: RenderParams, cx: &mut MutableAppContext) -> ElementBox {
3036        View::render(self, &mut RenderContext::new(params, cx))
3037    }
3038
3039    fn on_focus_in(
3040        &mut self,
3041        cx: &mut MutableAppContext,
3042        window_id: usize,
3043        view_id: usize,
3044        focused_id: usize,
3045    ) {
3046        let mut cx = ViewContext::new(cx, window_id, view_id);
3047        let focused_view_handle: AnyViewHandle = if view_id == focused_id {
3048            cx.handle().into()
3049        } else {
3050            let focused_type = cx
3051                .views
3052                .get(&(window_id, focused_id))
3053                .unwrap()
3054                .as_any()
3055                .type_id();
3056            AnyViewHandle::new(window_id, focused_id, focused_type, cx.ref_counts.clone())
3057        };
3058        View::on_focus_in(self, focused_view_handle, &mut cx);
3059    }
3060
3061    fn on_focus_out(
3062        &mut self,
3063        cx: &mut MutableAppContext,
3064        window_id: usize,
3065        view_id: usize,
3066        blurred_id: usize,
3067    ) {
3068        let mut cx = ViewContext::new(cx, window_id, view_id);
3069        let blurred_view_handle: AnyViewHandle = if view_id == blurred_id {
3070            cx.handle().into()
3071        } else {
3072            let blurred_type = cx
3073                .views
3074                .get(&(window_id, blurred_id))
3075                .unwrap()
3076                .as_any()
3077                .type_id();
3078            AnyViewHandle::new(window_id, blurred_id, blurred_type, cx.ref_counts.clone())
3079        };
3080        View::on_focus_out(self, blurred_view_handle, &mut cx);
3081    }
3082
3083    fn keymap_context(&self, cx: &AppContext) -> keymap::Context {
3084        View::keymap_context(self, cx)
3085    }
3086
3087    fn debug_json(&self, cx: &AppContext) -> serde_json::Value {
3088        View::debug_json(self, cx)
3089    }
3090
3091    fn text_for_range(&self, range: Range<usize>, cx: &AppContext) -> Option<String> {
3092        View::text_for_range(self, range, cx)
3093    }
3094
3095    fn selected_text_range(&self, cx: &AppContext) -> Option<Range<usize>> {
3096        View::selected_text_range(self, cx)
3097    }
3098
3099    fn marked_text_range(&self, cx: &AppContext) -> Option<Range<usize>> {
3100        View::marked_text_range(self, cx)
3101    }
3102
3103    fn unmark_text(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
3104        let mut cx = ViewContext::new(cx, window_id, view_id);
3105        View::unmark_text(self, &mut cx)
3106    }
3107
3108    fn replace_text_in_range(
3109        &mut self,
3110        range: Option<Range<usize>>,
3111        text: &str,
3112        cx: &mut MutableAppContext,
3113        window_id: usize,
3114        view_id: usize,
3115    ) {
3116        let mut cx = ViewContext::new(cx, window_id, view_id);
3117        View::replace_text_in_range(self, range, text, &mut cx)
3118    }
3119
3120    fn replace_and_mark_text_in_range(
3121        &mut self,
3122        range: Option<Range<usize>>,
3123        new_text: &str,
3124        new_selected_range: Option<Range<usize>>,
3125        cx: &mut MutableAppContext,
3126        window_id: usize,
3127        view_id: usize,
3128    ) {
3129        let mut cx = ViewContext::new(cx, window_id, view_id);
3130        View::replace_and_mark_text_in_range(self, range, new_text, new_selected_range, &mut cx)
3131    }
3132}
3133
3134pub struct ModelContext<'a, T: ?Sized> {
3135    app: &'a mut MutableAppContext,
3136    model_id: usize,
3137    model_type: PhantomData<T>,
3138    halt_stream: bool,
3139}
3140
3141impl<'a, T: Entity> ModelContext<'a, T> {
3142    fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
3143        Self {
3144            app,
3145            model_id,
3146            model_type: PhantomData,
3147            halt_stream: false,
3148        }
3149    }
3150
3151    pub fn background(&self) -> &Arc<executor::Background> {
3152        &self.app.cx.background
3153    }
3154
3155    pub fn halt_stream(&mut self) {
3156        self.halt_stream = true;
3157    }
3158
3159    pub fn model_id(&self) -> usize {
3160        self.model_id
3161    }
3162
3163    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
3164    where
3165        S: Entity,
3166        F: FnOnce(&mut ModelContext<S>) -> S,
3167    {
3168        self.app.add_model(build_model)
3169    }
3170
3171    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ModelContext<T>)) {
3172        let handle = self.handle();
3173        self.app.defer(move |cx| {
3174            handle.update(cx, |model, cx| {
3175                callback(model, cx);
3176            })
3177        })
3178    }
3179
3180    pub fn emit(&mut self, payload: T::Event) {
3181        self.app.pending_effects.push_back(Effect::Event {
3182            entity_id: self.model_id,
3183            payload: Box::new(payload),
3184        });
3185    }
3186
3187    pub fn notify(&mut self) {
3188        self.app.notify_model(self.model_id);
3189    }
3190
3191    pub fn subscribe<S: Entity, F>(
3192        &mut self,
3193        handle: &ModelHandle<S>,
3194        mut callback: F,
3195    ) -> Subscription
3196    where
3197        S::Event: 'static,
3198        F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
3199    {
3200        let subscriber = self.weak_handle();
3201        self.app
3202            .subscribe_internal(handle, move |emitter, event, cx| {
3203                if let Some(subscriber) = subscriber.upgrade(cx) {
3204                    subscriber.update(cx, |subscriber, cx| {
3205                        callback(subscriber, emitter, event, cx);
3206                    });
3207                    true
3208                } else {
3209                    false
3210                }
3211            })
3212    }
3213
3214    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
3215    where
3216        S: Entity,
3217        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
3218    {
3219        let observer = self.weak_handle();
3220        self.app.observe_internal(handle, move |observed, cx| {
3221            if let Some(observer) = observer.upgrade(cx) {
3222                observer.update(cx, |observer, cx| {
3223                    callback(observer, observed, cx);
3224                });
3225                true
3226            } else {
3227                false
3228            }
3229        })
3230    }
3231
3232    pub fn observe_global<G, F>(&mut self, mut callback: F) -> Subscription
3233    where
3234        G: Any,
3235        F: 'static + FnMut(&mut T, &mut ModelContext<T>),
3236    {
3237        let observer = self.weak_handle();
3238        self.app.observe_global::<G, _>(move |cx| {
3239            if let Some(observer) = observer.upgrade(cx) {
3240                observer.update(cx, |observer, cx| callback(observer, cx));
3241            }
3242        })
3243    }
3244
3245    pub fn observe_release<S, F>(
3246        &mut self,
3247        handle: &ModelHandle<S>,
3248        mut callback: F,
3249    ) -> Subscription
3250    where
3251        S: Entity,
3252        F: 'static + FnMut(&mut T, &S, &mut ModelContext<T>),
3253    {
3254        let observer = self.weak_handle();
3255        self.app.observe_release(handle, move |released, cx| {
3256            if let Some(observer) = observer.upgrade(cx) {
3257                observer.update(cx, |observer, cx| {
3258                    callback(observer, released, cx);
3259                });
3260            }
3261        })
3262    }
3263
3264    pub fn handle(&self) -> ModelHandle<T> {
3265        ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
3266    }
3267
3268    pub fn weak_handle(&self) -> WeakModelHandle<T> {
3269        WeakModelHandle::new(self.model_id)
3270    }
3271
3272    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
3273    where
3274        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
3275        Fut: 'static + Future<Output = S>,
3276        S: 'static,
3277    {
3278        let handle = self.handle();
3279        self.app.spawn(|cx| f(handle, cx))
3280    }
3281
3282    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
3283    where
3284        F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
3285        Fut: 'static + Future<Output = S>,
3286        S: 'static,
3287    {
3288        let handle = self.weak_handle();
3289        self.app.spawn(|cx| f(handle, cx))
3290    }
3291}
3292
3293impl<M> AsRef<AppContext> for ModelContext<'_, M> {
3294    fn as_ref(&self) -> &AppContext {
3295        &self.app.cx
3296    }
3297}
3298
3299impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
3300    fn as_mut(&mut self) -> &mut MutableAppContext {
3301        self.app
3302    }
3303}
3304
3305impl<M> ReadModel for ModelContext<'_, M> {
3306    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
3307        self.app.read_model(handle)
3308    }
3309}
3310
3311impl<M> UpdateModel for ModelContext<'_, M> {
3312    fn update_model<T: Entity, V>(
3313        &mut self,
3314        handle: &ModelHandle<T>,
3315        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
3316    ) -> V {
3317        self.app.update_model(handle, update)
3318    }
3319}
3320
3321impl<M> UpgradeModelHandle for ModelContext<'_, M> {
3322    fn upgrade_model_handle<T: Entity>(
3323        &self,
3324        handle: &WeakModelHandle<T>,
3325    ) -> Option<ModelHandle<T>> {
3326        self.cx.upgrade_model_handle(handle)
3327    }
3328
3329    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
3330        self.cx.model_handle_is_upgradable(handle)
3331    }
3332
3333    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
3334        self.cx.upgrade_any_model_handle(handle)
3335    }
3336}
3337
3338impl<M> Deref for ModelContext<'_, M> {
3339    type Target = MutableAppContext;
3340
3341    fn deref(&self) -> &Self::Target {
3342        self.app
3343    }
3344}
3345
3346impl<M> DerefMut for ModelContext<'_, M> {
3347    fn deref_mut(&mut self) -> &mut Self::Target {
3348        &mut self.app
3349    }
3350}
3351
3352pub struct ViewContext<'a, T: ?Sized> {
3353    app: &'a mut MutableAppContext,
3354    window_id: usize,
3355    view_id: usize,
3356    view_type: PhantomData<T>,
3357}
3358
3359impl<'a, T: View> ViewContext<'a, T> {
3360    fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
3361        Self {
3362            app,
3363            window_id,
3364            view_id,
3365            view_type: PhantomData,
3366        }
3367    }
3368
3369    pub fn handle(&self) -> ViewHandle<T> {
3370        ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
3371    }
3372
3373    pub fn weak_handle(&self) -> WeakViewHandle<T> {
3374        WeakViewHandle::new(self.window_id, self.view_id)
3375    }
3376
3377    pub fn window_id(&self) -> usize {
3378        self.window_id
3379    }
3380
3381    pub fn view_id(&self) -> usize {
3382        self.view_id
3383    }
3384
3385    pub fn foreground(&self) -> &Rc<executor::Foreground> {
3386        self.app.foreground()
3387    }
3388
3389    pub fn background_executor(&self) -> &Arc<executor::Background> {
3390        &self.app.cx.background
3391    }
3392
3393    pub fn platform(&self) -> Arc<dyn Platform> {
3394        self.app.platform()
3395    }
3396
3397    pub fn show_character_palette(&self) {
3398        self.app.show_character_palette(self.window_id);
3399    }
3400
3401    pub fn minimize_window(&self) {
3402        self.app.minimize_window(self.window_id)
3403    }
3404
3405    pub fn zoom_window(&self) {
3406        self.app.zoom_window(self.window_id)
3407    }
3408
3409    pub fn toggle_full_screen(&self) {
3410        self.app.toggle_window_full_screen(self.window_id)
3411    }
3412
3413    pub fn window_bounds(&self) -> RectF {
3414        self.app.window_bounds(self.window_id)
3415    }
3416
3417    pub fn prompt(
3418        &self,
3419        level: PromptLevel,
3420        msg: &str,
3421        answers: &[&str],
3422    ) -> oneshot::Receiver<usize> {
3423        self.app.prompt(self.window_id, level, msg, answers)
3424    }
3425
3426    pub fn prompt_for_paths(
3427        &self,
3428        options: PathPromptOptions,
3429    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
3430        self.app.prompt_for_paths(options)
3431    }
3432
3433    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
3434        self.app.prompt_for_new_path(directory)
3435    }
3436
3437    pub fn debug_elements(&self) -> crate::json::Value {
3438        self.app.debug_elements(self.window_id).unwrap()
3439    }
3440
3441    pub fn focus<S>(&mut self, handle: S)
3442    where
3443        S: Into<AnyViewHandle>,
3444    {
3445        let handle = handle.into();
3446        self.app.focus(handle.window_id, Some(handle.view_id));
3447    }
3448
3449    pub fn focus_self(&mut self) {
3450        self.app.focus(self.window_id, Some(self.view_id));
3451    }
3452
3453    pub fn is_self_focused(&self) -> bool {
3454        self.app.focused_view_id(self.window_id) == Some(self.view_id)
3455    }
3456
3457    pub fn is_child(&self, view: impl Into<AnyViewHandle>) -> bool {
3458        let view = view.into();
3459        if self.window_id != view.window_id {
3460            return false;
3461        }
3462        self.parents(view.window_id, view.view_id)
3463            .any(|parent| parent == self.view_id)
3464    }
3465
3466    pub fn blur(&mut self) {
3467        self.app.focus(self.window_id, None);
3468    }
3469
3470    pub fn set_window_title(&mut self, title: &str) {
3471        let window_id = self.window_id();
3472        if let Some((_, window)) = self.presenters_and_platform_windows.get_mut(&window_id) {
3473            window.set_title(title);
3474        }
3475    }
3476
3477    pub fn set_window_edited(&mut self, edited: bool) {
3478        let window_id = self.window_id();
3479        if let Some((_, window)) = self.presenters_and_platform_windows.get_mut(&window_id) {
3480            window.set_edited(edited);
3481        }
3482    }
3483
3484    pub fn on_window_should_close<F>(&mut self, mut callback: F)
3485    where
3486        F: 'static + FnMut(&mut T, &mut ViewContext<T>) -> bool,
3487    {
3488        let window_id = self.window_id();
3489        let view = self.weak_handle();
3490        self.pending_effects
3491            .push_back(Effect::WindowShouldCloseSubscription {
3492                window_id,
3493                callback: Box::new(move |cx| {
3494                    if let Some(view) = view.upgrade(cx) {
3495                        view.update(cx, |view, cx| callback(view, cx))
3496                    } else {
3497                        true
3498                    }
3499                }),
3500            });
3501    }
3502
3503    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
3504    where
3505        S: Entity,
3506        F: FnOnce(&mut ModelContext<S>) -> S,
3507    {
3508        self.app.add_model(build_model)
3509    }
3510
3511    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
3512    where
3513        S: View,
3514        F: FnOnce(&mut ViewContext<S>) -> S,
3515    {
3516        self.app
3517            .build_and_insert_view(self.window_id, ParentId::View(self.view_id), |cx| {
3518                Some(build_view(cx))
3519            })
3520            .unwrap()
3521    }
3522
3523    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
3524    where
3525        S: View,
3526        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
3527    {
3528        self.app
3529            .build_and_insert_view(self.window_id, ParentId::View(self.view_id), build_view)
3530    }
3531
3532    pub fn reparent(&mut self, view_handle: impl Into<AnyViewHandle>) {
3533        let view_handle = view_handle.into();
3534        if self.window_id != view_handle.window_id {
3535            panic!("Can't reparent view to a view from a different window");
3536        }
3537        self.cx
3538            .parents
3539            .remove(&(view_handle.window_id, view_handle.view_id));
3540        let new_parent_id = self.view_id;
3541        self.cx.parents.insert(
3542            (view_handle.window_id, view_handle.view_id),
3543            ParentId::View(new_parent_id),
3544        );
3545    }
3546
3547    pub fn replace_root_view<V, F>(&mut self, build_root_view: F) -> ViewHandle<V>
3548    where
3549        V: View,
3550        F: FnOnce(&mut ViewContext<V>) -> V,
3551    {
3552        let window_id = self.window_id;
3553        self.update(|this| {
3554            let root_view = this
3555                .build_and_insert_view(window_id, ParentId::Root, |cx| Some(build_root_view(cx)))
3556                .unwrap();
3557            let window = this.cx.windows.get_mut(&window_id).unwrap();
3558            window.root_view = root_view.clone().into();
3559            window.focused_view_id = Some(root_view.id());
3560            root_view
3561        })
3562    }
3563
3564    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
3565    where
3566        E: Entity,
3567        E::Event: 'static,
3568        H: Handle<E>,
3569        F: 'static + FnMut(&mut T, H, &E::Event, &mut ViewContext<T>),
3570    {
3571        let subscriber = self.weak_handle();
3572        self.app
3573            .subscribe_internal(handle, move |emitter, event, cx| {
3574                if let Some(subscriber) = subscriber.upgrade(cx) {
3575                    subscriber.update(cx, |subscriber, cx| {
3576                        callback(subscriber, emitter, event, cx);
3577                    });
3578                    true
3579                } else {
3580                    false
3581                }
3582            })
3583    }
3584
3585    pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3586    where
3587        E: Entity,
3588        H: Handle<E>,
3589        F: 'static + FnMut(&mut T, H, &mut ViewContext<T>),
3590    {
3591        let observer = self.weak_handle();
3592        self.app.observe_internal(handle, move |observed, cx| {
3593            if let Some(observer) = observer.upgrade(cx) {
3594                observer.update(cx, |observer, cx| {
3595                    callback(observer, observed, cx);
3596                });
3597                true
3598            } else {
3599                false
3600            }
3601        })
3602    }
3603
3604    pub fn observe_focus<F, V>(&mut self, handle: &ViewHandle<V>, mut callback: F) -> Subscription
3605    where
3606        F: 'static + FnMut(&mut T, ViewHandle<V>, bool, &mut ViewContext<T>),
3607        V: View,
3608    {
3609        let observer = self.weak_handle();
3610        self.app
3611            .observe_focus(handle, move |observed, focused, cx| {
3612                if let Some(observer) = observer.upgrade(cx) {
3613                    observer.update(cx, |observer, cx| {
3614                        callback(observer, observed, focused, cx);
3615                    });
3616                    true
3617                } else {
3618                    false
3619                }
3620            })
3621    }
3622
3623    pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3624    where
3625        E: Entity,
3626        H: Handle<E>,
3627        F: 'static + FnMut(&mut T, &E, &mut ViewContext<T>),
3628    {
3629        let observer = self.weak_handle();
3630        self.app.observe_release(handle, move |released, cx| {
3631            if let Some(observer) = observer.upgrade(cx) {
3632                observer.update(cx, |observer, cx| {
3633                    callback(observer, released, cx);
3634                });
3635            }
3636        })
3637    }
3638
3639    pub fn observe_actions<F>(&mut self, mut callback: F) -> Subscription
3640    where
3641        F: 'static + FnMut(&mut T, TypeId, &mut ViewContext<T>),
3642    {
3643        let observer = self.weak_handle();
3644        self.app.observe_actions(move |action_id, cx| {
3645            if let Some(observer) = observer.upgrade(cx) {
3646                observer.update(cx, |observer, cx| {
3647                    callback(observer, action_id, cx);
3648                });
3649            }
3650        })
3651    }
3652
3653    pub fn observe_window_activation<F>(&mut self, mut callback: F) -> Subscription
3654    where
3655        F: 'static + FnMut(&mut T, bool, &mut ViewContext<T>),
3656    {
3657        let observer = self.weak_handle();
3658        self.app
3659            .observe_window_activation(self.window_id(), move |active, cx| {
3660                if let Some(observer) = observer.upgrade(cx) {
3661                    observer.update(cx, |observer, cx| {
3662                        callback(observer, active, cx);
3663                    });
3664                    true
3665                } else {
3666                    false
3667                }
3668            })
3669    }
3670
3671    pub fn observe_fullscreen<F>(&mut self, mut callback: F) -> Subscription
3672    where
3673        F: 'static + FnMut(&mut T, bool, &mut ViewContext<T>),
3674    {
3675        let observer = self.weak_handle();
3676        self.app
3677            .observe_fullscreen(self.window_id(), move |active, cx| {
3678                if let Some(observer) = observer.upgrade(cx) {
3679                    observer.update(cx, |observer, cx| {
3680                        callback(observer, active, cx);
3681                    });
3682                    true
3683                } else {
3684                    false
3685                }
3686            })
3687    }
3688
3689    pub fn emit(&mut self, payload: T::Event) {
3690        self.app.pending_effects.push_back(Effect::Event {
3691            entity_id: self.view_id,
3692            payload: Box::new(payload),
3693        });
3694    }
3695
3696    pub fn notify(&mut self) {
3697        self.app.notify_view(self.window_id, self.view_id);
3698    }
3699
3700    pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
3701        self.app
3702            .dispatch_any_action_at(self.window_id, self.view_id, action)
3703    }
3704
3705    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>)) {
3706        let handle = self.handle();
3707        self.app.defer(move |cx| {
3708            handle.update(cx, |view, cx| {
3709                callback(view, cx);
3710            })
3711        })
3712    }
3713
3714    pub fn after_window_update(
3715        &mut self,
3716        callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>),
3717    ) {
3718        let handle = self.handle();
3719        self.app.after_window_update(move |cx| {
3720            handle.update(cx, |view, cx| {
3721                callback(view, cx);
3722            })
3723        })
3724    }
3725
3726    pub fn propagate_action(&mut self) {
3727        self.app.halt_action_dispatch = false;
3728    }
3729
3730    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
3731    where
3732        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
3733        Fut: 'static + Future<Output = S>,
3734        S: 'static,
3735    {
3736        let handle = self.handle();
3737        self.app.spawn(|cx| f(handle, cx))
3738    }
3739
3740    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
3741    where
3742        F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut,
3743        Fut: 'static + Future<Output = S>,
3744        S: 'static,
3745    {
3746        let handle = self.weak_handle();
3747        self.app.spawn(|cx| f(handle, cx))
3748    }
3749}
3750
3751pub struct RenderParams {
3752    pub window_id: usize,
3753    pub view_id: usize,
3754    pub titlebar_height: f32,
3755    pub hovered_region_ids: HashSet<MouseRegionId>,
3756    pub clicked_region_ids: Option<(HashSet<MouseRegionId>, MouseButton)>,
3757    pub refreshing: bool,
3758    pub appearance: Appearance,
3759}
3760
3761pub struct RenderContext<'a, T: View> {
3762    pub(crate) window_id: usize,
3763    pub(crate) view_id: usize,
3764    pub(crate) view_type: PhantomData<T>,
3765    pub(crate) hovered_region_ids: HashSet<MouseRegionId>,
3766    pub(crate) clicked_region_ids: Option<(HashSet<MouseRegionId>, MouseButton)>,
3767    pub app: &'a mut MutableAppContext,
3768    pub titlebar_height: f32,
3769    pub appearance: Appearance,
3770    pub refreshing: bool,
3771}
3772
3773#[derive(Clone, Copy, Default)]
3774pub struct MouseState {
3775    pub hovered: bool,
3776    pub clicked: Option<MouseButton>,
3777}
3778
3779impl<'a, V: View> RenderContext<'a, V> {
3780    fn new(params: RenderParams, app: &'a mut MutableAppContext) -> Self {
3781        Self {
3782            app,
3783            window_id: params.window_id,
3784            view_id: params.view_id,
3785            view_type: PhantomData,
3786            titlebar_height: params.titlebar_height,
3787            hovered_region_ids: params.hovered_region_ids.clone(),
3788            clicked_region_ids: params.clicked_region_ids.clone(),
3789            refreshing: params.refreshing,
3790            appearance: params.appearance,
3791        }
3792    }
3793
3794    pub fn handle(&self) -> WeakViewHandle<V> {
3795        WeakViewHandle::new(self.window_id, self.view_id)
3796    }
3797
3798    pub fn window_id(&self) -> usize {
3799        self.window_id
3800    }
3801
3802    pub fn view_id(&self) -> usize {
3803        self.view_id
3804    }
3805
3806    pub fn mouse_state<Tag: 'static>(&self, region_id: usize) -> MouseState {
3807        let region_id = MouseRegionId::new::<Tag>(self.view_id, region_id);
3808        MouseState {
3809            hovered: self.hovered_region_ids.contains(&region_id),
3810            clicked: self.clicked_region_ids.as_ref().and_then(|(ids, button)| {
3811                if ids.contains(&region_id) {
3812                    Some(*button)
3813                } else {
3814                    None
3815                }
3816            }),
3817        }
3818    }
3819
3820    pub fn element_state<Tag: 'static, T: 'static>(
3821        &mut self,
3822        element_id: usize,
3823        initial: T,
3824    ) -> ElementStateHandle<T> {
3825        let id = ElementStateId {
3826            view_id: self.view_id(),
3827            element_id,
3828            tag: TypeId::of::<Tag>(),
3829        };
3830        self.cx
3831            .element_states
3832            .entry(id)
3833            .or_insert_with(|| Box::new(initial));
3834        ElementStateHandle::new(id, self.frame_count, &self.cx.ref_counts)
3835    }
3836
3837    pub fn default_element_state<Tag: 'static, T: 'static + Default>(
3838        &mut self,
3839        element_id: usize,
3840    ) -> ElementStateHandle<T> {
3841        self.element_state::<Tag, T>(element_id, T::default())
3842    }
3843}
3844
3845impl AsRef<AppContext> for &AppContext {
3846    fn as_ref(&self) -> &AppContext {
3847        self
3848    }
3849}
3850
3851impl<V: View> Deref for RenderContext<'_, V> {
3852    type Target = MutableAppContext;
3853
3854    fn deref(&self) -> &Self::Target {
3855        self.app
3856    }
3857}
3858
3859impl<V: View> DerefMut for RenderContext<'_, V> {
3860    fn deref_mut(&mut self) -> &mut Self::Target {
3861        self.app
3862    }
3863}
3864
3865impl<V: View> ReadModel for RenderContext<'_, V> {
3866    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
3867        self.app.read_model(handle)
3868    }
3869}
3870
3871impl<V: View> UpdateModel for RenderContext<'_, V> {
3872    fn update_model<T: Entity, O>(
3873        &mut self,
3874        handle: &ModelHandle<T>,
3875        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
3876    ) -> O {
3877        self.app.update_model(handle, update)
3878    }
3879}
3880
3881impl<V: View> ReadView for RenderContext<'_, V> {
3882    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
3883        self.app.read_view(handle)
3884    }
3885}
3886
3887impl<M> AsRef<AppContext> for ViewContext<'_, M> {
3888    fn as_ref(&self) -> &AppContext {
3889        &self.app.cx
3890    }
3891}
3892
3893impl<M> Deref for ViewContext<'_, M> {
3894    type Target = MutableAppContext;
3895
3896    fn deref(&self) -> &Self::Target {
3897        self.app
3898    }
3899}
3900
3901impl<M> DerefMut for ViewContext<'_, M> {
3902    fn deref_mut(&mut self) -> &mut Self::Target {
3903        &mut self.app
3904    }
3905}
3906
3907impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
3908    fn as_mut(&mut self) -> &mut MutableAppContext {
3909        self.app
3910    }
3911}
3912
3913impl<V> ReadModel for ViewContext<'_, V> {
3914    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
3915        self.app.read_model(handle)
3916    }
3917}
3918
3919impl<V> UpgradeModelHandle for ViewContext<'_, V> {
3920    fn upgrade_model_handle<T: Entity>(
3921        &self,
3922        handle: &WeakModelHandle<T>,
3923    ) -> Option<ModelHandle<T>> {
3924        self.cx.upgrade_model_handle(handle)
3925    }
3926
3927    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
3928        self.cx.model_handle_is_upgradable(handle)
3929    }
3930
3931    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
3932        self.cx.upgrade_any_model_handle(handle)
3933    }
3934}
3935
3936impl<V> UpgradeViewHandle for ViewContext<'_, V> {
3937    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
3938        self.cx.upgrade_view_handle(handle)
3939    }
3940
3941    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
3942        self.cx.upgrade_any_view_handle(handle)
3943    }
3944}
3945
3946impl<V: View> UpgradeViewHandle for RenderContext<'_, V> {
3947    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
3948        self.cx.upgrade_view_handle(handle)
3949    }
3950
3951    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
3952        self.cx.upgrade_any_view_handle(handle)
3953    }
3954}
3955
3956impl<V: View> UpdateModel for ViewContext<'_, V> {
3957    fn update_model<T: Entity, O>(
3958        &mut self,
3959        handle: &ModelHandle<T>,
3960        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
3961    ) -> O {
3962        self.app.update_model(handle, update)
3963    }
3964}
3965
3966impl<V: View> ReadView for ViewContext<'_, V> {
3967    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
3968        self.app.read_view(handle)
3969    }
3970}
3971
3972impl<V: View> UpdateView for ViewContext<'_, V> {
3973    fn update_view<T, S>(
3974        &mut self,
3975        handle: &ViewHandle<T>,
3976        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
3977    ) -> S
3978    where
3979        T: View,
3980    {
3981        self.app.update_view(handle, update)
3982    }
3983}
3984
3985pub trait Handle<T> {
3986    type Weak: 'static;
3987    fn id(&self) -> usize;
3988    fn location(&self) -> EntityLocation;
3989    fn downgrade(&self) -> Self::Weak;
3990    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3991    where
3992        Self: Sized;
3993}
3994
3995pub trait WeakHandle {
3996    fn id(&self) -> usize;
3997}
3998
3999#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
4000pub enum EntityLocation {
4001    Model(usize),
4002    View(usize, usize),
4003}
4004
4005pub struct ModelHandle<T: Entity> {
4006    model_id: usize,
4007    model_type: PhantomData<T>,
4008    ref_counts: Arc<Mutex<RefCounts>>,
4009
4010    #[cfg(any(test, feature = "test-support"))]
4011    handle_id: usize,
4012}
4013
4014impl<T: Entity> ModelHandle<T> {
4015    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4016        ref_counts.lock().inc_model(model_id);
4017
4018        #[cfg(any(test, feature = "test-support"))]
4019        let handle_id = ref_counts
4020            .lock()
4021            .leak_detector
4022            .lock()
4023            .handle_created(Some(type_name::<T>()), model_id);
4024
4025        Self {
4026            model_id,
4027            model_type: PhantomData,
4028            ref_counts: ref_counts.clone(),
4029
4030            #[cfg(any(test, feature = "test-support"))]
4031            handle_id,
4032        }
4033    }
4034
4035    pub fn downgrade(&self) -> WeakModelHandle<T> {
4036        WeakModelHandle::new(self.model_id)
4037    }
4038
4039    pub fn id(&self) -> usize {
4040        self.model_id
4041    }
4042
4043    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
4044        cx.read_model(self)
4045    }
4046
4047    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
4048    where
4049        C: ReadModelWith,
4050        F: FnOnce(&T, &AppContext) -> S,
4051    {
4052        let mut read = Some(read);
4053        cx.read_model_with(self, &mut |model, cx| {
4054            let read = read.take().unwrap();
4055            read(model, cx)
4056        })
4057    }
4058
4059    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
4060    where
4061        C: UpdateModel,
4062        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
4063    {
4064        let mut update = Some(update);
4065        cx.update_model(self, &mut |model, cx| {
4066            let update = update.take().unwrap();
4067            update(model, cx)
4068        })
4069    }
4070}
4071
4072impl<T: Entity> Clone for ModelHandle<T> {
4073    fn clone(&self) -> Self {
4074        Self::new(self.model_id, &self.ref_counts)
4075    }
4076}
4077
4078impl<T: Entity> PartialEq for ModelHandle<T> {
4079    fn eq(&self, other: &Self) -> bool {
4080        self.model_id == other.model_id
4081    }
4082}
4083
4084impl<T: Entity> Eq for ModelHandle<T> {}
4085
4086impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
4087    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
4088        self.model_id == other.model_id
4089    }
4090}
4091
4092impl<T: Entity> Hash for ModelHandle<T> {
4093    fn hash<H: Hasher>(&self, state: &mut H) {
4094        self.model_id.hash(state);
4095    }
4096}
4097
4098impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
4099    fn borrow(&self) -> &usize {
4100        &self.model_id
4101    }
4102}
4103
4104impl<T: Entity> Debug for ModelHandle<T> {
4105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4106        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
4107            .field(&self.model_id)
4108            .finish()
4109    }
4110}
4111
4112unsafe impl<T: Entity> Send for ModelHandle<T> {}
4113unsafe impl<T: Entity> Sync for ModelHandle<T> {}
4114
4115impl<T: Entity> Drop for ModelHandle<T> {
4116    fn drop(&mut self) {
4117        let mut ref_counts = self.ref_counts.lock();
4118        ref_counts.dec_model(self.model_id);
4119
4120        #[cfg(any(test, feature = "test-support"))]
4121        ref_counts
4122            .leak_detector
4123            .lock()
4124            .handle_dropped(self.model_id, self.handle_id);
4125    }
4126}
4127
4128impl<T: Entity> Handle<T> for ModelHandle<T> {
4129    type Weak = WeakModelHandle<T>;
4130
4131    fn id(&self) -> usize {
4132        self.model_id
4133    }
4134
4135    fn location(&self) -> EntityLocation {
4136        EntityLocation::Model(self.model_id)
4137    }
4138
4139    fn downgrade(&self) -> Self::Weak {
4140        self.downgrade()
4141    }
4142
4143    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4144    where
4145        Self: Sized,
4146    {
4147        weak.upgrade(cx)
4148    }
4149}
4150
4151pub struct WeakModelHandle<T> {
4152    model_id: usize,
4153    model_type: PhantomData<T>,
4154}
4155
4156impl<T> WeakHandle for WeakModelHandle<T> {
4157    fn id(&self) -> usize {
4158        self.model_id
4159    }
4160}
4161
4162unsafe impl<T> Send for WeakModelHandle<T> {}
4163unsafe impl<T> Sync for WeakModelHandle<T> {}
4164
4165impl<T: Entity> WeakModelHandle<T> {
4166    fn new(model_id: usize) -> Self {
4167        Self {
4168            model_id,
4169            model_type: PhantomData,
4170        }
4171    }
4172
4173    pub fn id(&self) -> usize {
4174        self.model_id
4175    }
4176
4177    pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
4178        cx.model_handle_is_upgradable(self)
4179    }
4180
4181    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
4182        cx.upgrade_model_handle(self)
4183    }
4184}
4185
4186impl<T> Hash for WeakModelHandle<T> {
4187    fn hash<H: Hasher>(&self, state: &mut H) {
4188        self.model_id.hash(state)
4189    }
4190}
4191
4192impl<T> PartialEq for WeakModelHandle<T> {
4193    fn eq(&self, other: &Self) -> bool {
4194        self.model_id == other.model_id
4195    }
4196}
4197
4198impl<T> Eq for WeakModelHandle<T> {}
4199
4200impl<T: Entity> PartialEq<ModelHandle<T>> for WeakModelHandle<T> {
4201    fn eq(&self, other: &ModelHandle<T>) -> bool {
4202        self.model_id == other.model_id
4203    }
4204}
4205
4206impl<T> Clone for WeakModelHandle<T> {
4207    fn clone(&self) -> Self {
4208        Self {
4209            model_id: self.model_id,
4210            model_type: PhantomData,
4211        }
4212    }
4213}
4214
4215impl<T> Copy for WeakModelHandle<T> {}
4216
4217pub struct ViewHandle<T> {
4218    window_id: usize,
4219    view_id: usize,
4220    view_type: PhantomData<T>,
4221    ref_counts: Arc<Mutex<RefCounts>>,
4222    #[cfg(any(test, feature = "test-support"))]
4223    handle_id: usize,
4224}
4225
4226impl<T: View> ViewHandle<T> {
4227    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4228        ref_counts.lock().inc_view(window_id, view_id);
4229        #[cfg(any(test, feature = "test-support"))]
4230        let handle_id = ref_counts
4231            .lock()
4232            .leak_detector
4233            .lock()
4234            .handle_created(Some(type_name::<T>()), view_id);
4235
4236        Self {
4237            window_id,
4238            view_id,
4239            view_type: PhantomData,
4240            ref_counts: ref_counts.clone(),
4241
4242            #[cfg(any(test, feature = "test-support"))]
4243            handle_id,
4244        }
4245    }
4246
4247    pub fn downgrade(&self) -> WeakViewHandle<T> {
4248        WeakViewHandle::new(self.window_id, self.view_id)
4249    }
4250
4251    pub fn window_id(&self) -> usize {
4252        self.window_id
4253    }
4254
4255    pub fn id(&self) -> usize {
4256        self.view_id
4257    }
4258
4259    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
4260        cx.read_view(self)
4261    }
4262
4263    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
4264    where
4265        C: ReadViewWith,
4266        F: FnOnce(&T, &AppContext) -> S,
4267    {
4268        let mut read = Some(read);
4269        cx.read_view_with(self, &mut |view, cx| {
4270            let read = read.take().unwrap();
4271            read(view, cx)
4272        })
4273    }
4274
4275    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
4276    where
4277        C: UpdateView,
4278        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
4279    {
4280        let mut update = Some(update);
4281        cx.update_view(self, &mut |view, cx| {
4282            let update = update.take().unwrap();
4283            update(view, cx)
4284        })
4285    }
4286
4287    pub fn defer<C, F>(&self, cx: &mut C, update: F)
4288    where
4289        C: AsMut<MutableAppContext>,
4290        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
4291    {
4292        let this = self.clone();
4293        cx.as_mut().defer(move |cx| {
4294            this.update(cx, |view, cx| update(view, cx));
4295        });
4296    }
4297
4298    pub fn is_focused(&self, cx: &AppContext) -> bool {
4299        cx.focused_view_id(self.window_id)
4300            .map_or(false, |focused_id| focused_id == self.view_id)
4301    }
4302}
4303
4304impl<T: View> Clone for ViewHandle<T> {
4305    fn clone(&self) -> Self {
4306        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
4307    }
4308}
4309
4310impl<T> PartialEq for ViewHandle<T> {
4311    fn eq(&self, other: &Self) -> bool {
4312        self.window_id == other.window_id && self.view_id == other.view_id
4313    }
4314}
4315
4316impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
4317    fn eq(&self, other: &WeakViewHandle<T>) -> bool {
4318        self.window_id == other.window_id && self.view_id == other.view_id
4319    }
4320}
4321
4322impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
4323    fn eq(&self, other: &ViewHandle<T>) -> bool {
4324        self.window_id == other.window_id && self.view_id == other.view_id
4325    }
4326}
4327
4328impl<T> Eq for ViewHandle<T> {}
4329
4330impl<T> Hash for ViewHandle<T> {
4331    fn hash<H: Hasher>(&self, state: &mut H) {
4332        self.window_id.hash(state);
4333        self.view_id.hash(state);
4334    }
4335}
4336
4337impl<T> Debug for ViewHandle<T> {
4338    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4339        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
4340            .field("window_id", &self.window_id)
4341            .field("view_id", &self.view_id)
4342            .finish()
4343    }
4344}
4345
4346impl<T> Drop for ViewHandle<T> {
4347    fn drop(&mut self) {
4348        self.ref_counts
4349            .lock()
4350            .dec_view(self.window_id, self.view_id);
4351        #[cfg(any(test, feature = "test-support"))]
4352        self.ref_counts
4353            .lock()
4354            .leak_detector
4355            .lock()
4356            .handle_dropped(self.view_id, self.handle_id);
4357    }
4358}
4359
4360impl<T: View> Handle<T> for ViewHandle<T> {
4361    type Weak = WeakViewHandle<T>;
4362
4363    fn id(&self) -> usize {
4364        self.view_id
4365    }
4366
4367    fn location(&self) -> EntityLocation {
4368        EntityLocation::View(self.window_id, self.view_id)
4369    }
4370
4371    fn downgrade(&self) -> Self::Weak {
4372        self.downgrade()
4373    }
4374
4375    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4376    where
4377        Self: Sized,
4378    {
4379        weak.upgrade(cx)
4380    }
4381}
4382
4383pub struct AnyViewHandle {
4384    window_id: usize,
4385    view_id: usize,
4386    view_type: TypeId,
4387    ref_counts: Arc<Mutex<RefCounts>>,
4388
4389    #[cfg(any(test, feature = "test-support"))]
4390    handle_id: usize,
4391}
4392
4393impl AnyViewHandle {
4394    fn new(
4395        window_id: usize,
4396        view_id: usize,
4397        view_type: TypeId,
4398        ref_counts: Arc<Mutex<RefCounts>>,
4399    ) -> Self {
4400        ref_counts.lock().inc_view(window_id, view_id);
4401
4402        #[cfg(any(test, feature = "test-support"))]
4403        let handle_id = ref_counts
4404            .lock()
4405            .leak_detector
4406            .lock()
4407            .handle_created(None, view_id);
4408
4409        Self {
4410            window_id,
4411            view_id,
4412            view_type,
4413            ref_counts,
4414            #[cfg(any(test, feature = "test-support"))]
4415            handle_id,
4416        }
4417    }
4418
4419    pub fn id(&self) -> usize {
4420        self.view_id
4421    }
4422
4423    pub fn is<T: 'static>(&self) -> bool {
4424        TypeId::of::<T>() == self.view_type
4425    }
4426
4427    pub fn is_focused(&self, cx: &AppContext) -> bool {
4428        cx.focused_view_id(self.window_id)
4429            .map_or(false, |focused_id| focused_id == self.view_id)
4430    }
4431
4432    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
4433        if self.is::<T>() {
4434            let result = Some(ViewHandle {
4435                window_id: self.window_id,
4436                view_id: self.view_id,
4437                ref_counts: self.ref_counts.clone(),
4438                view_type: PhantomData,
4439                #[cfg(any(test, feature = "test-support"))]
4440                handle_id: self.handle_id,
4441            });
4442            unsafe {
4443                Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
4444            }
4445            std::mem::forget(self);
4446            result
4447        } else {
4448            None
4449        }
4450    }
4451
4452    pub fn downgrade(&self) -> AnyWeakViewHandle {
4453        AnyWeakViewHandle {
4454            window_id: self.window_id,
4455            view_id: self.view_id,
4456            view_type: self.view_type,
4457        }
4458    }
4459
4460    pub fn view_type(&self) -> TypeId {
4461        self.view_type
4462    }
4463
4464    pub fn debug_json(&self, cx: &AppContext) -> serde_json::Value {
4465        cx.views
4466            .get(&(self.window_id, self.view_id))
4467            .map_or_else(|| serde_json::Value::Null, |view| view.debug_json(cx))
4468    }
4469}
4470
4471impl Clone for AnyViewHandle {
4472    fn clone(&self) -> Self {
4473        Self::new(
4474            self.window_id,
4475            self.view_id,
4476            self.view_type,
4477            self.ref_counts.clone(),
4478        )
4479    }
4480}
4481
4482impl From<&AnyViewHandle> for AnyViewHandle {
4483    fn from(handle: &AnyViewHandle) -> Self {
4484        handle.clone()
4485    }
4486}
4487
4488impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
4489    fn from(handle: &ViewHandle<T>) -> Self {
4490        Self::new(
4491            handle.window_id,
4492            handle.view_id,
4493            TypeId::of::<T>(),
4494            handle.ref_counts.clone(),
4495        )
4496    }
4497}
4498
4499impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
4500    fn from(handle: ViewHandle<T>) -> Self {
4501        let any_handle = AnyViewHandle {
4502            window_id: handle.window_id,
4503            view_id: handle.view_id,
4504            view_type: TypeId::of::<T>(),
4505            ref_counts: handle.ref_counts.clone(),
4506            #[cfg(any(test, feature = "test-support"))]
4507            handle_id: handle.handle_id,
4508        };
4509
4510        unsafe {
4511            Arc::decrement_strong_count(Arc::as_ptr(&handle.ref_counts));
4512        }
4513        std::mem::forget(handle);
4514        any_handle
4515    }
4516}
4517
4518impl Drop for AnyViewHandle {
4519    fn drop(&mut self) {
4520        self.ref_counts
4521            .lock()
4522            .dec_view(self.window_id, self.view_id);
4523        #[cfg(any(test, feature = "test-support"))]
4524        self.ref_counts
4525            .lock()
4526            .leak_detector
4527            .lock()
4528            .handle_dropped(self.view_id, self.handle_id);
4529    }
4530}
4531
4532pub struct AnyModelHandle {
4533    model_id: usize,
4534    model_type: TypeId,
4535    ref_counts: Arc<Mutex<RefCounts>>,
4536
4537    #[cfg(any(test, feature = "test-support"))]
4538    handle_id: usize,
4539}
4540
4541impl AnyModelHandle {
4542    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
4543        ref_counts.lock().inc_model(model_id);
4544
4545        #[cfg(any(test, feature = "test-support"))]
4546        let handle_id = ref_counts
4547            .lock()
4548            .leak_detector
4549            .lock()
4550            .handle_created(None, model_id);
4551
4552        Self {
4553            model_id,
4554            model_type,
4555            ref_counts,
4556
4557            #[cfg(any(test, feature = "test-support"))]
4558            handle_id,
4559        }
4560    }
4561
4562    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
4563        if self.is::<T>() {
4564            let result = Some(ModelHandle {
4565                model_id: self.model_id,
4566                model_type: PhantomData,
4567                ref_counts: self.ref_counts.clone(),
4568
4569                #[cfg(any(test, feature = "test-support"))]
4570                handle_id: self.handle_id,
4571            });
4572            unsafe {
4573                Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
4574            }
4575            std::mem::forget(self);
4576            result
4577        } else {
4578            None
4579        }
4580    }
4581
4582    pub fn downgrade(&self) -> AnyWeakModelHandle {
4583        AnyWeakModelHandle {
4584            model_id: self.model_id,
4585            model_type: self.model_type,
4586        }
4587    }
4588
4589    pub fn is<T: Entity>(&self) -> bool {
4590        self.model_type == TypeId::of::<T>()
4591    }
4592
4593    pub fn model_type(&self) -> TypeId {
4594        self.model_type
4595    }
4596}
4597
4598impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
4599    fn from(handle: ModelHandle<T>) -> Self {
4600        Self::new(
4601            handle.model_id,
4602            TypeId::of::<T>(),
4603            handle.ref_counts.clone(),
4604        )
4605    }
4606}
4607
4608impl Clone for AnyModelHandle {
4609    fn clone(&self) -> Self {
4610        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
4611    }
4612}
4613
4614impl Drop for AnyModelHandle {
4615    fn drop(&mut self) {
4616        let mut ref_counts = self.ref_counts.lock();
4617        ref_counts.dec_model(self.model_id);
4618
4619        #[cfg(any(test, feature = "test-support"))]
4620        ref_counts
4621            .leak_detector
4622            .lock()
4623            .handle_dropped(self.model_id, self.handle_id);
4624    }
4625}
4626
4627#[derive(Hash, PartialEq, Eq, Debug)]
4628pub struct AnyWeakModelHandle {
4629    model_id: usize,
4630    model_type: TypeId,
4631}
4632
4633impl AnyWeakModelHandle {
4634    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
4635        cx.upgrade_any_model_handle(self)
4636    }
4637    pub fn model_type(&self) -> TypeId {
4638        self.model_type
4639    }
4640
4641    fn is<T: 'static>(&self) -> bool {
4642        TypeId::of::<T>() == self.model_type
4643    }
4644
4645    pub fn downcast<T: Entity>(&self) -> Option<WeakModelHandle<T>> {
4646        if self.is::<T>() {
4647            let result = Some(WeakModelHandle {
4648                model_id: self.model_id,
4649                model_type: PhantomData,
4650            });
4651
4652            result
4653        } else {
4654            None
4655        }
4656    }
4657}
4658
4659impl<T: Entity> From<WeakModelHandle<T>> for AnyWeakModelHandle {
4660    fn from(handle: WeakModelHandle<T>) -> Self {
4661        AnyWeakModelHandle {
4662            model_id: handle.model_id,
4663            model_type: TypeId::of::<T>(),
4664        }
4665    }
4666}
4667
4668#[derive(Debug)]
4669pub struct WeakViewHandle<T> {
4670    window_id: usize,
4671    view_id: usize,
4672    view_type: PhantomData<T>,
4673}
4674
4675impl<T> WeakHandle for WeakViewHandle<T> {
4676    fn id(&self) -> usize {
4677        self.view_id
4678    }
4679}
4680
4681impl<T: View> WeakViewHandle<T> {
4682    fn new(window_id: usize, view_id: usize) -> Self {
4683        Self {
4684            window_id,
4685            view_id,
4686            view_type: PhantomData,
4687        }
4688    }
4689
4690    pub fn id(&self) -> usize {
4691        self.view_id
4692    }
4693
4694    pub fn window_id(&self) -> usize {
4695        self.window_id
4696    }
4697
4698    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
4699        cx.upgrade_view_handle(self)
4700    }
4701}
4702
4703impl<T> Clone for WeakViewHandle<T> {
4704    fn clone(&self) -> Self {
4705        Self {
4706            window_id: self.window_id,
4707            view_id: self.view_id,
4708            view_type: PhantomData,
4709        }
4710    }
4711}
4712
4713impl<T> PartialEq for WeakViewHandle<T> {
4714    fn eq(&self, other: &Self) -> bool {
4715        self.window_id == other.window_id && self.view_id == other.view_id
4716    }
4717}
4718
4719impl<T> Eq for WeakViewHandle<T> {}
4720
4721impl<T> Hash for WeakViewHandle<T> {
4722    fn hash<H: Hasher>(&self, state: &mut H) {
4723        self.window_id.hash(state);
4724        self.view_id.hash(state);
4725    }
4726}
4727
4728pub struct AnyWeakViewHandle {
4729    window_id: usize,
4730    view_id: usize,
4731    view_type: TypeId,
4732}
4733
4734impl AnyWeakViewHandle {
4735    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<AnyViewHandle> {
4736        cx.upgrade_any_view_handle(self)
4737    }
4738}
4739
4740impl<T: View> From<WeakViewHandle<T>> for AnyWeakViewHandle {
4741    fn from(handle: WeakViewHandle<T>) -> Self {
4742        AnyWeakViewHandle {
4743            window_id: handle.window_id,
4744            view_id: handle.view_id,
4745            view_type: TypeId::of::<T>(),
4746        }
4747    }
4748}
4749
4750#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4751pub struct ElementStateId {
4752    view_id: usize,
4753    element_id: usize,
4754    tag: TypeId,
4755}
4756
4757pub struct ElementStateHandle<T> {
4758    value_type: PhantomData<T>,
4759    id: ElementStateId,
4760    ref_counts: Weak<Mutex<RefCounts>>,
4761}
4762
4763impl<T: 'static> ElementStateHandle<T> {
4764    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4765        ref_counts.lock().inc_element_state(id, frame_id);
4766        Self {
4767            value_type: PhantomData,
4768            id,
4769            ref_counts: Arc::downgrade(ref_counts),
4770        }
4771    }
4772
4773    pub fn id(&self) -> ElementStateId {
4774        self.id
4775    }
4776
4777    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
4778        cx.element_states
4779            .get(&self.id)
4780            .unwrap()
4781            .downcast_ref()
4782            .unwrap()
4783    }
4784
4785    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
4786    where
4787        C: DerefMut<Target = MutableAppContext>,
4788    {
4789        let mut element_state = cx.deref_mut().cx.element_states.remove(&self.id).unwrap();
4790        let result = f(element_state.downcast_mut().unwrap(), cx);
4791        cx.deref_mut()
4792            .cx
4793            .element_states
4794            .insert(self.id, element_state);
4795        result
4796    }
4797}
4798
4799impl<T> Drop for ElementStateHandle<T> {
4800    fn drop(&mut self) {
4801        if let Some(ref_counts) = self.ref_counts.upgrade() {
4802            ref_counts.lock().dec_element_state(self.id);
4803        }
4804    }
4805}
4806
4807#[must_use]
4808pub enum Subscription {
4809    Subscription {
4810        id: usize,
4811        entity_id: usize,
4812        subscriptions: Option<Weak<Mapping<usize, SubscriptionCallback>>>,
4813    },
4814    GlobalSubscription {
4815        id: usize,
4816        type_id: TypeId,
4817        subscriptions: Option<Weak<Mapping<TypeId, GlobalSubscriptionCallback>>>,
4818    },
4819    Observation {
4820        id: usize,
4821        entity_id: usize,
4822        observations: Option<Weak<Mapping<usize, ObservationCallback>>>,
4823    },
4824    GlobalObservation {
4825        id: usize,
4826        type_id: TypeId,
4827        observations: Option<Weak<Mapping<TypeId, GlobalObservationCallback>>>,
4828    },
4829    FocusObservation {
4830        id: usize,
4831        view_id: usize,
4832        observations: Option<Weak<Mapping<usize, FocusObservationCallback>>>,
4833    },
4834    WindowActivationObservation {
4835        id: usize,
4836        window_id: usize,
4837        observations: Option<Weak<Mapping<usize, WindowActivationCallback>>>,
4838    },
4839    WindowFullscreenObservation {
4840        id: usize,
4841        window_id: usize,
4842        observations: Option<Weak<Mapping<usize, WindowFullscreenCallback>>>,
4843    },
4844
4845    ReleaseObservation {
4846        id: usize,
4847        entity_id: usize,
4848        #[allow(clippy::type_complexity)]
4849        observations:
4850            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>>,
4851    },
4852    ActionObservation {
4853        id: usize,
4854        observations: Option<Weak<Mutex<BTreeMap<usize, ActionObservationCallback>>>>,
4855    },
4856}
4857
4858impl Subscription {
4859    pub fn detach(&mut self) {
4860        match self {
4861            Subscription::Subscription { subscriptions, .. } => {
4862                subscriptions.take();
4863            }
4864            Subscription::GlobalSubscription { subscriptions, .. } => {
4865                subscriptions.take();
4866            }
4867            Subscription::Observation { observations, .. } => {
4868                observations.take();
4869            }
4870            Subscription::GlobalObservation { observations, .. } => {
4871                observations.take();
4872            }
4873            Subscription::ReleaseObservation { observations, .. } => {
4874                observations.take();
4875            }
4876            Subscription::FocusObservation { observations, .. } => {
4877                observations.take();
4878            }
4879            Subscription::ActionObservation { observations, .. } => {
4880                observations.take();
4881            }
4882            Subscription::WindowActivationObservation { observations, .. } => {
4883                observations.take();
4884            }
4885            Subscription::WindowFullscreenObservation { observations, .. } => {
4886                observations.take();
4887            }
4888        }
4889    }
4890}
4891
4892impl Drop for Subscription {
4893    fn drop(&mut self) {
4894        match self {
4895            Subscription::Subscription {
4896                id,
4897                entity_id,
4898                subscriptions,
4899            } => {
4900                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
4901                    match subscriptions
4902                        .lock()
4903                        .entry(*entity_id)
4904                        .or_default()
4905                        .entry(*id)
4906                    {
4907                        btree_map::Entry::Vacant(entry) => {
4908                            entry.insert(None);
4909                        }
4910                        btree_map::Entry::Occupied(entry) => {
4911                            entry.remove();
4912                        }
4913                    }
4914                }
4915            }
4916            Subscription::GlobalSubscription {
4917                id,
4918                type_id,
4919                subscriptions,
4920            } => {
4921                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
4922                    match subscriptions.lock().entry(*type_id).or_default().entry(*id) {
4923                        btree_map::Entry::Vacant(entry) => {
4924                            entry.insert(None);
4925                        }
4926                        btree_map::Entry::Occupied(entry) => {
4927                            entry.remove();
4928                        }
4929                    }
4930                }
4931            }
4932            Subscription::Observation {
4933                id,
4934                entity_id,
4935                observations,
4936            } => {
4937                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4938                    match observations
4939                        .lock()
4940                        .entry(*entity_id)
4941                        .or_default()
4942                        .entry(*id)
4943                    {
4944                        btree_map::Entry::Vacant(entry) => {
4945                            entry.insert(None);
4946                        }
4947                        btree_map::Entry::Occupied(entry) => {
4948                            entry.remove();
4949                        }
4950                    }
4951                }
4952            }
4953            Subscription::GlobalObservation {
4954                id,
4955                type_id,
4956                observations,
4957            } => {
4958                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4959                    match observations.lock().entry(*type_id).or_default().entry(*id) {
4960                        collections::btree_map::Entry::Vacant(entry) => {
4961                            entry.insert(None);
4962                        }
4963                        collections::btree_map::Entry::Occupied(entry) => {
4964                            entry.remove();
4965                        }
4966                    }
4967                }
4968            }
4969            Subscription::ReleaseObservation {
4970                id,
4971                entity_id,
4972                observations,
4973            } => {
4974                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4975                    if let Some(observations) = observations.lock().get_mut(entity_id) {
4976                        observations.remove(id);
4977                    }
4978                }
4979            }
4980            Subscription::FocusObservation {
4981                id,
4982                view_id,
4983                observations,
4984            } => {
4985                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4986                    match observations.lock().entry(*view_id).or_default().entry(*id) {
4987                        btree_map::Entry::Vacant(entry) => {
4988                            entry.insert(None);
4989                        }
4990                        btree_map::Entry::Occupied(entry) => {
4991                            entry.remove();
4992                        }
4993                    }
4994                }
4995            }
4996            Subscription::ActionObservation { id, observations } => {
4997                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
4998                    observations.lock().remove(id);
4999                }
5000            }
5001            Subscription::WindowActivationObservation {
5002                id,
5003                window_id,
5004                observations,
5005            } => {
5006                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5007                    match observations
5008                        .lock()
5009                        .entry(*window_id)
5010                        .or_default()
5011                        .entry(*id)
5012                    {
5013                        btree_map::Entry::Vacant(entry) => {
5014                            entry.insert(None);
5015                        }
5016                        btree_map::Entry::Occupied(entry) => {
5017                            entry.remove();
5018                        }
5019                    }
5020                }
5021            }
5022            Subscription::WindowFullscreenObservation {
5023                id,
5024                window_id,
5025                observations,
5026            } => {
5027                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5028                    match observations
5029                        .lock()
5030                        .entry(*window_id)
5031                        .or_default()
5032                        .entry(*id)
5033                    {
5034                        btree_map::Entry::Vacant(entry) => {
5035                            entry.insert(None);
5036                        }
5037                        btree_map::Entry::Occupied(entry) => {
5038                            entry.remove();
5039                        }
5040                    }
5041                }
5042            }
5043        }
5044    }
5045}
5046
5047lazy_static! {
5048    static ref LEAK_BACKTRACE: bool =
5049        std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty());
5050}
5051
5052#[cfg(any(test, feature = "test-support"))]
5053#[derive(Default)]
5054pub struct LeakDetector {
5055    next_handle_id: usize,
5056    #[allow(clippy::type_complexity)]
5057    handle_backtraces: HashMap<
5058        usize,
5059        (
5060            Option<&'static str>,
5061            HashMap<usize, Option<backtrace::Backtrace>>,
5062        ),
5063    >,
5064}
5065
5066#[cfg(any(test, feature = "test-support"))]
5067impl LeakDetector {
5068    fn handle_created(&mut self, type_name: Option<&'static str>, entity_id: usize) -> usize {
5069        let handle_id = post_inc(&mut self.next_handle_id);
5070        let entry = self.handle_backtraces.entry(entity_id).or_default();
5071        let backtrace = if *LEAK_BACKTRACE {
5072            Some(backtrace::Backtrace::new_unresolved())
5073        } else {
5074            None
5075        };
5076        if let Some(type_name) = type_name {
5077            entry.0.get_or_insert(type_name);
5078        }
5079        entry.1.insert(handle_id, backtrace);
5080        handle_id
5081    }
5082
5083    fn handle_dropped(&mut self, entity_id: usize, handle_id: usize) {
5084        if let Some((_, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
5085            assert!(backtraces.remove(&handle_id).is_some());
5086            if backtraces.is_empty() {
5087                self.handle_backtraces.remove(&entity_id);
5088            }
5089        }
5090    }
5091
5092    pub fn assert_dropped(&mut self, entity_id: usize) {
5093        if let Some((type_name, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
5094            for trace in backtraces.values_mut().flatten() {
5095                trace.resolve();
5096                eprintln!("{:?}", crate::util::CwdBacktrace(trace));
5097            }
5098
5099            let hint = if *LEAK_BACKTRACE {
5100                ""
5101            } else {
5102                " – set LEAK_BACKTRACE=1 for more information"
5103            };
5104
5105            panic!(
5106                "{} handles to {} {} still exist{}",
5107                backtraces.len(),
5108                type_name.unwrap_or("entity"),
5109                entity_id,
5110                hint
5111            );
5112        }
5113    }
5114
5115    pub fn detect(&mut self) {
5116        let mut found_leaks = false;
5117        for (id, (type_name, backtraces)) in self.handle_backtraces.iter_mut() {
5118            eprintln!(
5119                "leaked {} handles to {} {}",
5120                backtraces.len(),
5121                type_name.unwrap_or("entity"),
5122                id
5123            );
5124            for trace in backtraces.values_mut().flatten() {
5125                trace.resolve();
5126                eprintln!("{:?}", crate::util::CwdBacktrace(trace));
5127            }
5128            found_leaks = true;
5129        }
5130
5131        let hint = if *LEAK_BACKTRACE {
5132            ""
5133        } else {
5134            " – set LEAK_BACKTRACE=1 for more information"
5135        };
5136        assert!(!found_leaks, "detected leaked handles{}", hint);
5137    }
5138}
5139
5140#[derive(Default)]
5141struct RefCounts {
5142    entity_counts: HashMap<usize, usize>,
5143    element_state_counts: HashMap<ElementStateId, ElementStateRefCount>,
5144    dropped_models: HashSet<usize>,
5145    dropped_views: HashSet<(usize, usize)>,
5146    dropped_element_states: HashSet<ElementStateId>,
5147
5148    #[cfg(any(test, feature = "test-support"))]
5149    leak_detector: Arc<Mutex<LeakDetector>>,
5150}
5151
5152struct ElementStateRefCount {
5153    ref_count: usize,
5154    frame_id: usize,
5155}
5156
5157impl RefCounts {
5158    fn inc_model(&mut self, model_id: usize) {
5159        match self.entity_counts.entry(model_id) {
5160            Entry::Occupied(mut entry) => {
5161                *entry.get_mut() += 1;
5162            }
5163            Entry::Vacant(entry) => {
5164                entry.insert(1);
5165                self.dropped_models.remove(&model_id);
5166            }
5167        }
5168    }
5169
5170    fn inc_view(&mut self, window_id: usize, view_id: usize) {
5171        match self.entity_counts.entry(view_id) {
5172            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
5173            Entry::Vacant(entry) => {
5174                entry.insert(1);
5175                self.dropped_views.remove(&(window_id, view_id));
5176            }
5177        }
5178    }
5179
5180    fn inc_element_state(&mut self, id: ElementStateId, frame_id: usize) {
5181        match self.element_state_counts.entry(id) {
5182            Entry::Occupied(mut entry) => {
5183                let entry = entry.get_mut();
5184                if entry.frame_id == frame_id || entry.ref_count >= 2 {
5185                    panic!("used the same element state more than once in the same frame");
5186                }
5187                entry.ref_count += 1;
5188                entry.frame_id = frame_id;
5189            }
5190            Entry::Vacant(entry) => {
5191                entry.insert(ElementStateRefCount {
5192                    ref_count: 1,
5193                    frame_id,
5194                });
5195                self.dropped_element_states.remove(&id);
5196            }
5197        }
5198    }
5199
5200    fn dec_model(&mut self, model_id: usize) {
5201        let count = self.entity_counts.get_mut(&model_id).unwrap();
5202        *count -= 1;
5203        if *count == 0 {
5204            self.entity_counts.remove(&model_id);
5205            self.dropped_models.insert(model_id);
5206        }
5207    }
5208
5209    fn dec_view(&mut self, window_id: usize, view_id: usize) {
5210        let count = self.entity_counts.get_mut(&view_id).unwrap();
5211        *count -= 1;
5212        if *count == 0 {
5213            self.entity_counts.remove(&view_id);
5214            self.dropped_views.insert((window_id, view_id));
5215        }
5216    }
5217
5218    fn dec_element_state(&mut self, id: ElementStateId) {
5219        let entry = self.element_state_counts.get_mut(&id).unwrap();
5220        entry.ref_count -= 1;
5221        if entry.ref_count == 0 {
5222            self.element_state_counts.remove(&id);
5223            self.dropped_element_states.insert(id);
5224        }
5225    }
5226
5227    fn is_entity_alive(&self, entity_id: usize) -> bool {
5228        self.entity_counts.contains_key(&entity_id)
5229    }
5230
5231    fn take_dropped(
5232        &mut self,
5233    ) -> (
5234        HashSet<usize>,
5235        HashSet<(usize, usize)>,
5236        HashSet<ElementStateId>,
5237    ) {
5238        (
5239            std::mem::take(&mut self.dropped_models),
5240            std::mem::take(&mut self.dropped_views),
5241            std::mem::take(&mut self.dropped_element_states),
5242        )
5243    }
5244}
5245
5246#[cfg(test)]
5247mod tests {
5248    use super::*;
5249    use crate::{actions, elements::*, impl_actions, MouseButton, MouseButtonEvent};
5250    use serde::Deserialize;
5251    use smol::future::poll_once;
5252    use std::{
5253        cell::Cell,
5254        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
5255    };
5256
5257    #[crate::test(self)]
5258    fn test_model_handles(cx: &mut MutableAppContext) {
5259        struct Model {
5260            other: Option<ModelHandle<Model>>,
5261            events: Vec<String>,
5262        }
5263
5264        impl Entity for Model {
5265            type Event = usize;
5266        }
5267
5268        impl Model {
5269            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
5270                if let Some(other) = other.as_ref() {
5271                    cx.observe(other, |me, _, _| {
5272                        me.events.push("notified".into());
5273                    })
5274                    .detach();
5275                    cx.subscribe(other, |me, _, event, _| {
5276                        me.events.push(format!("observed event {}", event));
5277                    })
5278                    .detach();
5279                }
5280
5281                Self {
5282                    other,
5283                    events: Vec::new(),
5284                }
5285            }
5286        }
5287
5288        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
5289        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
5290        assert_eq!(cx.cx.models.len(), 2);
5291
5292        handle_1.update(cx, |model, cx| {
5293            model.events.push("updated".into());
5294            cx.emit(1);
5295            cx.notify();
5296            cx.emit(2);
5297        });
5298        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5299        assert_eq!(
5300            handle_2.read(cx).events,
5301            vec![
5302                "observed event 1".to_string(),
5303                "notified".to_string(),
5304                "observed event 2".to_string(),
5305            ]
5306        );
5307
5308        handle_2.update(cx, |model, _| {
5309            drop(handle_1);
5310            model.other.take();
5311        });
5312
5313        assert_eq!(cx.cx.models.len(), 1);
5314        assert!(cx.subscriptions.is_empty());
5315        assert!(cx.observations.is_empty());
5316    }
5317
5318    #[crate::test(self)]
5319    fn test_model_events(cx: &mut MutableAppContext) {
5320        #[derive(Default)]
5321        struct Model {
5322            events: Vec<usize>,
5323        }
5324
5325        impl Entity for Model {
5326            type Event = usize;
5327        }
5328
5329        let handle_1 = cx.add_model(|_| Model::default());
5330        let handle_2 = cx.add_model(|_| Model::default());
5331
5332        handle_1.update(cx, |_, cx| {
5333            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
5334                model.events.push(*event);
5335
5336                cx.subscribe(&emitter, |model, _, event, _| {
5337                    model.events.push(*event * 2);
5338                })
5339                .detach();
5340            })
5341            .detach();
5342        });
5343
5344        handle_2.update(cx, |_, c| c.emit(7));
5345        assert_eq!(handle_1.read(cx).events, vec![7]);
5346
5347        handle_2.update(cx, |_, c| c.emit(5));
5348        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
5349    }
5350
5351    #[crate::test(self)]
5352    fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
5353        #[derive(Default)]
5354        struct Model;
5355
5356        impl Entity for Model {
5357            type Event = ();
5358        }
5359
5360        let events = Rc::new(RefCell::new(Vec::new()));
5361        cx.add_model(|cx| {
5362            drop(cx.subscribe(&cx.handle(), {
5363                let events = events.clone();
5364                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
5365            }));
5366            cx.subscribe(&cx.handle(), {
5367                let events = events.clone();
5368                move |_, _, _, _| events.borrow_mut().push("before emit")
5369            })
5370            .detach();
5371            cx.emit(());
5372            cx.subscribe(&cx.handle(), {
5373                let events = events.clone();
5374                move |_, _, _, _| events.borrow_mut().push("after emit")
5375            })
5376            .detach();
5377            Model
5378        });
5379        assert_eq!(*events.borrow(), ["before emit"]);
5380    }
5381
5382    #[crate::test(self)]
5383    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
5384        #[derive(Default)]
5385        struct Model {
5386            count: usize,
5387            events: Vec<usize>,
5388        }
5389
5390        impl Entity for Model {
5391            type Event = ();
5392        }
5393
5394        let handle_1 = cx.add_model(|_| Model::default());
5395        let handle_2 = cx.add_model(|_| Model::default());
5396
5397        handle_1.update(cx, |_, c| {
5398            c.observe(&handle_2, move |model, observed, c| {
5399                model.events.push(observed.read(c).count);
5400                c.observe(&observed, |model, observed, c| {
5401                    model.events.push(observed.read(c).count * 2);
5402                })
5403                .detach();
5404            })
5405            .detach();
5406        });
5407
5408        handle_2.update(cx, |model, c| {
5409            model.count = 7;
5410            c.notify()
5411        });
5412        assert_eq!(handle_1.read(cx).events, vec![7]);
5413
5414        handle_2.update(cx, |model, c| {
5415            model.count = 5;
5416            c.notify()
5417        });
5418        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
5419    }
5420
5421    #[crate::test(self)]
5422    fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
5423        #[derive(Default)]
5424        struct Model;
5425
5426        impl Entity for Model {
5427            type Event = ();
5428        }
5429
5430        let events = Rc::new(RefCell::new(Vec::new()));
5431        cx.add_model(|cx| {
5432            drop(cx.observe(&cx.handle(), {
5433                let events = events.clone();
5434                move |_, _, _| events.borrow_mut().push("dropped before flush")
5435            }));
5436            cx.observe(&cx.handle(), {
5437                let events = events.clone();
5438                move |_, _, _| events.borrow_mut().push("before notify")
5439            })
5440            .detach();
5441            cx.notify();
5442            cx.observe(&cx.handle(), {
5443                let events = events.clone();
5444                move |_, _, _| events.borrow_mut().push("after notify")
5445            })
5446            .detach();
5447            Model
5448        });
5449        assert_eq!(*events.borrow(), ["before notify"]);
5450    }
5451
5452    #[crate::test(self)]
5453    fn test_defer_and_after_window_update(cx: &mut MutableAppContext) {
5454        struct View {
5455            render_count: usize,
5456        }
5457
5458        impl Entity for View {
5459            type Event = usize;
5460        }
5461
5462        impl super::View for View {
5463            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5464                post_inc(&mut self.render_count);
5465                Empty::new().boxed()
5466            }
5467
5468            fn ui_name() -> &'static str {
5469                "View"
5470            }
5471        }
5472
5473        let (_, view) = cx.add_window(Default::default(), |_| View { render_count: 0 });
5474        let called_defer = Rc::new(AtomicBool::new(false));
5475        let called_after_window_update = Rc::new(AtomicBool::new(false));
5476
5477        view.update(cx, |this, cx| {
5478            assert_eq!(this.render_count, 1);
5479            cx.defer({
5480                let called_defer = called_defer.clone();
5481                move |this, _| {
5482                    assert_eq!(this.render_count, 1);
5483                    called_defer.store(true, SeqCst);
5484                }
5485            });
5486            cx.after_window_update({
5487                let called_after_window_update = called_after_window_update.clone();
5488                move |this, cx| {
5489                    assert_eq!(this.render_count, 2);
5490                    called_after_window_update.store(true, SeqCst);
5491                    cx.notify();
5492                }
5493            });
5494            assert!(!called_defer.load(SeqCst));
5495            assert!(!called_after_window_update.load(SeqCst));
5496            cx.notify();
5497        });
5498
5499        assert!(called_defer.load(SeqCst));
5500        assert!(called_after_window_update.load(SeqCst));
5501        assert_eq!(view.read(cx).render_count, 3);
5502    }
5503
5504    #[crate::test(self)]
5505    fn test_view_handles(cx: &mut MutableAppContext) {
5506        struct View {
5507            other: Option<ViewHandle<View>>,
5508            events: Vec<String>,
5509        }
5510
5511        impl Entity for View {
5512            type Event = usize;
5513        }
5514
5515        impl super::View for View {
5516            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5517                Empty::new().boxed()
5518            }
5519
5520            fn ui_name() -> &'static str {
5521                "View"
5522            }
5523        }
5524
5525        impl View {
5526            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
5527                if let Some(other) = other.as_ref() {
5528                    cx.subscribe(other, |me, _, event, _| {
5529                        me.events.push(format!("observed event {}", event));
5530                    })
5531                    .detach();
5532                }
5533                Self {
5534                    other,
5535                    events: Vec::new(),
5536                }
5537            }
5538        }
5539
5540        let (_, root_view) = cx.add_window(Default::default(), |cx| View::new(None, cx));
5541        let handle_1 = cx.add_view(&root_view, |cx| View::new(None, cx));
5542        let handle_2 = cx.add_view(&root_view, |cx| View::new(Some(handle_1.clone()), cx));
5543        assert_eq!(cx.cx.views.len(), 3);
5544
5545        handle_1.update(cx, |view, cx| {
5546            view.events.push("updated".into());
5547            cx.emit(1);
5548            cx.emit(2);
5549        });
5550        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5551        assert_eq!(
5552            handle_2.read(cx).events,
5553            vec![
5554                "observed event 1".to_string(),
5555                "observed event 2".to_string(),
5556            ]
5557        );
5558
5559        handle_2.update(cx, |view, _| {
5560            drop(handle_1);
5561            view.other.take();
5562        });
5563
5564        assert_eq!(cx.cx.views.len(), 2);
5565        assert!(cx.subscriptions.is_empty());
5566        assert!(cx.observations.is_empty());
5567    }
5568
5569    #[crate::test(self)]
5570    fn test_add_window(cx: &mut MutableAppContext) {
5571        struct View {
5572            mouse_down_count: Arc<AtomicUsize>,
5573        }
5574
5575        impl Entity for View {
5576            type Event = ();
5577        }
5578
5579        impl super::View for View {
5580            fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
5581                enum Handler {}
5582                let mouse_down_count = self.mouse_down_count.clone();
5583                MouseEventHandler::<Handler>::new(0, cx, |_, _| Empty::new().boxed())
5584                    .on_down(MouseButton::Left, move |_, _| {
5585                        mouse_down_count.fetch_add(1, SeqCst);
5586                    })
5587                    .boxed()
5588            }
5589
5590            fn ui_name() -> &'static str {
5591                "View"
5592            }
5593        }
5594
5595        let mouse_down_count = Arc::new(AtomicUsize::new(0));
5596        let (window_id, _) = cx.add_window(Default::default(), |_| View {
5597            mouse_down_count: mouse_down_count.clone(),
5598        });
5599        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
5600        // Ensure window's root element is in a valid lifecycle state.
5601        presenter.borrow_mut().dispatch_event(
5602            Event::MouseDown(MouseButtonEvent {
5603                position: Default::default(),
5604                button: MouseButton::Left,
5605                ctrl: false,
5606                alt: false,
5607                shift: false,
5608                cmd: false,
5609                click_count: 1,
5610            }),
5611            false,
5612            cx,
5613        );
5614        assert_eq!(mouse_down_count.load(SeqCst), 1);
5615    }
5616
5617    #[crate::test(self)]
5618    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
5619        struct Model {
5620            released: Rc<Cell<bool>>,
5621        }
5622
5623        struct View {
5624            released: Rc<Cell<bool>>,
5625        }
5626
5627        impl Entity for Model {
5628            type Event = ();
5629
5630            fn release(&mut self, _: &mut MutableAppContext) {
5631                self.released.set(true);
5632            }
5633        }
5634
5635        impl Entity for View {
5636            type Event = ();
5637
5638            fn release(&mut self, _: &mut MutableAppContext) {
5639                self.released.set(true);
5640            }
5641        }
5642
5643        impl super::View for View {
5644            fn ui_name() -> &'static str {
5645                "View"
5646            }
5647
5648            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5649                Empty::new().boxed()
5650            }
5651        }
5652
5653        let model_released = Rc::new(Cell::new(false));
5654        let model_release_observed = Rc::new(Cell::new(false));
5655        let view_released = Rc::new(Cell::new(false));
5656        let view_release_observed = Rc::new(Cell::new(false));
5657
5658        let model = cx.add_model(|_| Model {
5659            released: model_released.clone(),
5660        });
5661        let (window_id, view) = cx.add_window(Default::default(), |_| View {
5662            released: view_released.clone(),
5663        });
5664        assert!(!model_released.get());
5665        assert!(!view_released.get());
5666
5667        cx.observe_release(&model, {
5668            let model_release_observed = model_release_observed.clone();
5669            move |_, _| model_release_observed.set(true)
5670        })
5671        .detach();
5672        cx.observe_release(&view, {
5673            let view_release_observed = view_release_observed.clone();
5674            move |_, _| view_release_observed.set(true)
5675        })
5676        .detach();
5677
5678        cx.update(move |_| {
5679            drop(model);
5680        });
5681        assert!(model_released.get());
5682        assert!(model_release_observed.get());
5683
5684        drop(view);
5685        cx.remove_window(window_id);
5686        assert!(view_released.get());
5687        assert!(view_release_observed.get());
5688    }
5689
5690    #[crate::test(self)]
5691    fn test_view_events(cx: &mut MutableAppContext) {
5692        #[derive(Default)]
5693        struct View {
5694            events: Vec<usize>,
5695        }
5696
5697        impl Entity for View {
5698            type Event = usize;
5699        }
5700
5701        impl super::View for View {
5702            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5703                Empty::new().boxed()
5704            }
5705
5706            fn ui_name() -> &'static str {
5707                "View"
5708            }
5709        }
5710
5711        struct Model;
5712
5713        impl Entity for Model {
5714            type Event = usize;
5715        }
5716
5717        let (_, handle_1) = cx.add_window(Default::default(), |_| View::default());
5718        let handle_2 = cx.add_view(&handle_1, |_| View::default());
5719        let handle_3 = cx.add_model(|_| Model);
5720
5721        handle_1.update(cx, |_, cx| {
5722            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
5723                me.events.push(*event);
5724
5725                cx.subscribe(&emitter, |me, _, event, _| {
5726                    me.events.push(*event * 2);
5727                })
5728                .detach();
5729            })
5730            .detach();
5731
5732            cx.subscribe(&handle_3, |me, _, event, _| {
5733                me.events.push(*event);
5734            })
5735            .detach();
5736        });
5737
5738        handle_2.update(cx, |_, c| c.emit(7));
5739        assert_eq!(handle_1.read(cx).events, vec![7]);
5740
5741        handle_2.update(cx, |_, c| c.emit(5));
5742        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
5743
5744        handle_3.update(cx, |_, c| c.emit(9));
5745        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
5746    }
5747
5748    #[crate::test(self)]
5749    fn test_global_events(cx: &mut MutableAppContext) {
5750        #[derive(Clone, Debug, Eq, PartialEq)]
5751        struct GlobalEvent(u64);
5752
5753        let events = Rc::new(RefCell::new(Vec::new()));
5754        let first_subscription;
5755        let second_subscription;
5756
5757        {
5758            let events = events.clone();
5759            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5760                events.borrow_mut().push(("First", e.clone()));
5761            });
5762        }
5763
5764        {
5765            let events = events.clone();
5766            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5767                events.borrow_mut().push(("Second", e.clone()));
5768            });
5769        }
5770
5771        cx.update(|cx| {
5772            cx.emit_global(GlobalEvent(1));
5773            cx.emit_global(GlobalEvent(2));
5774        });
5775
5776        drop(first_subscription);
5777
5778        cx.update(|cx| {
5779            cx.emit_global(GlobalEvent(3));
5780        });
5781
5782        drop(second_subscription);
5783
5784        cx.update(|cx| {
5785            cx.emit_global(GlobalEvent(4));
5786        });
5787
5788        assert_eq!(
5789            &*events.borrow(),
5790            &[
5791                ("First", GlobalEvent(1)),
5792                ("Second", GlobalEvent(1)),
5793                ("First", GlobalEvent(2)),
5794                ("Second", GlobalEvent(2)),
5795                ("Second", GlobalEvent(3)),
5796            ]
5797        );
5798    }
5799
5800    #[crate::test(self)]
5801    fn test_global_events_emitted_before_subscription_in_same_update_cycle(
5802        cx: &mut MutableAppContext,
5803    ) {
5804        let events = Rc::new(RefCell::new(Vec::new()));
5805        cx.update(|cx| {
5806            {
5807                let events = events.clone();
5808                drop(cx.subscribe_global(move |_: &(), _| {
5809                    events.borrow_mut().push("dropped before emit");
5810                }));
5811            }
5812
5813            {
5814                let events = events.clone();
5815                cx.subscribe_global(move |_: &(), _| {
5816                    events.borrow_mut().push("before emit");
5817                })
5818                .detach();
5819            }
5820
5821            cx.emit_global(());
5822
5823            {
5824                let events = events.clone();
5825                cx.subscribe_global(move |_: &(), _| {
5826                    events.borrow_mut().push("after emit");
5827                })
5828                .detach();
5829            }
5830        });
5831
5832        assert_eq!(*events.borrow(), ["before emit"]);
5833    }
5834
5835    #[crate::test(self)]
5836    fn test_global_nested_events(cx: &mut MutableAppContext) {
5837        #[derive(Clone, Debug, Eq, PartialEq)]
5838        struct GlobalEvent(u64);
5839
5840        let events = Rc::new(RefCell::new(Vec::new()));
5841
5842        {
5843            let events = events.clone();
5844            cx.subscribe_global(move |e: &GlobalEvent, cx| {
5845                events.borrow_mut().push(("Outer", e.clone()));
5846
5847                if e.0 == 1 {
5848                    let events = events.clone();
5849                    cx.subscribe_global(move |e: &GlobalEvent, _| {
5850                        events.borrow_mut().push(("Inner", e.clone()));
5851                    })
5852                    .detach();
5853                }
5854            })
5855            .detach();
5856        }
5857
5858        cx.update(|cx| {
5859            cx.emit_global(GlobalEvent(1));
5860            cx.emit_global(GlobalEvent(2));
5861            cx.emit_global(GlobalEvent(3));
5862        });
5863        cx.update(|cx| {
5864            cx.emit_global(GlobalEvent(4));
5865        });
5866
5867        assert_eq!(
5868            &*events.borrow(),
5869            &[
5870                ("Outer", GlobalEvent(1)),
5871                ("Outer", GlobalEvent(2)),
5872                ("Outer", GlobalEvent(3)),
5873                ("Outer", GlobalEvent(4)),
5874                ("Inner", GlobalEvent(4)),
5875            ]
5876        );
5877    }
5878
5879    #[crate::test(self)]
5880    fn test_global(cx: &mut MutableAppContext) {
5881        type Global = usize;
5882
5883        let observation_count = Rc::new(RefCell::new(0));
5884        let subscription = cx.observe_global::<Global, _>({
5885            let observation_count = observation_count.clone();
5886            move |_| {
5887                *observation_count.borrow_mut() += 1;
5888            }
5889        });
5890
5891        assert!(!cx.has_global::<Global>());
5892        assert_eq!(cx.default_global::<Global>(), &0);
5893        assert_eq!(*observation_count.borrow(), 1);
5894        assert!(cx.has_global::<Global>());
5895        assert_eq!(
5896            cx.update_global::<Global, _, _>(|global, _| {
5897                *global = 1;
5898                "Update Result"
5899            }),
5900            "Update Result"
5901        );
5902        assert_eq!(*observation_count.borrow(), 2);
5903        assert_eq!(cx.global::<Global>(), &1);
5904
5905        drop(subscription);
5906        cx.update_global::<Global, _, _>(|global, _| {
5907            *global = 2;
5908        });
5909        assert_eq!(*observation_count.borrow(), 2);
5910
5911        type OtherGlobal = f32;
5912
5913        let observation_count = Rc::new(RefCell::new(0));
5914        cx.observe_global::<OtherGlobal, _>({
5915            let observation_count = observation_count.clone();
5916            move |_| {
5917                *observation_count.borrow_mut() += 1;
5918            }
5919        })
5920        .detach();
5921
5922        assert_eq!(
5923            cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
5924                assert_eq!(global, &0.0);
5925                *global = 2.0;
5926                "Default update result"
5927            }),
5928            "Default update result"
5929        );
5930        assert_eq!(cx.global::<OtherGlobal>(), &2.0);
5931        assert_eq!(*observation_count.borrow(), 1);
5932    }
5933
5934    #[crate::test(self)]
5935    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
5936        struct View;
5937
5938        impl Entity for View {
5939            type Event = ();
5940        }
5941
5942        impl super::View for View {
5943            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5944                Empty::new().boxed()
5945            }
5946
5947            fn ui_name() -> &'static str {
5948                "View"
5949            }
5950        }
5951
5952        struct Model;
5953
5954        impl Entity for Model {
5955            type Event = ();
5956        }
5957
5958        let (_, root_view) = cx.add_window(Default::default(), |_| View);
5959        let observing_view = cx.add_view(&root_view, |_| View);
5960        let emitting_view = cx.add_view(&root_view, |_| View);
5961        let observing_model = cx.add_model(|_| Model);
5962        let observed_model = cx.add_model(|_| Model);
5963
5964        observing_view.update(cx, |_, cx| {
5965            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
5966            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5967        });
5968        observing_model.update(cx, |_, cx| {
5969            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
5970        });
5971
5972        cx.update(|_| {
5973            drop(observing_view);
5974            drop(observing_model);
5975        });
5976
5977        emitting_view.update(cx, |_, cx| cx.emit(()));
5978        observed_model.update(cx, |_, cx| cx.emit(()));
5979    }
5980
5981    #[crate::test(self)]
5982    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
5983        #[derive(Default)]
5984        struct TestView;
5985
5986        impl Entity for TestView {
5987            type Event = ();
5988        }
5989
5990        impl View for TestView {
5991            fn ui_name() -> &'static str {
5992                "TestView"
5993            }
5994
5995            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5996                Empty::new().boxed()
5997            }
5998        }
5999
6000        let events = Rc::new(RefCell::new(Vec::new()));
6001        cx.add_window(Default::default(), |cx| {
6002            drop(cx.subscribe(&cx.handle(), {
6003                let events = events.clone();
6004                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
6005            }));
6006            cx.subscribe(&cx.handle(), {
6007                let events = events.clone();
6008                move |_, _, _, _| events.borrow_mut().push("before emit")
6009            })
6010            .detach();
6011            cx.emit(());
6012            cx.subscribe(&cx.handle(), {
6013                let events = events.clone();
6014                move |_, _, _, _| events.borrow_mut().push("after emit")
6015            })
6016            .detach();
6017            TestView
6018        });
6019        assert_eq!(*events.borrow(), ["before emit"]);
6020    }
6021
6022    #[crate::test(self)]
6023    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
6024        #[derive(Default)]
6025        struct View {
6026            events: Vec<usize>,
6027        }
6028
6029        impl Entity for View {
6030            type Event = usize;
6031        }
6032
6033        impl super::View for View {
6034            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6035                Empty::new().boxed()
6036            }
6037
6038            fn ui_name() -> &'static str {
6039                "View"
6040            }
6041        }
6042
6043        #[derive(Default)]
6044        struct Model {
6045            count: usize,
6046        }
6047
6048        impl Entity for Model {
6049            type Event = ();
6050        }
6051
6052        let (_, view) = cx.add_window(Default::default(), |_| View::default());
6053        let model = cx.add_model(|_| Model::default());
6054
6055        view.update(cx, |_, c| {
6056            c.observe(&model, |me, observed, c| {
6057                me.events.push(observed.read(c).count)
6058            })
6059            .detach();
6060        });
6061
6062        model.update(cx, |model, c| {
6063            model.count = 11;
6064            c.notify();
6065        });
6066        assert_eq!(view.read(cx).events, vec![11]);
6067    }
6068
6069    #[crate::test(self)]
6070    fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
6071        #[derive(Default)]
6072        struct TestView;
6073
6074        impl Entity for TestView {
6075            type Event = ();
6076        }
6077
6078        impl View for TestView {
6079            fn ui_name() -> &'static str {
6080                "TestView"
6081            }
6082
6083            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6084                Empty::new().boxed()
6085            }
6086        }
6087
6088        let events = Rc::new(RefCell::new(Vec::new()));
6089        cx.add_window(Default::default(), |cx| {
6090            drop(cx.observe(&cx.handle(), {
6091                let events = events.clone();
6092                move |_, _, _| events.borrow_mut().push("dropped before flush")
6093            }));
6094            cx.observe(&cx.handle(), {
6095                let events = events.clone();
6096                move |_, _, _| events.borrow_mut().push("before notify")
6097            })
6098            .detach();
6099            cx.notify();
6100            cx.observe(&cx.handle(), {
6101                let events = events.clone();
6102                move |_, _, _| events.borrow_mut().push("after notify")
6103            })
6104            .detach();
6105            TestView
6106        });
6107        assert_eq!(*events.borrow(), ["before notify"]);
6108    }
6109
6110    #[crate::test(self)]
6111    fn test_dropping_observers(cx: &mut MutableAppContext) {
6112        struct View;
6113
6114        impl Entity for View {
6115            type Event = ();
6116        }
6117
6118        impl super::View for View {
6119            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6120                Empty::new().boxed()
6121            }
6122
6123            fn ui_name() -> &'static str {
6124                "View"
6125            }
6126        }
6127
6128        struct Model;
6129
6130        impl Entity for Model {
6131            type Event = ();
6132        }
6133
6134        let (_, root_view) = cx.add_window(Default::default(), |_| View);
6135        let observing_view = cx.add_view(root_view, |_| View);
6136        let observing_model = cx.add_model(|_| Model);
6137        let observed_model = cx.add_model(|_| Model);
6138
6139        observing_view.update(cx, |_, cx| {
6140            cx.observe(&observed_model, |_, _, _| {}).detach();
6141        });
6142        observing_model.update(cx, |_, cx| {
6143            cx.observe(&observed_model, |_, _, _| {}).detach();
6144        });
6145
6146        cx.update(|_| {
6147            drop(observing_view);
6148            drop(observing_model);
6149        });
6150
6151        observed_model.update(cx, |_, cx| cx.notify());
6152    }
6153
6154    #[crate::test(self)]
6155    fn test_dropping_subscriptions_during_callback(cx: &mut MutableAppContext) {
6156        struct Model;
6157
6158        impl Entity for Model {
6159            type Event = u64;
6160        }
6161
6162        // Events
6163        let observing_model = cx.add_model(|_| Model);
6164        let observed_model = cx.add_model(|_| Model);
6165
6166        let events = Rc::new(RefCell::new(Vec::new()));
6167
6168        observing_model.update(cx, |_, cx| {
6169            let events = events.clone();
6170            let subscription = Rc::new(RefCell::new(None));
6171            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
6172                let subscription = subscription.clone();
6173                move |_, _, e, _| {
6174                    subscription.borrow_mut().take();
6175                    events.borrow_mut().push(*e);
6176                }
6177            }));
6178        });
6179
6180        observed_model.update(cx, |_, cx| {
6181            cx.emit(1);
6182            cx.emit(2);
6183        });
6184
6185        assert_eq!(*events.borrow(), [1]);
6186
6187        // Global Events
6188        #[derive(Clone, Debug, Eq, PartialEq)]
6189        struct GlobalEvent(u64);
6190
6191        let events = Rc::new(RefCell::new(Vec::new()));
6192
6193        {
6194            let events = events.clone();
6195            let subscription = Rc::new(RefCell::new(None));
6196            *subscription.borrow_mut() = Some(cx.subscribe_global({
6197                let subscription = subscription.clone();
6198                move |e: &GlobalEvent, _| {
6199                    subscription.borrow_mut().take();
6200                    events.borrow_mut().push(e.clone());
6201                }
6202            }));
6203        }
6204
6205        cx.update(|cx| {
6206            cx.emit_global(GlobalEvent(1));
6207            cx.emit_global(GlobalEvent(2));
6208        });
6209
6210        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
6211
6212        // Model Observation
6213        let observing_model = cx.add_model(|_| Model);
6214        let observed_model = cx.add_model(|_| Model);
6215
6216        let observation_count = Rc::new(RefCell::new(0));
6217
6218        observing_model.update(cx, |_, cx| {
6219            let observation_count = observation_count.clone();
6220            let subscription = Rc::new(RefCell::new(None));
6221            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
6222                let subscription = subscription.clone();
6223                move |_, _, _| {
6224                    subscription.borrow_mut().take();
6225                    *observation_count.borrow_mut() += 1;
6226                }
6227            }));
6228        });
6229
6230        observed_model.update(cx, |_, cx| {
6231            cx.notify();
6232        });
6233
6234        observed_model.update(cx, |_, cx| {
6235            cx.notify();
6236        });
6237
6238        assert_eq!(*observation_count.borrow(), 1);
6239
6240        // View Observation
6241        struct View;
6242
6243        impl Entity for View {
6244            type Event = ();
6245        }
6246
6247        impl super::View for View {
6248            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6249                Empty::new().boxed()
6250            }
6251
6252            fn ui_name() -> &'static str {
6253                "View"
6254            }
6255        }
6256
6257        let (_, root_view) = cx.add_window(Default::default(), |_| View);
6258        let observing_view = cx.add_view(&root_view, |_| View);
6259        let observed_view = cx.add_view(&root_view, |_| View);
6260
6261        let observation_count = Rc::new(RefCell::new(0));
6262        observing_view.update(cx, |_, cx| {
6263            let observation_count = observation_count.clone();
6264            let subscription = Rc::new(RefCell::new(None));
6265            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
6266                let subscription = subscription.clone();
6267                move |_, _, _| {
6268                    subscription.borrow_mut().take();
6269                    *observation_count.borrow_mut() += 1;
6270                }
6271            }));
6272        });
6273
6274        observed_view.update(cx, |_, cx| {
6275            cx.notify();
6276        });
6277
6278        observed_view.update(cx, |_, cx| {
6279            cx.notify();
6280        });
6281
6282        assert_eq!(*observation_count.borrow(), 1);
6283
6284        // Global Observation
6285        let observation_count = Rc::new(RefCell::new(0));
6286        let subscription = Rc::new(RefCell::new(None));
6287        *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
6288            let observation_count = observation_count.clone();
6289            let subscription = subscription.clone();
6290            move |_| {
6291                subscription.borrow_mut().take();
6292                *observation_count.borrow_mut() += 1;
6293            }
6294        }));
6295
6296        cx.default_global::<()>();
6297        cx.set_global(());
6298        assert_eq!(*observation_count.borrow(), 1);
6299    }
6300
6301    #[crate::test(self)]
6302    fn test_focus(cx: &mut MutableAppContext) {
6303        struct View {
6304            name: String,
6305            events: Arc<Mutex<Vec<String>>>,
6306        }
6307
6308        impl Entity for View {
6309            type Event = ();
6310        }
6311
6312        impl super::View for View {
6313            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6314                Empty::new().boxed()
6315            }
6316
6317            fn ui_name() -> &'static str {
6318                "View"
6319            }
6320
6321            fn on_focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
6322                if cx.handle().id() == focused.id() {
6323                    self.events.lock().push(format!("{} focused", &self.name));
6324                }
6325            }
6326
6327            fn on_focus_out(&mut self, blurred: AnyViewHandle, cx: &mut ViewContext<Self>) {
6328                if cx.handle().id() == blurred.id() {
6329                    self.events.lock().push(format!("{} blurred", &self.name));
6330                }
6331            }
6332        }
6333
6334        let view_events: Arc<Mutex<Vec<String>>> = Default::default();
6335        let (_, view_1) = cx.add_window(Default::default(), |_| View {
6336            events: view_events.clone(),
6337            name: "view 1".to_string(),
6338        });
6339        let view_2 = cx.add_view(&view_1, |_| View {
6340            events: view_events.clone(),
6341            name: "view 2".to_string(),
6342        });
6343
6344        let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
6345        view_1.update(cx, |_, cx| {
6346            cx.observe_focus(&view_2, {
6347                let observed_events = observed_events.clone();
6348                move |this, view, focused, cx| {
6349                    let label = if focused { "focus" } else { "blur" };
6350                    observed_events.lock().push(format!(
6351                        "{} observed {}'s {}",
6352                        this.name,
6353                        view.read(cx).name,
6354                        label
6355                    ))
6356                }
6357            })
6358            .detach();
6359        });
6360        view_2.update(cx, |_, cx| {
6361            cx.observe_focus(&view_1, {
6362                let observed_events = observed_events.clone();
6363                move |this, view, focused, cx| {
6364                    let label = if focused { "focus" } else { "blur" };
6365                    observed_events.lock().push(format!(
6366                        "{} observed {}'s {}",
6367                        this.name,
6368                        view.read(cx).name,
6369                        label
6370                    ))
6371                }
6372            })
6373            .detach();
6374        });
6375        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6376        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6377
6378        view_1.update(cx, |_, cx| {
6379            // Ensure only the latest focus is honored.
6380            cx.focus(&view_2);
6381            cx.focus(&view_1);
6382            cx.focus(&view_2);
6383        });
6384        assert_eq!(
6385            mem::take(&mut *view_events.lock()),
6386            ["view 1 blurred", "view 2 focused"],
6387        );
6388        assert_eq!(
6389            mem::take(&mut *observed_events.lock()),
6390            [
6391                "view 2 observed view 1's blur",
6392                "view 1 observed view 2's focus"
6393            ]
6394        );
6395
6396        view_1.update(cx, |_, cx| cx.focus(&view_1));
6397        assert_eq!(
6398            mem::take(&mut *view_events.lock()),
6399            ["view 2 blurred", "view 1 focused"],
6400        );
6401        assert_eq!(
6402            mem::take(&mut *observed_events.lock()),
6403            [
6404                "view 1 observed view 2's blur",
6405                "view 2 observed view 1's focus"
6406            ]
6407        );
6408
6409        view_1.update(cx, |_, cx| cx.focus(&view_2));
6410        assert_eq!(
6411            mem::take(&mut *view_events.lock()),
6412            ["view 1 blurred", "view 2 focused"],
6413        );
6414        assert_eq!(
6415            mem::take(&mut *observed_events.lock()),
6416            [
6417                "view 2 observed view 1's blur",
6418                "view 1 observed view 2's focus"
6419            ]
6420        );
6421
6422        view_1.update(cx, |_, _| drop(view_2));
6423        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6424        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6425    }
6426
6427    #[crate::test(self)]
6428    fn test_deserialize_actions(cx: &mut MutableAppContext) {
6429        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6430        pub struct ComplexAction {
6431            arg: String,
6432            count: usize,
6433        }
6434
6435        actions!(test::something, [SimpleAction]);
6436        impl_actions!(test::something, [ComplexAction]);
6437
6438        cx.add_global_action(move |_: &SimpleAction, _: &mut MutableAppContext| {});
6439        cx.add_global_action(move |_: &ComplexAction, _: &mut MutableAppContext| {});
6440
6441        let action1 = cx
6442            .deserialize_action(
6443                "test::something::ComplexAction",
6444                Some(r#"{"arg": "a", "count": 5}"#),
6445            )
6446            .unwrap();
6447        let action2 = cx
6448            .deserialize_action("test::something::SimpleAction", None)
6449            .unwrap();
6450        assert_eq!(
6451            action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
6452            &ComplexAction {
6453                arg: "a".to_string(),
6454                count: 5,
6455            }
6456        );
6457        assert_eq!(
6458            action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
6459            &SimpleAction
6460        );
6461    }
6462
6463    #[crate::test(self)]
6464    fn test_dispatch_action(cx: &mut MutableAppContext) {
6465        struct ViewA {
6466            id: usize,
6467        }
6468
6469        impl Entity for ViewA {
6470            type Event = ();
6471        }
6472
6473        impl View for ViewA {
6474            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6475                Empty::new().boxed()
6476            }
6477
6478            fn ui_name() -> &'static str {
6479                "View"
6480            }
6481        }
6482
6483        struct ViewB {
6484            id: usize,
6485        }
6486
6487        impl Entity for ViewB {
6488            type Event = ();
6489        }
6490
6491        impl View for ViewB {
6492            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6493                Empty::new().boxed()
6494            }
6495
6496            fn ui_name() -> &'static str {
6497                "View"
6498            }
6499        }
6500
6501        #[derive(Clone, Default, Deserialize, PartialEq)]
6502        pub struct Action(pub String);
6503
6504        impl_actions!(test, [Action]);
6505
6506        let actions = Rc::new(RefCell::new(Vec::new()));
6507
6508        cx.add_global_action({
6509            let actions = actions.clone();
6510            move |_: &Action, _: &mut MutableAppContext| {
6511                actions.borrow_mut().push("global".to_string());
6512            }
6513        });
6514
6515        cx.add_action({
6516            let actions = actions.clone();
6517            move |view: &mut ViewA, action: &Action, cx| {
6518                assert_eq!(action.0, "bar");
6519                cx.propagate_action();
6520                actions.borrow_mut().push(format!("{} a", view.id));
6521            }
6522        });
6523
6524        cx.add_action({
6525            let actions = actions.clone();
6526            move |view: &mut ViewA, _: &Action, cx| {
6527                if view.id != 1 {
6528                    cx.add_view(|cx| {
6529                        cx.propagate_action(); // Still works on a nested ViewContext
6530                        ViewB { id: 5 }
6531                    });
6532                }
6533                actions.borrow_mut().push(format!("{} b", view.id));
6534            }
6535        });
6536
6537        cx.add_action({
6538            let actions = actions.clone();
6539            move |view: &mut ViewB, _: &Action, cx| {
6540                cx.propagate_action();
6541                actions.borrow_mut().push(format!("{} c", view.id));
6542            }
6543        });
6544
6545        cx.add_action({
6546            let actions = actions.clone();
6547            move |view: &mut ViewB, _: &Action, cx| {
6548                cx.propagate_action();
6549                actions.borrow_mut().push(format!("{} d", view.id));
6550            }
6551        });
6552
6553        cx.capture_action({
6554            let actions = actions.clone();
6555            move |view: &mut ViewA, _: &Action, cx| {
6556                cx.propagate_action();
6557                actions.borrow_mut().push(format!("{} capture", view.id));
6558            }
6559        });
6560
6561        let observed_actions = Rc::new(RefCell::new(Vec::new()));
6562        cx.observe_actions({
6563            let observed_actions = observed_actions.clone();
6564            move |action_id, _| observed_actions.borrow_mut().push(action_id)
6565        })
6566        .detach();
6567
6568        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
6569        let view_2 = cx.add_view(&view_1, |_| ViewB { id: 2 });
6570        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
6571        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
6572
6573        cx.handle_dispatch_action_from_effect(
6574            window_id,
6575            Some(view_4.id()),
6576            &Action("bar".to_string()),
6577        );
6578
6579        assert_eq!(
6580            *actions.borrow(),
6581            vec![
6582                "1 capture",
6583                "3 capture",
6584                "4 d",
6585                "4 c",
6586                "3 b",
6587                "3 a",
6588                "2 d",
6589                "2 c",
6590                "1 b"
6591            ]
6592        );
6593        assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
6594
6595        // Remove view_1, which doesn't propagate the action
6596
6597        let (window_id, view_2) = cx.add_window(Default::default(), |_| ViewB { id: 2 });
6598        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
6599        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
6600
6601        actions.borrow_mut().clear();
6602        cx.handle_dispatch_action_from_effect(
6603            window_id,
6604            Some(view_4.id()),
6605            &Action("bar".to_string()),
6606        );
6607
6608        assert_eq!(
6609            *actions.borrow(),
6610            vec![
6611                "3 capture",
6612                "4 d",
6613                "4 c",
6614                "3 b",
6615                "3 a",
6616                "2 d",
6617                "2 c",
6618                "global"
6619            ]
6620        );
6621        assert_eq!(
6622            *observed_actions.borrow(),
6623            [Action::default().id(), Action::default().id()]
6624        );
6625    }
6626
6627    #[crate::test(self)]
6628    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
6629        #[derive(Clone, Deserialize, PartialEq)]
6630        pub struct Action(String);
6631
6632        impl_actions!(test, [Action]);
6633
6634        struct View {
6635            id: usize,
6636            keymap_context: keymap::Context,
6637        }
6638
6639        impl Entity for View {
6640            type Event = ();
6641        }
6642
6643        impl super::View for View {
6644            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6645                Empty::new().boxed()
6646            }
6647
6648            fn ui_name() -> &'static str {
6649                "View"
6650            }
6651
6652            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
6653                self.keymap_context.clone()
6654            }
6655        }
6656
6657        impl View {
6658            fn new(id: usize) -> Self {
6659                View {
6660                    id,
6661                    keymap_context: keymap::Context::default(),
6662                }
6663            }
6664        }
6665
6666        let mut view_1 = View::new(1);
6667        let mut view_2 = View::new(2);
6668        let mut view_3 = View::new(3);
6669        view_1.keymap_context.set.insert("a".into());
6670        view_2.keymap_context.set.insert("a".into());
6671        view_2.keymap_context.set.insert("b".into());
6672        view_3.keymap_context.set.insert("a".into());
6673        view_3.keymap_context.set.insert("b".into());
6674        view_3.keymap_context.set.insert("c".into());
6675
6676        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
6677        let view_2 = cx.add_view(&view_1, |_| view_2);
6678        let _view_3 = cx.add_view(&view_2, |cx| {
6679            cx.focus_self();
6680            view_3
6681        });
6682
6683        // This keymap's only binding dispatches an action on view 2 because that view will have
6684        // "a" and "b" in its context, but not "c".
6685        cx.add_bindings(vec![keymap::Binding::new(
6686            "a",
6687            Action("a".to_string()),
6688            Some("a && b && !c"),
6689        )]);
6690
6691        cx.add_bindings(vec![keymap::Binding::new(
6692            "b",
6693            Action("b".to_string()),
6694            None,
6695        )]);
6696
6697        let actions = Rc::new(RefCell::new(Vec::new()));
6698        cx.add_action({
6699            let actions = actions.clone();
6700            move |view: &mut View, action: &Action, cx| {
6701                if action.0 == "a" {
6702                    actions.borrow_mut().push(format!("{} a", view.id));
6703                } else {
6704                    actions
6705                        .borrow_mut()
6706                        .push(format!("{} {}", view.id, action.0));
6707                    cx.propagate_action();
6708                }
6709            }
6710        });
6711
6712        cx.add_global_action({
6713            let actions = actions.clone();
6714            move |action: &Action, _| {
6715                actions.borrow_mut().push(format!("global {}", action.0));
6716            }
6717        });
6718
6719        cx.dispatch_keystroke(window_id, &Keystroke::parse("a").unwrap());
6720
6721        assert_eq!(&*actions.borrow(), &["2 a"]);
6722
6723        actions.borrow_mut().clear();
6724
6725        cx.dispatch_keystroke(window_id, &Keystroke::parse("b").unwrap());
6726
6727        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
6728    }
6729
6730    #[crate::test(self)]
6731    async fn test_model_condition(cx: &mut TestAppContext) {
6732        struct Counter(usize);
6733
6734        impl super::Entity for Counter {
6735            type Event = ();
6736        }
6737
6738        impl Counter {
6739            fn inc(&mut self, cx: &mut ModelContext<Self>) {
6740                self.0 += 1;
6741                cx.notify();
6742            }
6743        }
6744
6745        let model = cx.add_model(|_| Counter(0));
6746
6747        let condition1 = model.condition(cx, |model, _| model.0 == 2);
6748        let condition2 = model.condition(cx, |model, _| model.0 == 3);
6749        smol::pin!(condition1, condition2);
6750
6751        model.update(cx, |model, cx| model.inc(cx));
6752        assert_eq!(poll_once(&mut condition1).await, None);
6753        assert_eq!(poll_once(&mut condition2).await, None);
6754
6755        model.update(cx, |model, cx| model.inc(cx));
6756        assert_eq!(poll_once(&mut condition1).await, Some(()));
6757        assert_eq!(poll_once(&mut condition2).await, None);
6758
6759        model.update(cx, |model, cx| model.inc(cx));
6760        assert_eq!(poll_once(&mut condition2).await, Some(()));
6761
6762        model.update(cx, |_, cx| cx.notify());
6763    }
6764
6765    #[crate::test(self)]
6766    #[should_panic]
6767    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
6768        struct Model;
6769
6770        impl super::Entity for Model {
6771            type Event = ();
6772        }
6773
6774        let model = cx.add_model(|_| Model);
6775        model.condition(cx, |_, _| false).await;
6776    }
6777
6778    #[crate::test(self)]
6779    #[should_panic(expected = "model dropped with pending condition")]
6780    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
6781        struct Model;
6782
6783        impl super::Entity for Model {
6784            type Event = ();
6785        }
6786
6787        let model = cx.add_model(|_| Model);
6788        let condition = model.condition(cx, |_, _| false);
6789        cx.update(|_| drop(model));
6790        condition.await;
6791    }
6792
6793    #[crate::test(self)]
6794    async fn test_view_condition(cx: &mut TestAppContext) {
6795        struct Counter(usize);
6796
6797        impl super::Entity for Counter {
6798            type Event = ();
6799        }
6800
6801        impl super::View for Counter {
6802            fn ui_name() -> &'static str {
6803                "test view"
6804            }
6805
6806            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6807                Empty::new().boxed()
6808            }
6809        }
6810
6811        impl Counter {
6812            fn inc(&mut self, cx: &mut ViewContext<Self>) {
6813                self.0 += 1;
6814                cx.notify();
6815            }
6816        }
6817
6818        let (_, view) = cx.add_window(|_| Counter(0));
6819
6820        let condition1 = view.condition(cx, |view, _| view.0 == 2);
6821        let condition2 = view.condition(cx, |view, _| view.0 == 3);
6822        smol::pin!(condition1, condition2);
6823
6824        view.update(cx, |view, cx| view.inc(cx));
6825        assert_eq!(poll_once(&mut condition1).await, None);
6826        assert_eq!(poll_once(&mut condition2).await, None);
6827
6828        view.update(cx, |view, cx| view.inc(cx));
6829        assert_eq!(poll_once(&mut condition1).await, Some(()));
6830        assert_eq!(poll_once(&mut condition2).await, None);
6831
6832        view.update(cx, |view, cx| view.inc(cx));
6833        assert_eq!(poll_once(&mut condition2).await, Some(()));
6834        view.update(cx, |_, cx| cx.notify());
6835    }
6836
6837    #[crate::test(self)]
6838    #[should_panic]
6839    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
6840        struct View;
6841
6842        impl super::Entity for View {
6843            type Event = ();
6844        }
6845
6846        impl super::View for View {
6847            fn ui_name() -> &'static str {
6848                "test view"
6849            }
6850
6851            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6852                Empty::new().boxed()
6853            }
6854        }
6855
6856        let (_, view) = cx.add_window(|_| View);
6857        view.condition(cx, |_, _| false).await;
6858    }
6859
6860    #[crate::test(self)]
6861    #[should_panic(expected = "view dropped with pending condition")]
6862    async fn test_view_condition_panic_on_drop(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 (_, root_view) = cx.add_window(|_| View);
6880        let view = cx.add_view(&root_view, |_| View);
6881
6882        let condition = view.condition(cx, |_, _| false);
6883        cx.update(|_| drop(view));
6884        condition.await;
6885    }
6886
6887    #[crate::test(self)]
6888    fn test_refresh_windows(cx: &mut MutableAppContext) {
6889        struct View(usize);
6890
6891        impl super::Entity for View {
6892            type Event = ();
6893        }
6894
6895        impl super::View for View {
6896            fn ui_name() -> &'static str {
6897                "test view"
6898            }
6899
6900            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6901                Empty::new().named(format!("render count: {}", post_inc(&mut self.0)))
6902            }
6903        }
6904
6905        let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
6906        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
6907
6908        assert_eq!(
6909            presenter.borrow().rendered_views[&root_view.id()].name(),
6910            Some("render count: 0")
6911        );
6912
6913        let view = cx.add_view(&root_view, |cx| {
6914            cx.refresh_windows();
6915            View(0)
6916        });
6917
6918        assert_eq!(
6919            presenter.borrow().rendered_views[&root_view.id()].name(),
6920            Some("render count: 1")
6921        );
6922        assert_eq!(
6923            presenter.borrow().rendered_views[&view.id()].name(),
6924            Some("render count: 0")
6925        );
6926
6927        cx.update(|cx| cx.refresh_windows());
6928        assert_eq!(
6929            presenter.borrow().rendered_views[&root_view.id()].name(),
6930            Some("render count: 2")
6931        );
6932        assert_eq!(
6933            presenter.borrow().rendered_views[&view.id()].name(),
6934            Some("render count: 1")
6935        );
6936
6937        cx.update(|cx| {
6938            cx.refresh_windows();
6939            drop(view);
6940        });
6941        assert_eq!(
6942            presenter.borrow().rendered_views[&root_view.id()].name(),
6943            Some("render count: 3")
6944        );
6945        assert_eq!(presenter.borrow().rendered_views.len(), 1);
6946    }
6947
6948    #[crate::test(self)]
6949    async fn test_window_activation(cx: &mut TestAppContext) {
6950        struct View(&'static str);
6951
6952        impl super::Entity for View {
6953            type Event = ();
6954        }
6955
6956        impl super::View for View {
6957            fn ui_name() -> &'static str {
6958                "test view"
6959            }
6960
6961            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6962                Empty::new().boxed()
6963            }
6964        }
6965
6966        let events = Rc::new(RefCell::new(Vec::new()));
6967        let (window_1, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6968            cx.observe_window_activation({
6969                let events = events.clone();
6970                move |this, active, _| events.borrow_mut().push((this.0, active))
6971            })
6972            .detach();
6973            View("window 1")
6974        });
6975        assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
6976
6977        let (window_2, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6978            cx.observe_window_activation({
6979                let events = events.clone();
6980                move |this, active, _| events.borrow_mut().push((this.0, active))
6981            })
6982            .detach();
6983            View("window 2")
6984        });
6985        assert_eq!(
6986            mem::take(&mut *events.borrow_mut()),
6987            [("window 1", false), ("window 2", true)]
6988        );
6989
6990        let (window_3, _) = 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 3")
6997        });
6998        assert_eq!(
6999            mem::take(&mut *events.borrow_mut()),
7000            [("window 2", false), ("window 3", true)]
7001        );
7002
7003        cx.simulate_window_activation(Some(window_2));
7004        assert_eq!(
7005            mem::take(&mut *events.borrow_mut()),
7006            [("window 3", false), ("window 2", true)]
7007        );
7008
7009        cx.simulate_window_activation(Some(window_1));
7010        assert_eq!(
7011            mem::take(&mut *events.borrow_mut()),
7012            [("window 2", false), ("window 1", true)]
7013        );
7014
7015        cx.simulate_window_activation(Some(window_3));
7016        assert_eq!(
7017            mem::take(&mut *events.borrow_mut()),
7018            [("window 1", false), ("window 3", true)]
7019        );
7020
7021        cx.simulate_window_activation(Some(window_3));
7022        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
7023    }
7024}