app.rs

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