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