app.rs

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