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