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 pathfinder_geometry::vector::Vector2F;
  25use postage::oneshot;
  26use smallvec::SmallVec;
  27use smol::prelude::*;
  28
  29pub use action::*;
  30use callback_collection::{CallbackCollection, Mapping};
  31use collections::{btree_map, hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque};
  32use keymap::MatchResult;
  33use platform::Event;
  34#[cfg(any(test, feature = "test-support"))]
  35pub use test_app_context::{ContextHandle, TestAppContext};
  36
  37use crate::{
  38    elements::ElementBox,
  39    executor::{self, Task},
  40    geometry::rect::RectF,
  41    keymap::{self, Binding, Keystroke},
  42    platform::{self, KeyDownEvent, Platform, PromptLevel, WindowOptions},
  43    presenter::Presenter,
  44    util::post_inc,
  45    Appearance, AssetCache, AssetSource, ClipboardItem, FontCache, InputHandler, KeyUpEvent,
  46    ModifiersChangedEvent, MouseButton, MouseRegionId, PathPromptOptions, TextLayoutCache,
  47};
  48
  49pub trait Entity: 'static {
  50    type Event;
  51
  52    fn release(&mut self, _: &mut MutableAppContext) {}
  53    fn app_will_quit(
  54        &mut self,
  55        _: &mut MutableAppContext,
  56    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
  57        None
  58    }
  59}
  60
  61pub trait View: Entity + Sized {
  62    fn ui_name() -> &'static str;
  63    fn render(&mut self, cx: &mut RenderContext<'_, Self>) -> ElementBox;
  64    fn focus_in(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {}
  65    fn focus_out(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {}
  66    fn key_down(&mut self, _: &KeyDownEvent, _: &mut ViewContext<Self>) -> bool {
  67        false
  68    }
  69    fn key_up(&mut self, _: &KeyUpEvent, _: &mut ViewContext<Self>) -> bool {
  70        false
  71    }
  72    fn modifiers_changed(&mut self, _: &ModifiersChangedEvent, _: &mut ViewContext<Self>) -> bool {
  73        false
  74    }
  75
  76    fn keymap_context(&self, _: &AppContext) -> keymap::Context {
  77        Self::default_keymap_context()
  78    }
  79    fn default_keymap_context() -> keymap::Context {
  80        let mut cx = keymap::Context::default();
  81        cx.set.insert(Self::ui_name().into());
  82        cx
  83    }
  84    fn debug_json(&self, _: &AppContext) -> serde_json::Value {
  85        serde_json::Value::Null
  86    }
  87
  88    fn text_for_range(&self, _: Range<usize>, _: &AppContext) -> Option<String> {
  89        None
  90    }
  91    fn selected_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
  92        None
  93    }
  94    fn marked_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
  95        None
  96    }
  97    fn unmark_text(&mut self, _: &mut ViewContext<Self>) {}
  98    fn replace_text_in_range(
  99        &mut self,
 100        _: Option<Range<usize>>,
 101        _: &str,
 102        _: &mut ViewContext<Self>,
 103    ) {
 104    }
 105    fn replace_and_mark_text_in_range(
 106        &mut self,
 107        _: Option<Range<usize>>,
 108        _: &str,
 109        _: Option<Range<usize>>,
 110        _: &mut ViewContext<Self>,
 111    ) {
 112    }
 113}
 114
 115pub trait ReadModel {
 116    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T;
 117}
 118
 119pub trait ReadModelWith {
 120    fn read_model_with<E: Entity, T>(
 121        &self,
 122        handle: &ModelHandle<E>,
 123        read: &mut dyn FnMut(&E, &AppContext) -> T,
 124    ) -> T;
 125}
 126
 127pub trait UpdateModel {
 128    fn update_model<T: Entity, O>(
 129        &mut self,
 130        handle: &ModelHandle<T>,
 131        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
 132    ) -> O;
 133}
 134
 135pub trait UpgradeModelHandle {
 136    fn upgrade_model_handle<T: Entity>(
 137        &self,
 138        handle: &WeakModelHandle<T>,
 139    ) -> Option<ModelHandle<T>>;
 140
 141    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool;
 142
 143    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle>;
 144}
 145
 146pub trait UpgradeViewHandle {
 147    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>>;
 148
 149    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle>;
 150}
 151
 152pub trait ReadView {
 153    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T;
 154}
 155
 156pub trait ReadViewWith {
 157    fn read_view_with<V, T>(
 158        &self,
 159        handle: &ViewHandle<V>,
 160        read: &mut dyn FnMut(&V, &AppContext) -> T,
 161    ) -> T
 162    where
 163        V: View;
 164}
 165
 166pub trait UpdateView {
 167    fn update_view<T, S>(
 168        &mut self,
 169        handle: &ViewHandle<T>,
 170        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 171    ) -> S
 172    where
 173        T: View;
 174}
 175
 176pub struct Menu<'a> {
 177    pub name: &'a str,
 178    pub items: Vec<MenuItem<'a>>,
 179}
 180
 181pub enum MenuItem<'a> {
 182    Separator,
 183    Submenu(Menu<'a>),
 184    Action {
 185        name: &'a str,
 186        action: Box<dyn Action>,
 187    },
 188}
 189
 190#[derive(Clone)]
 191pub struct App(Rc<RefCell<MutableAppContext>>);
 192
 193#[derive(Clone)]
 194pub struct AsyncAppContext(Rc<RefCell<MutableAppContext>>);
 195
 196pub struct WindowInputHandler {
 197    app: Rc<RefCell<MutableAppContext>>,
 198    window_id: usize,
 199}
 200
 201impl App {
 202    pub fn new(asset_source: impl AssetSource) -> Result<Self> {
 203        let platform = platform::current::platform();
 204        let foreground_platform = platform::current::foreground_platform();
 205        let foreground = Rc::new(executor::Foreground::platform(platform.dispatcher())?);
 206        let app = Self(Rc::new(RefCell::new(MutableAppContext::new(
 207            foreground,
 208            Arc::new(executor::Background::new()),
 209            platform.clone(),
 210            foreground_platform.clone(),
 211            Arc::new(FontCache::new(platform.fonts())),
 212            Default::default(),
 213            asset_source,
 214        ))));
 215
 216        foreground_platform.on_quit(Box::new({
 217            let cx = app.0.clone();
 218            move || {
 219                cx.borrow_mut().quit();
 220            }
 221        }));
 222        foreground_platform.on_will_open_menu(Box::new({
 223            let cx = app.0.clone();
 224            move || {
 225                let mut cx = cx.borrow_mut();
 226                cx.keystroke_matcher.clear_pending();
 227            }
 228        }));
 229        foreground_platform.on_validate_menu_command(Box::new({
 230            let cx = app.0.clone();
 231            move |action| {
 232                let cx = cx.borrow_mut();
 233                !cx.keystroke_matcher.has_pending_keystrokes() && cx.is_action_available(action)
 234            }
 235        }));
 236        foreground_platform.on_menu_command(Box::new({
 237            let cx = app.0.clone();
 238            move |action| {
 239                let mut cx = cx.borrow_mut();
 240                if let Some(key_window_id) = cx.cx.platform.key_window_id() {
 241                    if let Some(view_id) = cx.focused_view_id(key_window_id) {
 242                        cx.handle_dispatch_action_from_effect(key_window_id, Some(view_id), action);
 243                        return;
 244                    }
 245                }
 246                cx.dispatch_global_action_any(action);
 247            }
 248        }));
 249
 250        app.0.borrow_mut().weak_self = Some(Rc::downgrade(&app.0));
 251        Ok(app)
 252    }
 253
 254    pub fn background(&self) -> Arc<executor::Background> {
 255        self.0.borrow().background().clone()
 256    }
 257
 258    pub fn on_become_active<F>(self, mut callback: F) -> Self
 259    where
 260        F: 'static + FnMut(&mut MutableAppContext),
 261    {
 262        let cx = self.0.clone();
 263        self.0
 264            .borrow_mut()
 265            .foreground_platform
 266            .on_become_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 267        self
 268    }
 269
 270    pub fn on_resign_active<F>(self, mut callback: F) -> Self
 271    where
 272        F: 'static + FnMut(&mut MutableAppContext),
 273    {
 274        let cx = self.0.clone();
 275        self.0
 276            .borrow_mut()
 277            .foreground_platform
 278            .on_resign_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 279        self
 280    }
 281
 282    pub fn on_quit<F>(&mut self, mut callback: F) -> &mut Self
 283    where
 284        F: 'static + FnMut(&mut MutableAppContext),
 285    {
 286        let cx = self.0.clone();
 287        self.0
 288            .borrow_mut()
 289            .foreground_platform
 290            .on_quit(Box::new(move || callback(&mut *cx.borrow_mut())));
 291        self
 292    }
 293
 294    pub fn on_event<F>(&mut self, mut callback: F) -> &mut Self
 295    where
 296        F: 'static + FnMut(Event, &mut MutableAppContext) -> bool,
 297    {
 298        let cx = self.0.clone();
 299        self.0
 300            .borrow_mut()
 301            .foreground_platform
 302            .on_event(Box::new(move |event| {
 303                callback(event, &mut *cx.borrow_mut())
 304            }));
 305        self
 306    }
 307
 308    pub fn on_open_urls<F>(&mut self, mut callback: F) -> &mut Self
 309    where
 310        F: 'static + FnMut(Vec<String>, &mut MutableAppContext),
 311    {
 312        let cx = self.0.clone();
 313        self.0
 314            .borrow_mut()
 315            .foreground_platform
 316            .on_open_urls(Box::new(move |paths| {
 317                callback(paths, &mut *cx.borrow_mut())
 318            }));
 319        self
 320    }
 321
 322    pub fn run<F>(self, on_finish_launching: F)
 323    where
 324        F: 'static + FnOnce(&mut MutableAppContext),
 325    {
 326        let platform = self.0.borrow().foreground_platform.clone();
 327        platform.run(Box::new(move || {
 328            let mut cx = self.0.borrow_mut();
 329            let cx = &mut *cx;
 330            crate::views::init(cx);
 331            on_finish_launching(cx);
 332        }))
 333    }
 334
 335    pub fn platform(&self) -> Arc<dyn Platform> {
 336        self.0.borrow().platform()
 337    }
 338
 339    pub fn font_cache(&self) -> Arc<FontCache> {
 340        self.0.borrow().cx.font_cache.clone()
 341    }
 342
 343    fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 344        let mut state = self.0.borrow_mut();
 345        let result = state.update(callback);
 346        state.pending_notifications.clear();
 347        result
 348    }
 349}
 350
 351impl WindowInputHandler {
 352    fn read_focused_view<T, F>(&self, f: F) -> Option<T>
 353    where
 354        F: FnOnce(&dyn AnyView, &AppContext) -> T,
 355    {
 356        // Input-related application hooks are sometimes called by the OS during
 357        // a call to a window-manipulation API, like prompting the user for file
 358        // paths. In that case, the AppContext will already be borrowed, so any
 359        // InputHandler methods need to fail gracefully.
 360        //
 361        // See https://github.com/zed-industries/feedback/issues/444
 362        let app = self.app.try_borrow().ok()?;
 363
 364        let view_id = app.focused_view_id(self.window_id)?;
 365        let view = app.cx.views.get(&(self.window_id, view_id))?;
 366        let result = f(view.as_ref(), &app);
 367        Some(result)
 368    }
 369
 370    fn update_focused_view<T, F>(&mut self, f: F) -> Option<T>
 371    where
 372        F: FnOnce(usize, usize, &mut dyn AnyView, &mut MutableAppContext) -> T,
 373    {
 374        let mut app = self.app.try_borrow_mut().ok()?;
 375        app.update(|app| {
 376            let view_id = app.focused_view_id(self.window_id)?;
 377            let mut view = app.cx.views.remove(&(self.window_id, view_id))?;
 378            let result = f(self.window_id, view_id, view.as_mut(), &mut *app);
 379            app.cx.views.insert((self.window_id, view_id), view);
 380            Some(result)
 381        })
 382    }
 383}
 384
 385impl InputHandler for WindowInputHandler {
 386    fn text_for_range(&self, range: Range<usize>) -> Option<String> {
 387        self.read_focused_view(|view, cx| view.text_for_range(range.clone(), cx))
 388            .flatten()
 389    }
 390
 391    fn selected_text_range(&self) -> Option<Range<usize>> {
 392        self.read_focused_view(|view, cx| view.selected_text_range(cx))
 393            .flatten()
 394    }
 395
 396    fn replace_text_in_range(&mut self, range: Option<Range<usize>>, text: &str) {
 397        self.update_focused_view(|window_id, view_id, view, cx| {
 398            view.replace_text_in_range(range, text, cx, window_id, view_id);
 399        });
 400    }
 401
 402    fn marked_text_range(&self) -> Option<Range<usize>> {
 403        self.read_focused_view(|view, cx| view.marked_text_range(cx))
 404            .flatten()
 405    }
 406
 407    fn unmark_text(&mut self) {
 408        self.update_focused_view(|window_id, view_id, view, cx| {
 409            view.unmark_text(cx, window_id, view_id);
 410        });
 411    }
 412
 413    fn replace_and_mark_text_in_range(
 414        &mut self,
 415        range: Option<Range<usize>>,
 416        new_text: &str,
 417        new_selected_range: Option<Range<usize>>,
 418    ) {
 419        self.update_focused_view(|window_id, view_id, view, cx| {
 420            view.replace_and_mark_text_in_range(
 421                range,
 422                new_text,
 423                new_selected_range,
 424                cx,
 425                window_id,
 426                view_id,
 427            );
 428        });
 429    }
 430
 431    fn rect_for_range(&self, range_utf16: Range<usize>) -> Option<RectF> {
 432        let app = self.app.borrow();
 433        let (presenter, _) = app.presenters_and_platform_windows.get(&self.window_id)?;
 434        let presenter = presenter.borrow();
 435        presenter.rect_for_text_range(range_utf16, &app)
 436    }
 437}
 438
 439impl AsyncAppContext {
 440    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
 441    where
 442        F: FnOnce(AsyncAppContext) -> Fut,
 443        Fut: 'static + Future<Output = T>,
 444        T: 'static,
 445    {
 446        self.0.borrow().foreground.spawn(f(self.clone()))
 447    }
 448
 449    pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
 450        callback(self.0.borrow().as_ref())
 451    }
 452
 453    pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 454        self.0.borrow_mut().update(callback)
 455    }
 456
 457    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 458    where
 459        T: Entity,
 460        F: FnOnce(&mut ModelContext<T>) -> T,
 461    {
 462        self.update(|cx| cx.add_model(build_model))
 463    }
 464
 465    pub fn add_window<T, F>(
 466        &mut self,
 467        window_options: WindowOptions,
 468        build_root_view: F,
 469    ) -> (usize, ViewHandle<T>)
 470    where
 471        T: View,
 472        F: FnOnce(&mut ViewContext<T>) -> T,
 473    {
 474        self.update(|cx| cx.add_window(window_options, build_root_view))
 475    }
 476
 477    pub fn remove_window(&mut self, window_id: usize) {
 478        self.update(|cx| cx.remove_window(window_id))
 479    }
 480
 481    pub fn activate_window(&mut self, window_id: usize) {
 482        self.update(|cx| cx.activate_window(window_id))
 483    }
 484
 485    pub fn prompt(
 486        &mut self,
 487        window_id: usize,
 488        level: PromptLevel,
 489        msg: &str,
 490        answers: &[&str],
 491    ) -> oneshot::Receiver<usize> {
 492        self.update(|cx| cx.prompt(window_id, level, msg, answers))
 493    }
 494
 495    pub fn platform(&self) -> Arc<dyn Platform> {
 496        self.0.borrow().platform()
 497    }
 498
 499    pub fn foreground(&self) -> Rc<executor::Foreground> {
 500        self.0.borrow().foreground.clone()
 501    }
 502
 503    pub fn background(&self) -> Arc<executor::Background> {
 504        self.0.borrow().cx.background.clone()
 505    }
 506}
 507
 508impl UpdateModel for AsyncAppContext {
 509    fn update_model<E: Entity, O>(
 510        &mut self,
 511        handle: &ModelHandle<E>,
 512        update: &mut dyn FnMut(&mut E, &mut ModelContext<E>) -> O,
 513    ) -> O {
 514        self.0.borrow_mut().update_model(handle, update)
 515    }
 516}
 517
 518impl UpgradeModelHandle for AsyncAppContext {
 519    fn upgrade_model_handle<T: Entity>(
 520        &self,
 521        handle: &WeakModelHandle<T>,
 522    ) -> Option<ModelHandle<T>> {
 523        self.0.borrow().upgrade_model_handle(handle)
 524    }
 525
 526    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
 527        self.0.borrow().model_handle_is_upgradable(handle)
 528    }
 529
 530    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
 531        self.0.borrow().upgrade_any_model_handle(handle)
 532    }
 533}
 534
 535impl UpgradeViewHandle for AsyncAppContext {
 536    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
 537        self.0.borrow_mut().upgrade_view_handle(handle)
 538    }
 539
 540    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
 541        self.0.borrow_mut().upgrade_any_view_handle(handle)
 542    }
 543}
 544
 545impl ReadModelWith for AsyncAppContext {
 546    fn read_model_with<E: Entity, T>(
 547        &self,
 548        handle: &ModelHandle<E>,
 549        read: &mut dyn FnMut(&E, &AppContext) -> T,
 550    ) -> T {
 551        let cx = self.0.borrow();
 552        let cx = cx.as_ref();
 553        read(handle.read(cx), cx)
 554    }
 555}
 556
 557impl UpdateView for AsyncAppContext {
 558    fn update_view<T, S>(
 559        &mut self,
 560        handle: &ViewHandle<T>,
 561        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 562    ) -> S
 563    where
 564        T: View,
 565    {
 566        self.0.borrow_mut().update_view(handle, update)
 567    }
 568}
 569
 570impl ReadViewWith for AsyncAppContext {
 571    fn read_view_with<V, T>(
 572        &self,
 573        handle: &ViewHandle<V>,
 574        read: &mut dyn FnMut(&V, &AppContext) -> T,
 575    ) -> T
 576    where
 577        V: View,
 578    {
 579        let cx = self.0.borrow();
 580        let cx = cx.as_ref();
 581        read(handle.read(cx), cx)
 582    }
 583}
 584
 585type ActionCallback =
 586    dyn FnMut(&mut dyn AnyView, &dyn Action, &mut MutableAppContext, usize, usize);
 587type GlobalActionCallback = dyn FnMut(&dyn Action, &mut MutableAppContext);
 588
 589type SubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut MutableAppContext) -> bool>;
 590type GlobalSubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut MutableAppContext)>;
 591type ObservationCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>;
 592type FocusObservationCallback = Box<dyn FnMut(bool, &mut MutableAppContext) -> bool>;
 593type GlobalObservationCallback = Box<dyn FnMut(&mut MutableAppContext)>;
 594type ReleaseObservationCallback = Box<dyn FnOnce(&dyn Any, &mut MutableAppContext)>;
 595type ActionObservationCallback = Box<dyn FnMut(TypeId, &mut MutableAppContext)>;
 596type WindowActivationCallback = Box<dyn FnMut(bool, &mut MutableAppContext) -> bool>;
 597type WindowFullscreenCallback = Box<dyn FnMut(bool, &mut MutableAppContext) -> bool>;
 598type DeserializeActionCallback = fn(json: &str) -> anyhow::Result<Box<dyn Action>>;
 599type WindowShouldCloseSubscriptionCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>;
 600
 601pub struct MutableAppContext {
 602    weak_self: Option<rc::Weak<RefCell<Self>>>,
 603    foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 604    assets: Arc<AssetCache>,
 605    cx: AppContext,
 606    action_deserializers: HashMap<&'static str, (TypeId, DeserializeActionCallback)>,
 607    capture_actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 608    actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 609    global_actions: HashMap<TypeId, Box<GlobalActionCallback>>,
 610    keystroke_matcher: keymap::Matcher,
 611    next_entity_id: usize,
 612    next_window_id: usize,
 613    next_subscription_id: usize,
 614    frame_count: usize,
 615
 616    focus_observations: CallbackCollection<usize, FocusObservationCallback>,
 617    global_subscriptions: CallbackCollection<TypeId, GlobalSubscriptionCallback>,
 618    global_observations: CallbackCollection<TypeId, GlobalObservationCallback>,
 619    subscriptions: CallbackCollection<usize, SubscriptionCallback>,
 620    observations: CallbackCollection<usize, ObservationCallback>,
 621    window_activation_observations: CallbackCollection<usize, WindowActivationCallback>,
 622    window_fullscreen_observations: CallbackCollection<usize, WindowFullscreenCallback>,
 623
 624    release_observations: Arc<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>,
 625    action_dispatch_observations: Arc<Mutex<BTreeMap<usize, ActionObservationCallback>>>,
 626
 627    #[allow(clippy::type_complexity)]
 628    presenters_and_platform_windows:
 629        HashMap<usize, (Rc<RefCell<Presenter>>, Box<dyn platform::Window>)>,
 630    foreground: Rc<executor::Foreground>,
 631    pending_effects: VecDeque<Effect>,
 632    pending_notifications: HashSet<usize>,
 633    pending_global_notifications: HashSet<TypeId>,
 634    pending_flushes: usize,
 635    flushing_effects: bool,
 636    halt_action_dispatch: bool,
 637}
 638
 639impl MutableAppContext {
 640    fn new(
 641        foreground: Rc<executor::Foreground>,
 642        background: Arc<executor::Background>,
 643        platform: Arc<dyn platform::Platform>,
 644        foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 645        font_cache: Arc<FontCache>,
 646        ref_counts: RefCounts,
 647        asset_source: impl AssetSource,
 648    ) -> Self {
 649        Self {
 650            weak_self: None,
 651            foreground_platform,
 652            assets: Arc::new(AssetCache::new(asset_source)),
 653            cx: AppContext {
 654                models: Default::default(),
 655                views: Default::default(),
 656                parents: Default::default(),
 657                windows: Default::default(),
 658                globals: Default::default(),
 659                element_states: Default::default(),
 660                ref_counts: Arc::new(Mutex::new(ref_counts)),
 661                background,
 662                font_cache,
 663                platform,
 664            },
 665            action_deserializers: Default::default(),
 666            capture_actions: Default::default(),
 667            actions: Default::default(),
 668            global_actions: Default::default(),
 669            keystroke_matcher: keymap::Matcher::default(),
 670            next_entity_id: 0,
 671            next_window_id: 0,
 672            next_subscription_id: 0,
 673            frame_count: 0,
 674            subscriptions: Default::default(),
 675            global_subscriptions: Default::default(),
 676            observations: Default::default(),
 677            focus_observations: Default::default(),
 678            release_observations: Default::default(),
 679            global_observations: Default::default(),
 680            window_activation_observations: Default::default(),
 681            window_fullscreen_observations: Default::default(),
 682            action_dispatch_observations: Default::default(),
 683            presenters_and_platform_windows: Default::default(),
 684            foreground,
 685            pending_effects: VecDeque::new(),
 686            pending_notifications: Default::default(),
 687            pending_global_notifications: Default::default(),
 688            pending_flushes: 0,
 689            flushing_effects: false,
 690            halt_action_dispatch: false,
 691        }
 692    }
 693
 694    pub fn upgrade(&self) -> App {
 695        App(self.weak_self.as_ref().unwrap().upgrade().unwrap())
 696    }
 697
 698    pub fn quit(&mut self) {
 699        let mut futures = Vec::new();
 700        for model_id in self.cx.models.keys().copied().collect::<Vec<_>>() {
 701            let mut model = self.cx.models.remove(&model_id).unwrap();
 702            futures.extend(model.app_will_quit(self));
 703            self.cx.models.insert(model_id, model);
 704        }
 705
 706        for view_id in self.cx.views.keys().copied().collect::<Vec<_>>() {
 707            let mut view = self.cx.views.remove(&view_id).unwrap();
 708            futures.extend(view.app_will_quit(self));
 709            self.cx.views.insert(view_id, view);
 710        }
 711
 712        self.remove_all_windows();
 713
 714        let futures = futures::future::join_all(futures);
 715        if self
 716            .background
 717            .block_with_timeout(Duration::from_millis(100), futures)
 718            .is_err()
 719        {
 720            log::error!("timed out waiting on app_will_quit");
 721        }
 722    }
 723
 724    pub fn remove_all_windows(&mut self) {
 725        for (window_id, _) in self.cx.windows.drain() {
 726            self.presenters_and_platform_windows.remove(&window_id);
 727        }
 728        self.flush_effects();
 729    }
 730
 731    pub fn platform(&self) -> Arc<dyn platform::Platform> {
 732        self.cx.platform.clone()
 733    }
 734
 735    pub fn font_cache(&self) -> &Arc<FontCache> {
 736        &self.cx.font_cache
 737    }
 738
 739    pub fn foreground(&self) -> &Rc<executor::Foreground> {
 740        &self.foreground
 741    }
 742
 743    pub fn background(&self) -> &Arc<executor::Background> {
 744        &self.cx.background
 745    }
 746
 747    pub fn debug_elements(&self, window_id: usize) -> Option<crate::json::Value> {
 748        self.presenters_and_platform_windows
 749            .get(&window_id)
 750            .and_then(|(presenter, _)| presenter.borrow().debug_elements(self))
 751    }
 752
 753    pub fn deserialize_action(
 754        &self,
 755        name: &str,
 756        argument: Option<&str>,
 757    ) -> Result<Box<dyn Action>> {
 758        let callback = self
 759            .action_deserializers
 760            .get(name)
 761            .ok_or_else(|| anyhow!("unknown action {}", name))?
 762            .1;
 763        callback(argument.unwrap_or("{}"))
 764            .with_context(|| format!("invalid data for action {}", name))
 765    }
 766
 767    pub fn add_action<A, V, F>(&mut self, handler: F)
 768    where
 769        A: Action,
 770        V: View,
 771        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
 772    {
 773        self.add_action_internal(handler, false)
 774    }
 775
 776    pub fn capture_action<A, V, F>(&mut self, handler: F)
 777    where
 778        A: Action,
 779        V: View,
 780        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
 781    {
 782        self.add_action_internal(handler, true)
 783    }
 784
 785    fn add_action_internal<A, V, F>(&mut self, mut handler: F, capture: bool)
 786    where
 787        A: Action,
 788        V: View,
 789        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
 790    {
 791        let handler = Box::new(
 792            move |view: &mut dyn AnyView,
 793                  action: &dyn Action,
 794                  cx: &mut MutableAppContext,
 795                  window_id: usize,
 796                  view_id: usize| {
 797                let action = action.as_any().downcast_ref().unwrap();
 798                let mut cx = ViewContext::new(cx, window_id, view_id);
 799                handler(
 800                    view.as_any_mut()
 801                        .downcast_mut()
 802                        .expect("downcast is type safe"),
 803                    action,
 804                    &mut cx,
 805                );
 806            },
 807        );
 808
 809        self.action_deserializers
 810            .entry(A::qualified_name())
 811            .or_insert((TypeId::of::<A>(), A::from_json_str));
 812
 813        let actions = if capture {
 814            &mut self.capture_actions
 815        } else {
 816            &mut self.actions
 817        };
 818
 819        actions
 820            .entry(TypeId::of::<V>())
 821            .or_default()
 822            .entry(TypeId::of::<A>())
 823            .or_default()
 824            .push(handler);
 825    }
 826
 827    pub fn add_async_action<A, V, F>(&mut self, mut handler: F)
 828    where
 829        A: Action,
 830        V: View,
 831        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> Option<Task<Result<()>>>,
 832    {
 833        self.add_action(move |view, action, cx| {
 834            if let Some(task) = handler(view, action, cx) {
 835                task.detach_and_log_err(cx);
 836            }
 837        })
 838    }
 839
 840    pub fn add_global_action<A, F>(&mut self, mut handler: F)
 841    where
 842        A: Action,
 843        F: 'static + FnMut(&A, &mut MutableAppContext),
 844    {
 845        let handler = Box::new(move |action: &dyn Action, cx: &mut MutableAppContext| {
 846            let action = action.as_any().downcast_ref().unwrap();
 847            handler(action, cx);
 848        });
 849
 850        self.action_deserializers
 851            .entry(A::qualified_name())
 852            .or_insert((TypeId::of::<A>(), A::from_json_str));
 853
 854        if self
 855            .global_actions
 856            .insert(TypeId::of::<A>(), handler)
 857            .is_some()
 858        {
 859            panic!(
 860                "registered multiple global handlers for {}",
 861                type_name::<A>()
 862            );
 863        }
 864    }
 865
 866    pub fn window_ids(&self) -> impl Iterator<Item = usize> + '_ {
 867        self.cx.windows.keys().cloned()
 868    }
 869
 870    pub fn activate_window(&self, window_id: usize) {
 871        if let Some((_, window)) = self.presenters_and_platform_windows.get(&window_id) {
 872            window.activate()
 873        }
 874    }
 875
 876    pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
 877        self.cx
 878            .windows
 879            .get(&window_id)
 880            .and_then(|window| window.root_view.clone().downcast::<T>())
 881    }
 882
 883    pub fn window_is_active(&self, window_id: usize) -> bool {
 884        self.cx
 885            .windows
 886            .get(&window_id)
 887            .map_or(false, |window| window.is_active)
 888    }
 889
 890    pub fn window_is_fullscreen(&self, window_id: usize) -> bool {
 891        self.cx
 892            .windows
 893            .get(&window_id)
 894            .map_or(false, |window| window.is_fullscreen)
 895    }
 896
 897    pub fn window_bounds(&self, window_id: usize) -> RectF {
 898        self.presenters_and_platform_windows[&window_id].1.bounds()
 899    }
 900
 901    pub fn render_view(&mut self, params: RenderParams) -> Result<ElementBox> {
 902        let window_id = params.window_id;
 903        let view_id = params.view_id;
 904        let mut view = self
 905            .cx
 906            .views
 907            .remove(&(window_id, view_id))
 908            .ok_or_else(|| anyhow!("view not found"))?;
 909        let element = view.render(params, self);
 910        self.cx.views.insert((window_id, view_id), view);
 911        Ok(element)
 912    }
 913
 914    pub fn render_views(
 915        &mut self,
 916        window_id: usize,
 917        titlebar_height: f32,
 918        appearance: Appearance,
 919    ) -> HashMap<usize, ElementBox> {
 920        self.start_frame();
 921        #[allow(clippy::needless_collect)]
 922        let view_ids = self
 923            .views
 924            .keys()
 925            .filter_map(|(win_id, view_id)| {
 926                if *win_id == window_id {
 927                    Some(*view_id)
 928                } else {
 929                    None
 930                }
 931            })
 932            .collect::<Vec<_>>();
 933
 934        view_ids
 935            .into_iter()
 936            .map(|view_id| {
 937                (
 938                    view_id,
 939                    self.render_view(RenderParams {
 940                        window_id,
 941                        view_id,
 942                        titlebar_height,
 943                        mouse_position: Default::default(),
 944                        hovered_region_ids: Default::default(),
 945                        clicked_region_ids: None,
 946                        refreshing: false,
 947                        appearance,
 948                    })
 949                    .unwrap(),
 950                )
 951            })
 952            .collect()
 953    }
 954
 955    pub(crate) fn start_frame(&mut self) {
 956        self.frame_count += 1;
 957    }
 958
 959    pub fn update<T, F: FnOnce(&mut Self) -> T>(&mut self, callback: F) -> T {
 960        self.pending_flushes += 1;
 961        let result = callback(self);
 962        self.flush_effects();
 963        result
 964    }
 965
 966    pub fn set_menus(&mut self, menus: Vec<Menu>) {
 967        self.foreground_platform
 968            .set_menus(menus, &self.keystroke_matcher);
 969    }
 970
 971    fn show_character_palette(&self, window_id: usize) {
 972        let (_, window) = &self.presenters_and_platform_windows[&window_id];
 973        window.show_character_palette();
 974    }
 975
 976    pub fn minimize_window(&self, window_id: usize) {
 977        let (_, window) = &self.presenters_and_platform_windows[&window_id];
 978        window.minimize();
 979    }
 980
 981    pub fn zoom_window(&self, window_id: usize) {
 982        let (_, window) = &self.presenters_and_platform_windows[&window_id];
 983        window.zoom();
 984    }
 985
 986    pub fn toggle_window_full_screen(&self, window_id: usize) {
 987        let (_, window) = &self.presenters_and_platform_windows[&window_id];
 988        window.toggle_full_screen();
 989    }
 990
 991    fn prompt(
 992        &self,
 993        window_id: usize,
 994        level: PromptLevel,
 995        msg: &str,
 996        answers: &[&str],
 997    ) -> oneshot::Receiver<usize> {
 998        let (_, window) = &self.presenters_and_platform_windows[&window_id];
 999        window.prompt(level, msg, answers)
1000    }
1001
1002    pub fn prompt_for_paths(
1003        &self,
1004        options: PathPromptOptions,
1005    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
1006        self.foreground_platform.prompt_for_paths(options)
1007    }
1008
1009    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
1010        self.foreground_platform.prompt_for_new_path(directory)
1011    }
1012
1013    pub fn emit_global<E: Any>(&mut self, payload: E) {
1014        self.pending_effects.push_back(Effect::GlobalEvent {
1015            payload: Box::new(payload),
1016        });
1017    }
1018
1019    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1020    where
1021        E: Entity,
1022        E::Event: 'static,
1023        H: Handle<E>,
1024        F: 'static + FnMut(H, &E::Event, &mut Self),
1025    {
1026        self.subscribe_internal(handle, move |handle, event, cx| {
1027            callback(handle, event, cx);
1028            true
1029        })
1030    }
1031
1032    pub fn subscribe_global<E, F>(&mut self, mut callback: F) -> Subscription
1033    where
1034        E: Any,
1035        F: 'static + FnMut(&E, &mut Self),
1036    {
1037        let subscription_id = post_inc(&mut self.next_subscription_id);
1038        let type_id = TypeId::of::<E>();
1039        self.pending_effects.push_back(Effect::GlobalSubscription {
1040            type_id,
1041            subscription_id,
1042            callback: Box::new(move |payload, cx| {
1043                let payload = payload.downcast_ref().expect("downcast is type safe");
1044                callback(payload, cx)
1045            }),
1046        });
1047
1048        Subscription::GlobalSubscription {
1049            id: subscription_id,
1050            type_id,
1051            subscriptions: Some(self.global_subscriptions.downgrade()),
1052        }
1053    }
1054
1055    pub fn observe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1056    where
1057        E: Entity,
1058        E::Event: 'static,
1059        H: Handle<E>,
1060        F: 'static + FnMut(H, &mut Self),
1061    {
1062        self.observe_internal(handle, move |handle, cx| {
1063            callback(handle, cx);
1064            true
1065        })
1066    }
1067
1068    pub fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1069    where
1070        E: Entity,
1071        E::Event: 'static,
1072        H: Handle<E>,
1073        F: 'static + FnMut(H, &E::Event, &mut Self) -> bool,
1074    {
1075        let subscription_id = post_inc(&mut self.next_subscription_id);
1076        let emitter = handle.downgrade();
1077        self.pending_effects.push_back(Effect::Subscription {
1078            entity_id: handle.id(),
1079            subscription_id,
1080            callback: Box::new(move |payload, cx| {
1081                if let Some(emitter) = H::upgrade_from(&emitter, cx.as_ref()) {
1082                    let payload = payload.downcast_ref().expect("downcast is type safe");
1083                    callback(emitter, payload, cx)
1084                } else {
1085                    false
1086                }
1087            }),
1088        });
1089        Subscription::Subscription {
1090            id: subscription_id,
1091            entity_id: handle.id(),
1092            subscriptions: Some(self.subscriptions.downgrade()),
1093        }
1094    }
1095
1096    fn observe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1097    where
1098        E: Entity,
1099        E::Event: 'static,
1100        H: Handle<E>,
1101        F: 'static + FnMut(H, &mut Self) -> bool,
1102    {
1103        let subscription_id = post_inc(&mut self.next_subscription_id);
1104        let observed = handle.downgrade();
1105        let entity_id = handle.id();
1106        self.pending_effects.push_back(Effect::Observation {
1107            entity_id,
1108            subscription_id,
1109            callback: Box::new(move |cx| {
1110                if let Some(observed) = H::upgrade_from(&observed, cx) {
1111                    callback(observed, cx)
1112                } else {
1113                    false
1114                }
1115            }),
1116        });
1117        Subscription::Observation {
1118            id: subscription_id,
1119            entity_id,
1120            observations: Some(self.observations.downgrade()),
1121        }
1122    }
1123
1124    fn observe_focus<F, V>(&mut self, handle: &ViewHandle<V>, mut callback: F) -> Subscription
1125    where
1126        F: 'static + FnMut(ViewHandle<V>, bool, &mut MutableAppContext) -> bool,
1127        V: View,
1128    {
1129        let subscription_id = post_inc(&mut self.next_subscription_id);
1130        let observed = handle.downgrade();
1131        let view_id = handle.id();
1132
1133        self.pending_effects.push_back(Effect::FocusObservation {
1134            view_id,
1135            subscription_id,
1136            callback: Box::new(move |focused, cx| {
1137                if let Some(observed) = observed.upgrade(cx) {
1138                    callback(observed, focused, cx)
1139                } else {
1140                    false
1141                }
1142            }),
1143        });
1144
1145        Subscription::FocusObservation {
1146            id: subscription_id,
1147            view_id,
1148            observations: Some(self.focus_observations.downgrade()),
1149        }
1150    }
1151
1152    pub fn observe_global<G, F>(&mut self, mut observe: F) -> Subscription
1153    where
1154        G: Any,
1155        F: 'static + FnMut(&mut MutableAppContext),
1156    {
1157        let type_id = TypeId::of::<G>();
1158        let id = post_inc(&mut self.next_subscription_id);
1159
1160        self.global_observations.add_callback(
1161            type_id,
1162            id,
1163            Box::new(move |cx: &mut MutableAppContext| observe(cx)),
1164        );
1165
1166        Subscription::GlobalObservation {
1167            id,
1168            type_id,
1169            observations: Some(self.global_observations.downgrade()),
1170        }
1171    }
1172
1173    pub fn observe_default_global<G, F>(&mut self, observe: F) -> Subscription
1174    where
1175        G: Any + Default,
1176        F: 'static + FnMut(&mut MutableAppContext),
1177    {
1178        if !self.has_global::<G>() {
1179            self.set_global(G::default());
1180        }
1181        self.observe_global::<G, F>(observe)
1182    }
1183
1184    pub fn observe_release<E, H, F>(&mut self, handle: &H, callback: F) -> Subscription
1185    where
1186        E: Entity,
1187        E::Event: 'static,
1188        H: Handle<E>,
1189        F: 'static + FnOnce(&E, &mut Self),
1190    {
1191        let id = post_inc(&mut self.next_subscription_id);
1192        self.release_observations
1193            .lock()
1194            .entry(handle.id())
1195            .or_default()
1196            .insert(
1197                id,
1198                Box::new(move |released, cx| {
1199                    let released = released.downcast_ref().unwrap();
1200                    callback(released, cx)
1201                }),
1202            );
1203        Subscription::ReleaseObservation {
1204            id,
1205            entity_id: handle.id(),
1206            observations: Some(Arc::downgrade(&self.release_observations)),
1207        }
1208    }
1209
1210    pub fn observe_actions<F>(&mut self, callback: F) -> Subscription
1211    where
1212        F: 'static + FnMut(TypeId, &mut MutableAppContext),
1213    {
1214        let id = post_inc(&mut self.next_subscription_id);
1215        self.action_dispatch_observations
1216            .lock()
1217            .insert(id, Box::new(callback));
1218        Subscription::ActionObservation {
1219            id,
1220            observations: Some(Arc::downgrade(&self.action_dispatch_observations)),
1221        }
1222    }
1223
1224    fn observe_window_activation<F>(&mut self, window_id: usize, callback: F) -> Subscription
1225    where
1226        F: 'static + FnMut(bool, &mut MutableAppContext) -> bool,
1227    {
1228        let subscription_id = post_inc(&mut self.next_subscription_id);
1229        self.pending_effects
1230            .push_back(Effect::WindowActivationObservation {
1231                window_id,
1232                subscription_id,
1233                callback: Box::new(callback),
1234            });
1235        Subscription::WindowActivationObservation {
1236            id: subscription_id,
1237            window_id,
1238            observations: Some(self.window_activation_observations.downgrade()),
1239        }
1240    }
1241
1242    fn observe_fullscreen<F>(&mut self, window_id: usize, callback: F) -> Subscription
1243    where
1244        F: 'static + FnMut(bool, &mut MutableAppContext) -> bool,
1245    {
1246        let subscription_id = post_inc(&mut self.next_subscription_id);
1247        self.pending_effects
1248            .push_back(Effect::WindowFullscreenObservation {
1249                window_id,
1250                subscription_id,
1251                callback: Box::new(callback),
1252            });
1253        Subscription::WindowFullscreenObservation {
1254            id: subscription_id,
1255            window_id,
1256            observations: Some(self.window_activation_observations.downgrade()),
1257        }
1258    }
1259
1260    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut MutableAppContext)) {
1261        self.pending_effects.push_back(Effect::Deferred {
1262            callback: Box::new(callback),
1263            after_window_update: false,
1264        })
1265    }
1266
1267    pub fn after_window_update(&mut self, callback: impl 'static + FnOnce(&mut MutableAppContext)) {
1268        self.pending_effects.push_back(Effect::Deferred {
1269            callback: Box::new(callback),
1270            after_window_update: true,
1271        })
1272    }
1273
1274    pub(crate) fn notify_model(&mut self, model_id: usize) {
1275        if self.pending_notifications.insert(model_id) {
1276            self.pending_effects
1277                .push_back(Effect::ModelNotification { model_id });
1278        }
1279    }
1280
1281    pub(crate) fn notify_view(&mut self, window_id: usize, view_id: usize) {
1282        if self.pending_notifications.insert(view_id) {
1283            self.pending_effects
1284                .push_back(Effect::ViewNotification { window_id, view_id });
1285        }
1286    }
1287
1288    pub(crate) fn notify_global(&mut self, type_id: TypeId) {
1289        if self.pending_global_notifications.insert(type_id) {
1290            self.pending_effects
1291                .push_back(Effect::GlobalNotification { type_id });
1292        }
1293    }
1294
1295    pub(crate) fn name_for_view(&self, window_id: usize, view_id: usize) -> Option<&str> {
1296        self.views
1297            .get(&(window_id, view_id))
1298            .map(|view| view.ui_name())
1299    }
1300
1301    pub fn all_action_names<'a>(&'a self) -> impl Iterator<Item = &'static str> + 'a {
1302        self.action_deserializers.keys().copied()
1303    }
1304
1305    pub fn available_actions(
1306        &self,
1307        window_id: usize,
1308        view_id: usize,
1309    ) -> impl Iterator<Item = (&'static str, Box<dyn Action>, SmallVec<[&Binding; 1]>)> {
1310        let mut action_types: HashSet<_> = self.global_actions.keys().copied().collect();
1311
1312        for view_id in self.ancestors(window_id, view_id) {
1313            if let Some(view) = self.views.get(&(window_id, view_id)) {
1314                let view_type = view.as_any().type_id();
1315                if let Some(actions) = self.actions.get(&view_type) {
1316                    action_types.extend(actions.keys().copied());
1317                }
1318            }
1319        }
1320
1321        self.action_deserializers
1322            .iter()
1323            .filter_map(move |(name, (type_id, deserialize))| {
1324                if action_types.contains(type_id) {
1325                    Some((
1326                        *name,
1327                        deserialize("{}").ok()?,
1328                        self.keystroke_matcher
1329                            .bindings_for_action_type(*type_id)
1330                            .collect(),
1331                    ))
1332                } else {
1333                    None
1334                }
1335            })
1336    }
1337
1338    pub fn is_action_available(&self, action: &dyn Action) -> bool {
1339        let action_type = action.as_any().type_id();
1340        if let Some(window_id) = self.cx.platform.key_window_id() {
1341            if let Some(focused_view_id) = self.focused_view_id(window_id) {
1342                for view_id in self.ancestors(window_id, focused_view_id) {
1343                    if let Some(view) = self.views.get(&(window_id, view_id)) {
1344                        let view_type = view.as_any().type_id();
1345                        if let Some(actions) = self.actions.get(&view_type) {
1346                            if actions.contains_key(&action_type) {
1347                                return true;
1348                            }
1349                        }
1350                    }
1351                }
1352            }
1353        }
1354        self.global_actions.contains_key(&action_type)
1355    }
1356
1357    /// Return keystrokes that would dispatch the given action closest to the focused view, if there are any.
1358    pub(crate) fn keystrokes_for_action(
1359        &self,
1360        window_id: usize,
1361        dispatch_path: &[usize],
1362        action: &dyn Action,
1363    ) -> Option<SmallVec<[Keystroke; 2]>> {
1364        for view_id in dispatch_path.iter().rev() {
1365            let view = self
1366                .cx
1367                .views
1368                .get(&(window_id, *view_id))
1369                .expect("view in responder chain does not exist");
1370            let cx = view.keymap_context(self.as_ref());
1371            let keystrokes = self.keystroke_matcher.keystrokes_for_action(action, &cx);
1372            if keystrokes.is_some() {
1373                return keystrokes;
1374            }
1375        }
1376
1377        None
1378    }
1379
1380    // Traverses the parent tree. Walks down the tree toward the passed
1381    // view calling visit with true. Then walks back up the tree calling visit with false.
1382    // If `visit` returns false this function will immediately return.
1383    // Returns a bool indicating if the traversal was completed early.
1384    fn visit_dispatch_path(
1385        &mut self,
1386        window_id: usize,
1387        view_id: usize,
1388        mut visit: impl FnMut(usize, bool, &mut MutableAppContext) -> bool,
1389    ) -> bool {
1390        // List of view ids from the leaf to the root of the window
1391        let path = self.ancestors(window_id, view_id).collect::<Vec<_>>();
1392
1393        // Walk down from the root to the leaf calling visit with capture_phase = true
1394        for view_id in path.iter().rev() {
1395            if !visit(*view_id, true, self) {
1396                return false;
1397            }
1398        }
1399
1400        // Walk up from the leaf to the root calling visit with capture_phase = false
1401        for view_id in path.iter() {
1402            if !visit(*view_id, false, self) {
1403                return false;
1404            }
1405        }
1406
1407        true
1408    }
1409
1410    // Returns an iterator over all of the view ids from the passed view up to the root of the window
1411    // Includes the passed view itself
1412    fn ancestors(&self, window_id: usize, mut view_id: usize) -> impl Iterator<Item = usize> + '_ {
1413        std::iter::once(view_id)
1414            .into_iter()
1415            .chain(std::iter::from_fn(move || {
1416                if let Some(ParentId::View(parent_id)) = self.parents.get(&(window_id, view_id)) {
1417                    view_id = *parent_id;
1418                    Some(view_id)
1419                } else {
1420                    None
1421                }
1422            }))
1423    }
1424
1425    fn actions_mut(
1426        &mut self,
1427        capture_phase: bool,
1428    ) -> &mut HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>> {
1429        if capture_phase {
1430            &mut self.capture_actions
1431        } else {
1432            &mut self.actions
1433        }
1434    }
1435
1436    pub fn dispatch_global_action<A: Action>(&mut self, action: A) {
1437        self.dispatch_global_action_any(&action);
1438    }
1439
1440    fn dispatch_global_action_any(&mut self, action: &dyn Action) -> bool {
1441        self.update(|this| {
1442            if let Some((name, mut handler)) = this.global_actions.remove_entry(&action.id()) {
1443                handler(action, this);
1444                this.global_actions.insert(name, handler);
1445                true
1446            } else {
1447                false
1448            }
1449        })
1450    }
1451
1452    pub fn add_bindings<T: IntoIterator<Item = keymap::Binding>>(&mut self, bindings: T) {
1453        self.keystroke_matcher.add_bindings(bindings);
1454    }
1455
1456    pub fn clear_bindings(&mut self) {
1457        self.keystroke_matcher.clear_bindings();
1458    }
1459
1460    pub fn dispatch_key_down(&mut self, window_id: usize, event: &KeyDownEvent) -> bool {
1461        if let Some(focused_view_id) = self.focused_view_id(window_id) {
1462            for view_id in self
1463                .ancestors(window_id, focused_view_id)
1464                .collect::<Vec<_>>()
1465            {
1466                if let Some(mut view) = self.cx.views.remove(&(window_id, view_id)) {
1467                    let handled = view.key_down(event, self, window_id, view_id);
1468                    self.cx.views.insert((window_id, view_id), view);
1469                    if handled {
1470                        return true;
1471                    }
1472                } else {
1473                    log::error!("view {} does not exist", view_id)
1474                }
1475            }
1476        }
1477
1478        false
1479    }
1480
1481    pub fn dispatch_key_up(&mut self, window_id: usize, event: &KeyUpEvent) -> bool {
1482        if let Some(focused_view_id) = self.focused_view_id(window_id) {
1483            for view_id in self
1484                .ancestors(window_id, focused_view_id)
1485                .collect::<Vec<_>>()
1486            {
1487                if let Some(mut view) = self.cx.views.remove(&(window_id, view_id)) {
1488                    let handled = view.key_up(event, self, window_id, view_id);
1489                    self.cx.views.insert((window_id, view_id), view);
1490                    if handled {
1491                        return true;
1492                    }
1493                } else {
1494                    log::error!("view {} does not exist", view_id)
1495                }
1496            }
1497        }
1498
1499        false
1500    }
1501
1502    pub fn dispatch_modifiers_changed(
1503        &mut self,
1504        window_id: usize,
1505        event: &ModifiersChangedEvent,
1506    ) -> bool {
1507        if let Some(focused_view_id) = self.focused_view_id(window_id) {
1508            for view_id in self
1509                .ancestors(window_id, focused_view_id)
1510                .collect::<Vec<_>>()
1511            {
1512                if let Some(mut view) = self.cx.views.remove(&(window_id, view_id)) {
1513                    let handled = view.modifiers_changed(event, self, window_id, view_id);
1514                    self.cx.views.insert((window_id, view_id), view);
1515                    if handled {
1516                        return true;
1517                    }
1518                } else {
1519                    log::error!("view {} does not exist", view_id)
1520                }
1521            }
1522        }
1523
1524        false
1525    }
1526
1527    pub fn dispatch_keystroke(&mut self, window_id: usize, keystroke: &Keystroke) -> bool {
1528        let mut pending = false;
1529
1530        if let Some(focused_view_id) = self.focused_view_id(window_id) {
1531            for view_id in self
1532                .ancestors(window_id, focused_view_id)
1533                .collect::<Vec<_>>()
1534            {
1535                let keymap_context = self
1536                    .cx
1537                    .views
1538                    .get(&(window_id, view_id))
1539                    .unwrap()
1540                    .keymap_context(self.as_ref());
1541
1542                match self.keystroke_matcher.push_keystroke(
1543                    keystroke.clone(),
1544                    view_id,
1545                    &keymap_context,
1546                ) {
1547                    MatchResult::None => {}
1548                    MatchResult::Pending => pending = true,
1549                    MatchResult::Action(action) => {
1550                        if self.handle_dispatch_action_from_effect(
1551                            window_id,
1552                            Some(view_id),
1553                            action.as_ref(),
1554                        ) {
1555                            self.keystroke_matcher.clear_pending();
1556                            return true;
1557                        }
1558                    }
1559                }
1560            }
1561        }
1562
1563        pending
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 mouse_position: Vector2F,
3901    pub hovered_region_ids: HashSet<MouseRegionId>,
3902    pub clicked_region_ids: Option<(HashSet<MouseRegionId>, MouseButton)>,
3903    pub refreshing: bool,
3904    pub appearance: Appearance,
3905}
3906
3907pub struct RenderContext<'a, T: View> {
3908    pub(crate) window_id: usize,
3909    pub(crate) view_id: usize,
3910    pub(crate) view_type: PhantomData<T>,
3911    pub(crate) mouse_position: Vector2F,
3912    pub(crate) hovered_region_ids: HashSet<MouseRegionId>,
3913    pub(crate) clicked_region_ids: Option<(HashSet<MouseRegionId>, MouseButton)>,
3914    pub app: &'a mut MutableAppContext,
3915    pub titlebar_height: f32,
3916    pub appearance: Appearance,
3917    pub refreshing: bool,
3918}
3919
3920#[derive(Clone, Default)]
3921pub struct MouseState {
3922    hovered: bool,
3923    mouse_position: Vector2F,
3924    clicked: Option<MouseButton>,
3925    accessed_mouse_position: bool,
3926    accessed_hovered: bool,
3927    accessed_clicked: bool,
3928}
3929
3930impl MouseState {
3931    pub fn mouse_position(&mut self) -> Vector2F {
3932        self.accessed_mouse_position = true;
3933        self.mouse_position
3934    }
3935
3936    pub fn hovered(&mut self) -> bool {
3937        self.accessed_hovered = true;
3938        self.hovered
3939    }
3940
3941    pub fn clicked(&mut self) -> Option<MouseButton> {
3942        self.accessed_clicked = true;
3943        self.clicked
3944    }
3945
3946    pub fn accessed_mouse_position(&self) -> bool {
3947        self.accessed_mouse_position
3948    }
3949
3950    pub fn accessed_hovered(&self) -> bool {
3951        self.accessed_hovered
3952    }
3953
3954    pub fn accessed_clicked(&self) -> bool {
3955        self.accessed_clicked
3956    }
3957}
3958
3959impl<'a, V: View> RenderContext<'a, V> {
3960    fn new(params: RenderParams, app: &'a mut MutableAppContext) -> Self {
3961        Self {
3962            app,
3963            window_id: params.window_id,
3964            view_id: params.view_id,
3965            view_type: PhantomData,
3966            titlebar_height: params.titlebar_height,
3967            mouse_position: params.mouse_position,
3968            hovered_region_ids: params.hovered_region_ids.clone(),
3969            clicked_region_ids: params.clicked_region_ids.clone(),
3970            refreshing: params.refreshing,
3971            appearance: params.appearance,
3972        }
3973    }
3974
3975    pub fn handle(&self) -> WeakViewHandle<V> {
3976        WeakViewHandle::new(self.window_id, self.view_id)
3977    }
3978
3979    pub fn window_id(&self) -> usize {
3980        self.window_id
3981    }
3982
3983    pub fn view_id(&self) -> usize {
3984        self.view_id
3985    }
3986
3987    pub fn mouse_state<Tag: 'static>(&self, region_id: usize) -> MouseState {
3988        let region_id = MouseRegionId::new::<Tag>(self.view_id, region_id);
3989        MouseState {
3990            mouse_position: self.mouse_position.clone(),
3991            hovered: self.hovered_region_ids.contains(&region_id),
3992            clicked: self.clicked_region_ids.as_ref().and_then(|(ids, button)| {
3993                if ids.contains(&region_id) {
3994                    Some(*button)
3995                } else {
3996                    None
3997                }
3998            }),
3999            accessed_mouse_position: false,
4000            accessed_hovered: false,
4001            accessed_clicked: false,
4002        }
4003    }
4004
4005    pub fn element_state<Tag: 'static, T: 'static>(
4006        &mut self,
4007        element_id: usize,
4008        initial: T,
4009    ) -> ElementStateHandle<T> {
4010        let id = ElementStateId {
4011            view_id: self.view_id(),
4012            element_id,
4013            tag: TypeId::of::<Tag>(),
4014        };
4015        self.cx
4016            .element_states
4017            .entry(id)
4018            .or_insert_with(|| Box::new(initial));
4019        ElementStateHandle::new(id, self.frame_count, &self.cx.ref_counts)
4020    }
4021
4022    pub fn default_element_state<Tag: 'static, T: 'static + Default>(
4023        &mut self,
4024        element_id: usize,
4025    ) -> ElementStateHandle<T> {
4026        self.element_state::<Tag, T>(element_id, T::default())
4027    }
4028}
4029
4030impl AsRef<AppContext> for &AppContext {
4031    fn as_ref(&self) -> &AppContext {
4032        self
4033    }
4034}
4035
4036impl<V: View> Deref for RenderContext<'_, V> {
4037    type Target = MutableAppContext;
4038
4039    fn deref(&self) -> &Self::Target {
4040        self.app
4041    }
4042}
4043
4044impl<V: View> DerefMut for RenderContext<'_, V> {
4045    fn deref_mut(&mut self) -> &mut Self::Target {
4046        self.app
4047    }
4048}
4049
4050impl<V: View> ReadModel for RenderContext<'_, V> {
4051    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
4052        self.app.read_model(handle)
4053    }
4054}
4055
4056impl<V: View> UpdateModel for RenderContext<'_, V> {
4057    fn update_model<T: Entity, O>(
4058        &mut self,
4059        handle: &ModelHandle<T>,
4060        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
4061    ) -> O {
4062        self.app.update_model(handle, update)
4063    }
4064}
4065
4066impl<V: View> ReadView for RenderContext<'_, V> {
4067    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
4068        self.app.read_view(handle)
4069    }
4070}
4071
4072impl<M> AsRef<AppContext> for ViewContext<'_, M> {
4073    fn as_ref(&self) -> &AppContext {
4074        &self.app.cx
4075    }
4076}
4077
4078impl<M> Deref for ViewContext<'_, M> {
4079    type Target = MutableAppContext;
4080
4081    fn deref(&self) -> &Self::Target {
4082        self.app
4083    }
4084}
4085
4086impl<M> DerefMut for ViewContext<'_, M> {
4087    fn deref_mut(&mut self) -> &mut Self::Target {
4088        &mut self.app
4089    }
4090}
4091
4092impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
4093    fn as_mut(&mut self) -> &mut MutableAppContext {
4094        self.app
4095    }
4096}
4097
4098impl<V> ReadModel for ViewContext<'_, V> {
4099    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
4100        self.app.read_model(handle)
4101    }
4102}
4103
4104impl<V> UpgradeModelHandle for ViewContext<'_, V> {
4105    fn upgrade_model_handle<T: Entity>(
4106        &self,
4107        handle: &WeakModelHandle<T>,
4108    ) -> Option<ModelHandle<T>> {
4109        self.cx.upgrade_model_handle(handle)
4110    }
4111
4112    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
4113        self.cx.model_handle_is_upgradable(handle)
4114    }
4115
4116    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
4117        self.cx.upgrade_any_model_handle(handle)
4118    }
4119}
4120
4121impl<V> UpgradeViewHandle for ViewContext<'_, V> {
4122    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
4123        self.cx.upgrade_view_handle(handle)
4124    }
4125
4126    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
4127        self.cx.upgrade_any_view_handle(handle)
4128    }
4129}
4130
4131impl<V: View> UpgradeViewHandle for RenderContext<'_, V> {
4132    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
4133        self.cx.upgrade_view_handle(handle)
4134    }
4135
4136    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
4137        self.cx.upgrade_any_view_handle(handle)
4138    }
4139}
4140
4141impl<V: View> UpdateModel for ViewContext<'_, V> {
4142    fn update_model<T: Entity, O>(
4143        &mut self,
4144        handle: &ModelHandle<T>,
4145        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
4146    ) -> O {
4147        self.app.update_model(handle, update)
4148    }
4149}
4150
4151impl<V: View> ReadView for ViewContext<'_, V> {
4152    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
4153        self.app.read_view(handle)
4154    }
4155}
4156
4157impl<V: View> UpdateView for ViewContext<'_, V> {
4158    fn update_view<T, S>(
4159        &mut self,
4160        handle: &ViewHandle<T>,
4161        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
4162    ) -> S
4163    where
4164        T: View,
4165    {
4166        self.app.update_view(handle, update)
4167    }
4168}
4169
4170pub trait Handle<T> {
4171    type Weak: 'static;
4172    fn id(&self) -> usize;
4173    fn location(&self) -> EntityLocation;
4174    fn downgrade(&self) -> Self::Weak;
4175    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4176    where
4177        Self: Sized;
4178}
4179
4180pub trait WeakHandle {
4181    fn id(&self) -> usize;
4182}
4183
4184#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
4185pub enum EntityLocation {
4186    Model(usize),
4187    View(usize, usize),
4188}
4189
4190pub struct ModelHandle<T: Entity> {
4191    model_id: usize,
4192    model_type: PhantomData<T>,
4193    ref_counts: Arc<Mutex<RefCounts>>,
4194
4195    #[cfg(any(test, feature = "test-support"))]
4196    handle_id: usize,
4197}
4198
4199impl<T: Entity> ModelHandle<T> {
4200    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4201        ref_counts.lock().inc_model(model_id);
4202
4203        #[cfg(any(test, feature = "test-support"))]
4204        let handle_id = ref_counts
4205            .lock()
4206            .leak_detector
4207            .lock()
4208            .handle_created(Some(type_name::<T>()), model_id);
4209
4210        Self {
4211            model_id,
4212            model_type: PhantomData,
4213            ref_counts: ref_counts.clone(),
4214
4215            #[cfg(any(test, feature = "test-support"))]
4216            handle_id,
4217        }
4218    }
4219
4220    pub fn downgrade(&self) -> WeakModelHandle<T> {
4221        WeakModelHandle::new(self.model_id)
4222    }
4223
4224    pub fn id(&self) -> usize {
4225        self.model_id
4226    }
4227
4228    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
4229        cx.read_model(self)
4230    }
4231
4232    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
4233    where
4234        C: ReadModelWith,
4235        F: FnOnce(&T, &AppContext) -> S,
4236    {
4237        let mut read = Some(read);
4238        cx.read_model_with(self, &mut |model, cx| {
4239            let read = read.take().unwrap();
4240            read(model, cx)
4241        })
4242    }
4243
4244    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
4245    where
4246        C: UpdateModel,
4247        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
4248    {
4249        let mut update = Some(update);
4250        cx.update_model(self, &mut |model, cx| {
4251            let update = update.take().unwrap();
4252            update(model, cx)
4253        })
4254    }
4255}
4256
4257impl<T: Entity> Clone for ModelHandle<T> {
4258    fn clone(&self) -> Self {
4259        Self::new(self.model_id, &self.ref_counts)
4260    }
4261}
4262
4263impl<T: Entity> PartialEq for ModelHandle<T> {
4264    fn eq(&self, other: &Self) -> bool {
4265        self.model_id == other.model_id
4266    }
4267}
4268
4269impl<T: Entity> Eq for ModelHandle<T> {}
4270
4271impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
4272    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
4273        self.model_id == other.model_id
4274    }
4275}
4276
4277impl<T: Entity> Hash for ModelHandle<T> {
4278    fn hash<H: Hasher>(&self, state: &mut H) {
4279        self.model_id.hash(state);
4280    }
4281}
4282
4283impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
4284    fn borrow(&self) -> &usize {
4285        &self.model_id
4286    }
4287}
4288
4289impl<T: Entity> Debug for ModelHandle<T> {
4290    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4291        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
4292            .field(&self.model_id)
4293            .finish()
4294    }
4295}
4296
4297unsafe impl<T: Entity> Send for ModelHandle<T> {}
4298unsafe impl<T: Entity> Sync for ModelHandle<T> {}
4299
4300impl<T: Entity> Drop for ModelHandle<T> {
4301    fn drop(&mut self) {
4302        let mut ref_counts = self.ref_counts.lock();
4303        ref_counts.dec_model(self.model_id);
4304
4305        #[cfg(any(test, feature = "test-support"))]
4306        ref_counts
4307            .leak_detector
4308            .lock()
4309            .handle_dropped(self.model_id, self.handle_id);
4310    }
4311}
4312
4313impl<T: Entity> Handle<T> for ModelHandle<T> {
4314    type Weak = WeakModelHandle<T>;
4315
4316    fn id(&self) -> usize {
4317        self.model_id
4318    }
4319
4320    fn location(&self) -> EntityLocation {
4321        EntityLocation::Model(self.model_id)
4322    }
4323
4324    fn downgrade(&self) -> Self::Weak {
4325        self.downgrade()
4326    }
4327
4328    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4329    where
4330        Self: Sized,
4331    {
4332        weak.upgrade(cx)
4333    }
4334}
4335
4336pub struct WeakModelHandle<T> {
4337    model_id: usize,
4338    model_type: PhantomData<T>,
4339}
4340
4341impl<T> WeakHandle for WeakModelHandle<T> {
4342    fn id(&self) -> usize {
4343        self.model_id
4344    }
4345}
4346
4347unsafe impl<T> Send for WeakModelHandle<T> {}
4348unsafe impl<T> Sync for WeakModelHandle<T> {}
4349
4350impl<T: Entity> WeakModelHandle<T> {
4351    fn new(model_id: usize) -> Self {
4352        Self {
4353            model_id,
4354            model_type: PhantomData,
4355        }
4356    }
4357
4358    pub fn id(&self) -> usize {
4359        self.model_id
4360    }
4361
4362    pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
4363        cx.model_handle_is_upgradable(self)
4364    }
4365
4366    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
4367        cx.upgrade_model_handle(self)
4368    }
4369}
4370
4371impl<T> Hash for WeakModelHandle<T> {
4372    fn hash<H: Hasher>(&self, state: &mut H) {
4373        self.model_id.hash(state)
4374    }
4375}
4376
4377impl<T> PartialEq for WeakModelHandle<T> {
4378    fn eq(&self, other: &Self) -> bool {
4379        self.model_id == other.model_id
4380    }
4381}
4382
4383impl<T> Eq for WeakModelHandle<T> {}
4384
4385impl<T: Entity> PartialEq<ModelHandle<T>> for WeakModelHandle<T> {
4386    fn eq(&self, other: &ModelHandle<T>) -> bool {
4387        self.model_id == other.model_id
4388    }
4389}
4390
4391impl<T> Clone for WeakModelHandle<T> {
4392    fn clone(&self) -> Self {
4393        Self {
4394            model_id: self.model_id,
4395            model_type: PhantomData,
4396        }
4397    }
4398}
4399
4400impl<T> Copy for WeakModelHandle<T> {}
4401
4402pub struct ViewHandle<T> {
4403    window_id: usize,
4404    view_id: usize,
4405    view_type: PhantomData<T>,
4406    ref_counts: Arc<Mutex<RefCounts>>,
4407    #[cfg(any(test, feature = "test-support"))]
4408    handle_id: usize,
4409}
4410
4411impl<T: View> ViewHandle<T> {
4412    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4413        ref_counts.lock().inc_view(window_id, view_id);
4414        #[cfg(any(test, feature = "test-support"))]
4415        let handle_id = ref_counts
4416            .lock()
4417            .leak_detector
4418            .lock()
4419            .handle_created(Some(type_name::<T>()), view_id);
4420
4421        Self {
4422            window_id,
4423            view_id,
4424            view_type: PhantomData,
4425            ref_counts: ref_counts.clone(),
4426
4427            #[cfg(any(test, feature = "test-support"))]
4428            handle_id,
4429        }
4430    }
4431
4432    pub fn downgrade(&self) -> WeakViewHandle<T> {
4433        WeakViewHandle::new(self.window_id, self.view_id)
4434    }
4435
4436    pub fn window_id(&self) -> usize {
4437        self.window_id
4438    }
4439
4440    pub fn id(&self) -> usize {
4441        self.view_id
4442    }
4443
4444    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
4445        cx.read_view(self)
4446    }
4447
4448    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
4449    where
4450        C: ReadViewWith,
4451        F: FnOnce(&T, &AppContext) -> S,
4452    {
4453        let mut read = Some(read);
4454        cx.read_view_with(self, &mut |view, cx| {
4455            let read = read.take().unwrap();
4456            read(view, cx)
4457        })
4458    }
4459
4460    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
4461    where
4462        C: UpdateView,
4463        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
4464    {
4465        let mut update = Some(update);
4466        cx.update_view(self, &mut |view, cx| {
4467            let update = update.take().unwrap();
4468            update(view, cx)
4469        })
4470    }
4471
4472    pub fn defer<C, F>(&self, cx: &mut C, update: F)
4473    where
4474        C: AsMut<MutableAppContext>,
4475        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
4476    {
4477        let this = self.clone();
4478        cx.as_mut().defer(move |cx| {
4479            this.update(cx, |view, cx| update(view, cx));
4480        });
4481    }
4482
4483    pub fn is_focused(&self, cx: &AppContext) -> bool {
4484        cx.focused_view_id(self.window_id)
4485            .map_or(false, |focused_id| focused_id == self.view_id)
4486    }
4487}
4488
4489impl<T: View> Clone for ViewHandle<T> {
4490    fn clone(&self) -> Self {
4491        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
4492    }
4493}
4494
4495impl<T> PartialEq for ViewHandle<T> {
4496    fn eq(&self, other: &Self) -> bool {
4497        self.window_id == other.window_id && self.view_id == other.view_id
4498    }
4499}
4500
4501impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
4502    fn eq(&self, other: &WeakViewHandle<T>) -> bool {
4503        self.window_id == other.window_id && self.view_id == other.view_id
4504    }
4505}
4506
4507impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
4508    fn eq(&self, other: &ViewHandle<T>) -> bool {
4509        self.window_id == other.window_id && self.view_id == other.view_id
4510    }
4511}
4512
4513impl<T> Eq for ViewHandle<T> {}
4514
4515impl<T> Hash for ViewHandle<T> {
4516    fn hash<H: Hasher>(&self, state: &mut H) {
4517        self.window_id.hash(state);
4518        self.view_id.hash(state);
4519    }
4520}
4521
4522impl<T> Debug for ViewHandle<T> {
4523    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4524        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
4525            .field("window_id", &self.window_id)
4526            .field("view_id", &self.view_id)
4527            .finish()
4528    }
4529}
4530
4531impl<T> Drop for ViewHandle<T> {
4532    fn drop(&mut self) {
4533        self.ref_counts
4534            .lock()
4535            .dec_view(self.window_id, self.view_id);
4536        #[cfg(any(test, feature = "test-support"))]
4537        self.ref_counts
4538            .lock()
4539            .leak_detector
4540            .lock()
4541            .handle_dropped(self.view_id, self.handle_id);
4542    }
4543}
4544
4545impl<T: View> Handle<T> for ViewHandle<T> {
4546    type Weak = WeakViewHandle<T>;
4547
4548    fn id(&self) -> usize {
4549        self.view_id
4550    }
4551
4552    fn location(&self) -> EntityLocation {
4553        EntityLocation::View(self.window_id, self.view_id)
4554    }
4555
4556    fn downgrade(&self) -> Self::Weak {
4557        self.downgrade()
4558    }
4559
4560    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4561    where
4562        Self: Sized,
4563    {
4564        weak.upgrade(cx)
4565    }
4566}
4567
4568pub struct AnyViewHandle {
4569    window_id: usize,
4570    view_id: usize,
4571    view_type: TypeId,
4572    ref_counts: Arc<Mutex<RefCounts>>,
4573
4574    #[cfg(any(test, feature = "test-support"))]
4575    handle_id: usize,
4576}
4577
4578impl AnyViewHandle {
4579    fn new(
4580        window_id: usize,
4581        view_id: usize,
4582        view_type: TypeId,
4583        ref_counts: Arc<Mutex<RefCounts>>,
4584    ) -> Self {
4585        ref_counts.lock().inc_view(window_id, view_id);
4586
4587        #[cfg(any(test, feature = "test-support"))]
4588        let handle_id = ref_counts
4589            .lock()
4590            .leak_detector
4591            .lock()
4592            .handle_created(None, view_id);
4593
4594        Self {
4595            window_id,
4596            view_id,
4597            view_type,
4598            ref_counts,
4599            #[cfg(any(test, feature = "test-support"))]
4600            handle_id,
4601        }
4602    }
4603
4604    pub fn window_id(&self) -> usize {
4605        self.window_id
4606    }
4607
4608    pub fn id(&self) -> usize {
4609        self.view_id
4610    }
4611
4612    pub fn is<T: 'static>(&self) -> bool {
4613        TypeId::of::<T>() == self.view_type
4614    }
4615
4616    pub fn is_focused(&self, cx: &AppContext) -> bool {
4617        cx.focused_view_id(self.window_id)
4618            .map_or(false, |focused_id| focused_id == self.view_id)
4619    }
4620
4621    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
4622        if self.is::<T>() {
4623            let result = Some(ViewHandle {
4624                window_id: self.window_id,
4625                view_id: self.view_id,
4626                ref_counts: self.ref_counts.clone(),
4627                view_type: PhantomData,
4628                #[cfg(any(test, feature = "test-support"))]
4629                handle_id: self.handle_id,
4630            });
4631            unsafe {
4632                Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
4633            }
4634            std::mem::forget(self);
4635            result
4636        } else {
4637            None
4638        }
4639    }
4640
4641    pub fn downgrade(&self) -> AnyWeakViewHandle {
4642        AnyWeakViewHandle {
4643            window_id: self.window_id,
4644            view_id: self.view_id,
4645            view_type: self.view_type,
4646        }
4647    }
4648
4649    pub fn view_type(&self) -> TypeId {
4650        self.view_type
4651    }
4652
4653    pub fn debug_json(&self, cx: &AppContext) -> serde_json::Value {
4654        cx.views
4655            .get(&(self.window_id, self.view_id))
4656            .map_or_else(|| serde_json::Value::Null, |view| view.debug_json(cx))
4657    }
4658}
4659
4660impl Clone for AnyViewHandle {
4661    fn clone(&self) -> Self {
4662        Self::new(
4663            self.window_id,
4664            self.view_id,
4665            self.view_type,
4666            self.ref_counts.clone(),
4667        )
4668    }
4669}
4670
4671impl From<&AnyViewHandle> for AnyViewHandle {
4672    fn from(handle: &AnyViewHandle) -> Self {
4673        handle.clone()
4674    }
4675}
4676
4677impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
4678    fn from(handle: &ViewHandle<T>) -> Self {
4679        Self::new(
4680            handle.window_id,
4681            handle.view_id,
4682            TypeId::of::<T>(),
4683            handle.ref_counts.clone(),
4684        )
4685    }
4686}
4687
4688impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
4689    fn from(handle: ViewHandle<T>) -> Self {
4690        let any_handle = AnyViewHandle {
4691            window_id: handle.window_id,
4692            view_id: handle.view_id,
4693            view_type: TypeId::of::<T>(),
4694            ref_counts: handle.ref_counts.clone(),
4695            #[cfg(any(test, feature = "test-support"))]
4696            handle_id: handle.handle_id,
4697        };
4698
4699        unsafe {
4700            Arc::decrement_strong_count(Arc::as_ptr(&handle.ref_counts));
4701        }
4702        std::mem::forget(handle);
4703        any_handle
4704    }
4705}
4706
4707impl Drop for AnyViewHandle {
4708    fn drop(&mut self) {
4709        self.ref_counts
4710            .lock()
4711            .dec_view(self.window_id, self.view_id);
4712        #[cfg(any(test, feature = "test-support"))]
4713        self.ref_counts
4714            .lock()
4715            .leak_detector
4716            .lock()
4717            .handle_dropped(self.view_id, self.handle_id);
4718    }
4719}
4720
4721pub struct AnyModelHandle {
4722    model_id: usize,
4723    model_type: TypeId,
4724    ref_counts: Arc<Mutex<RefCounts>>,
4725
4726    #[cfg(any(test, feature = "test-support"))]
4727    handle_id: usize,
4728}
4729
4730impl AnyModelHandle {
4731    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
4732        ref_counts.lock().inc_model(model_id);
4733
4734        #[cfg(any(test, feature = "test-support"))]
4735        let handle_id = ref_counts
4736            .lock()
4737            .leak_detector
4738            .lock()
4739            .handle_created(None, model_id);
4740
4741        Self {
4742            model_id,
4743            model_type,
4744            ref_counts,
4745
4746            #[cfg(any(test, feature = "test-support"))]
4747            handle_id,
4748        }
4749    }
4750
4751    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
4752        if self.is::<T>() {
4753            let result = Some(ModelHandle {
4754                model_id: self.model_id,
4755                model_type: PhantomData,
4756                ref_counts: self.ref_counts.clone(),
4757
4758                #[cfg(any(test, feature = "test-support"))]
4759                handle_id: self.handle_id,
4760            });
4761            unsafe {
4762                Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
4763            }
4764            std::mem::forget(self);
4765            result
4766        } else {
4767            None
4768        }
4769    }
4770
4771    pub fn downgrade(&self) -> AnyWeakModelHandle {
4772        AnyWeakModelHandle {
4773            model_id: self.model_id,
4774            model_type: self.model_type,
4775        }
4776    }
4777
4778    pub fn is<T: Entity>(&self) -> bool {
4779        self.model_type == TypeId::of::<T>()
4780    }
4781
4782    pub fn model_type(&self) -> TypeId {
4783        self.model_type
4784    }
4785}
4786
4787impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
4788    fn from(handle: ModelHandle<T>) -> Self {
4789        Self::new(
4790            handle.model_id,
4791            TypeId::of::<T>(),
4792            handle.ref_counts.clone(),
4793        )
4794    }
4795}
4796
4797impl Clone for AnyModelHandle {
4798    fn clone(&self) -> Self {
4799        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
4800    }
4801}
4802
4803impl Drop for AnyModelHandle {
4804    fn drop(&mut self) {
4805        let mut ref_counts = self.ref_counts.lock();
4806        ref_counts.dec_model(self.model_id);
4807
4808        #[cfg(any(test, feature = "test-support"))]
4809        ref_counts
4810            .leak_detector
4811            .lock()
4812            .handle_dropped(self.model_id, self.handle_id);
4813    }
4814}
4815
4816#[derive(Hash, PartialEq, Eq, Debug)]
4817pub struct AnyWeakModelHandle {
4818    model_id: usize,
4819    model_type: TypeId,
4820}
4821
4822impl AnyWeakModelHandle {
4823    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
4824        cx.upgrade_any_model_handle(self)
4825    }
4826    pub fn model_type(&self) -> TypeId {
4827        self.model_type
4828    }
4829
4830    fn is<T: 'static>(&self) -> bool {
4831        TypeId::of::<T>() == self.model_type
4832    }
4833
4834    pub fn downcast<T: Entity>(&self) -> Option<WeakModelHandle<T>> {
4835        if self.is::<T>() {
4836            let result = Some(WeakModelHandle {
4837                model_id: self.model_id,
4838                model_type: PhantomData,
4839            });
4840
4841            result
4842        } else {
4843            None
4844        }
4845    }
4846}
4847
4848impl<T: Entity> From<WeakModelHandle<T>> for AnyWeakModelHandle {
4849    fn from(handle: WeakModelHandle<T>) -> Self {
4850        AnyWeakModelHandle {
4851            model_id: handle.model_id,
4852            model_type: TypeId::of::<T>(),
4853        }
4854    }
4855}
4856
4857#[derive(Debug)]
4858pub struct WeakViewHandle<T> {
4859    window_id: usize,
4860    view_id: usize,
4861    view_type: PhantomData<T>,
4862}
4863
4864impl<T> WeakHandle for WeakViewHandle<T> {
4865    fn id(&self) -> usize {
4866        self.view_id
4867    }
4868}
4869
4870impl<T: View> WeakViewHandle<T> {
4871    fn new(window_id: usize, view_id: usize) -> Self {
4872        Self {
4873            window_id,
4874            view_id,
4875            view_type: PhantomData,
4876        }
4877    }
4878
4879    pub fn id(&self) -> usize {
4880        self.view_id
4881    }
4882
4883    pub fn window_id(&self) -> usize {
4884        self.window_id
4885    }
4886
4887    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
4888        cx.upgrade_view_handle(self)
4889    }
4890}
4891
4892impl<T> Clone for WeakViewHandle<T> {
4893    fn clone(&self) -> Self {
4894        Self {
4895            window_id: self.window_id,
4896            view_id: self.view_id,
4897            view_type: PhantomData,
4898        }
4899    }
4900}
4901
4902impl<T> PartialEq for WeakViewHandle<T> {
4903    fn eq(&self, other: &Self) -> bool {
4904        self.window_id == other.window_id && self.view_id == other.view_id
4905    }
4906}
4907
4908impl<T> Eq for WeakViewHandle<T> {}
4909
4910impl<T> Hash for WeakViewHandle<T> {
4911    fn hash<H: Hasher>(&self, state: &mut H) {
4912        self.window_id.hash(state);
4913        self.view_id.hash(state);
4914    }
4915}
4916
4917pub struct AnyWeakViewHandle {
4918    window_id: usize,
4919    view_id: usize,
4920    view_type: TypeId,
4921}
4922
4923impl AnyWeakViewHandle {
4924    pub fn id(&self) -> usize {
4925        self.view_id
4926    }
4927
4928    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<AnyViewHandle> {
4929        cx.upgrade_any_view_handle(self)
4930    }
4931}
4932
4933impl<T: View> From<WeakViewHandle<T>> for AnyWeakViewHandle {
4934    fn from(handle: WeakViewHandle<T>) -> Self {
4935        AnyWeakViewHandle {
4936            window_id: handle.window_id,
4937            view_id: handle.view_id,
4938            view_type: TypeId::of::<T>(),
4939        }
4940    }
4941}
4942
4943#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4944pub struct ElementStateId {
4945    view_id: usize,
4946    element_id: usize,
4947    tag: TypeId,
4948}
4949
4950pub struct ElementStateHandle<T> {
4951    value_type: PhantomData<T>,
4952    id: ElementStateId,
4953    ref_counts: Weak<Mutex<RefCounts>>,
4954}
4955
4956impl<T: 'static> ElementStateHandle<T> {
4957    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4958        ref_counts.lock().inc_element_state(id, frame_id);
4959        Self {
4960            value_type: PhantomData,
4961            id,
4962            ref_counts: Arc::downgrade(ref_counts),
4963        }
4964    }
4965
4966    pub fn id(&self) -> ElementStateId {
4967        self.id
4968    }
4969
4970    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
4971        cx.element_states
4972            .get(&self.id)
4973            .unwrap()
4974            .downcast_ref()
4975            .unwrap()
4976    }
4977
4978    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
4979    where
4980        C: DerefMut<Target = MutableAppContext>,
4981    {
4982        let mut element_state = cx.deref_mut().cx.element_states.remove(&self.id).unwrap();
4983        let result = f(element_state.downcast_mut().unwrap(), cx);
4984        cx.deref_mut()
4985            .cx
4986            .element_states
4987            .insert(self.id, element_state);
4988        result
4989    }
4990}
4991
4992impl<T> Drop for ElementStateHandle<T> {
4993    fn drop(&mut self) {
4994        if let Some(ref_counts) = self.ref_counts.upgrade() {
4995            ref_counts.lock().dec_element_state(self.id);
4996        }
4997    }
4998}
4999
5000#[must_use]
5001pub enum Subscription {
5002    Subscription {
5003        id: usize,
5004        entity_id: usize,
5005        subscriptions: Option<Weak<Mapping<usize, SubscriptionCallback>>>,
5006    },
5007    GlobalSubscription {
5008        id: usize,
5009        type_id: TypeId,
5010        subscriptions: Option<Weak<Mapping<TypeId, GlobalSubscriptionCallback>>>,
5011    },
5012    Observation {
5013        id: usize,
5014        entity_id: usize,
5015        observations: Option<Weak<Mapping<usize, ObservationCallback>>>,
5016    },
5017    GlobalObservation {
5018        id: usize,
5019        type_id: TypeId,
5020        observations: Option<Weak<Mapping<TypeId, GlobalObservationCallback>>>,
5021    },
5022    FocusObservation {
5023        id: usize,
5024        view_id: usize,
5025        observations: Option<Weak<Mapping<usize, FocusObservationCallback>>>,
5026    },
5027    WindowActivationObservation {
5028        id: usize,
5029        window_id: usize,
5030        observations: Option<Weak<Mapping<usize, WindowActivationCallback>>>,
5031    },
5032    WindowFullscreenObservation {
5033        id: usize,
5034        window_id: usize,
5035        observations: Option<Weak<Mapping<usize, WindowFullscreenCallback>>>,
5036    },
5037
5038    ReleaseObservation {
5039        id: usize,
5040        entity_id: usize,
5041        #[allow(clippy::type_complexity)]
5042        observations:
5043            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>>,
5044    },
5045    ActionObservation {
5046        id: usize,
5047        observations: Option<Weak<Mutex<BTreeMap<usize, ActionObservationCallback>>>>,
5048    },
5049}
5050
5051impl Subscription {
5052    pub fn detach(&mut self) {
5053        match self {
5054            Subscription::Subscription { subscriptions, .. } => {
5055                subscriptions.take();
5056            }
5057            Subscription::GlobalSubscription { subscriptions, .. } => {
5058                subscriptions.take();
5059            }
5060            Subscription::Observation { observations, .. } => {
5061                observations.take();
5062            }
5063            Subscription::GlobalObservation { observations, .. } => {
5064                observations.take();
5065            }
5066            Subscription::ReleaseObservation { observations, .. } => {
5067                observations.take();
5068            }
5069            Subscription::FocusObservation { observations, .. } => {
5070                observations.take();
5071            }
5072            Subscription::ActionObservation { observations, .. } => {
5073                observations.take();
5074            }
5075            Subscription::WindowActivationObservation { observations, .. } => {
5076                observations.take();
5077            }
5078            Subscription::WindowFullscreenObservation { observations, .. } => {
5079                observations.take();
5080            }
5081        }
5082    }
5083}
5084
5085impl Drop for Subscription {
5086    fn drop(&mut self) {
5087        match self {
5088            Subscription::Subscription {
5089                id,
5090                entity_id,
5091                subscriptions,
5092            } => {
5093                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
5094                    match subscriptions
5095                        .lock()
5096                        .entry(*entity_id)
5097                        .or_default()
5098                        .entry(*id)
5099                    {
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::GlobalSubscription {
5110                id,
5111                type_id,
5112                subscriptions,
5113            } => {
5114                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
5115                    match subscriptions.lock().entry(*type_id).or_default().entry(*id) {
5116                        btree_map::Entry::Vacant(entry) => {
5117                            entry.insert(None);
5118                        }
5119                        btree_map::Entry::Occupied(entry) => {
5120                            entry.remove();
5121                        }
5122                    }
5123                }
5124            }
5125            Subscription::Observation {
5126                id,
5127                entity_id,
5128                observations,
5129            } => {
5130                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5131                    match observations
5132                        .lock()
5133                        .entry(*entity_id)
5134                        .or_default()
5135                        .entry(*id)
5136                    {
5137                        btree_map::Entry::Vacant(entry) => {
5138                            entry.insert(None);
5139                        }
5140                        btree_map::Entry::Occupied(entry) => {
5141                            entry.remove();
5142                        }
5143                    }
5144                }
5145            }
5146            Subscription::GlobalObservation {
5147                id,
5148                type_id,
5149                observations,
5150            } => {
5151                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5152                    match observations.lock().entry(*type_id).or_default().entry(*id) {
5153                        collections::btree_map::Entry::Vacant(entry) => {
5154                            entry.insert(None);
5155                        }
5156                        collections::btree_map::Entry::Occupied(entry) => {
5157                            entry.remove();
5158                        }
5159                    }
5160                }
5161            }
5162            Subscription::ReleaseObservation {
5163                id,
5164                entity_id,
5165                observations,
5166            } => {
5167                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5168                    if let Some(observations) = observations.lock().get_mut(entity_id) {
5169                        observations.remove(id);
5170                    }
5171                }
5172            }
5173            Subscription::FocusObservation {
5174                id,
5175                view_id,
5176                observations,
5177            } => {
5178                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5179                    match observations.lock().entry(*view_id).or_default().entry(*id) {
5180                        btree_map::Entry::Vacant(entry) => {
5181                            entry.insert(None);
5182                        }
5183                        btree_map::Entry::Occupied(entry) => {
5184                            entry.remove();
5185                        }
5186                    }
5187                }
5188            }
5189            Subscription::ActionObservation { id, observations } => {
5190                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5191                    observations.lock().remove(id);
5192                }
5193            }
5194            Subscription::WindowActivationObservation {
5195                id,
5196                window_id,
5197                observations,
5198            } => {
5199                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5200                    match observations
5201                        .lock()
5202                        .entry(*window_id)
5203                        .or_default()
5204                        .entry(*id)
5205                    {
5206                        btree_map::Entry::Vacant(entry) => {
5207                            entry.insert(None);
5208                        }
5209                        btree_map::Entry::Occupied(entry) => {
5210                            entry.remove();
5211                        }
5212                    }
5213                }
5214            }
5215            Subscription::WindowFullscreenObservation {
5216                id,
5217                window_id,
5218                observations,
5219            } => {
5220                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5221                    match observations
5222                        .lock()
5223                        .entry(*window_id)
5224                        .or_default()
5225                        .entry(*id)
5226                    {
5227                        btree_map::Entry::Vacant(entry) => {
5228                            entry.insert(None);
5229                        }
5230                        btree_map::Entry::Occupied(entry) => {
5231                            entry.remove();
5232                        }
5233                    }
5234                }
5235            }
5236        }
5237    }
5238}
5239
5240lazy_static! {
5241    static ref LEAK_BACKTRACE: bool =
5242        std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty());
5243}
5244
5245#[cfg(any(test, feature = "test-support"))]
5246#[derive(Default)]
5247pub struct LeakDetector {
5248    next_handle_id: usize,
5249    #[allow(clippy::type_complexity)]
5250    handle_backtraces: HashMap<
5251        usize,
5252        (
5253            Option<&'static str>,
5254            HashMap<usize, Option<backtrace::Backtrace>>,
5255        ),
5256    >,
5257}
5258
5259#[cfg(any(test, feature = "test-support"))]
5260impl LeakDetector {
5261    fn handle_created(&mut self, type_name: Option<&'static str>, entity_id: usize) -> usize {
5262        let handle_id = post_inc(&mut self.next_handle_id);
5263        let entry = self.handle_backtraces.entry(entity_id).or_default();
5264        let backtrace = if *LEAK_BACKTRACE {
5265            Some(backtrace::Backtrace::new_unresolved())
5266        } else {
5267            None
5268        };
5269        if let Some(type_name) = type_name {
5270            entry.0.get_or_insert(type_name);
5271        }
5272        entry.1.insert(handle_id, backtrace);
5273        handle_id
5274    }
5275
5276    fn handle_dropped(&mut self, entity_id: usize, handle_id: usize) {
5277        if let Some((_, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
5278            assert!(backtraces.remove(&handle_id).is_some());
5279            if backtraces.is_empty() {
5280                self.handle_backtraces.remove(&entity_id);
5281            }
5282        }
5283    }
5284
5285    pub fn assert_dropped(&mut self, entity_id: usize) {
5286        if let Some((type_name, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
5287            for trace in backtraces.values_mut().flatten() {
5288                trace.resolve();
5289                eprintln!("{:?}", crate::util::CwdBacktrace(trace));
5290            }
5291
5292            let hint = if *LEAK_BACKTRACE {
5293                ""
5294            } else {
5295                " – set LEAK_BACKTRACE=1 for more information"
5296            };
5297
5298            panic!(
5299                "{} handles to {} {} still exist{}",
5300                backtraces.len(),
5301                type_name.unwrap_or("entity"),
5302                entity_id,
5303                hint
5304            );
5305        }
5306    }
5307
5308    pub fn detect(&mut self) {
5309        let mut found_leaks = false;
5310        for (id, (type_name, backtraces)) in self.handle_backtraces.iter_mut() {
5311            eprintln!(
5312                "leaked {} handles to {} {}",
5313                backtraces.len(),
5314                type_name.unwrap_or("entity"),
5315                id
5316            );
5317            for trace in backtraces.values_mut().flatten() {
5318                trace.resolve();
5319                eprintln!("{:?}", crate::util::CwdBacktrace(trace));
5320            }
5321            found_leaks = true;
5322        }
5323
5324        let hint = if *LEAK_BACKTRACE {
5325            ""
5326        } else {
5327            " – set LEAK_BACKTRACE=1 for more information"
5328        };
5329        assert!(!found_leaks, "detected leaked handles{}", hint);
5330    }
5331}
5332
5333#[derive(Default)]
5334struct RefCounts {
5335    entity_counts: HashMap<usize, usize>,
5336    element_state_counts: HashMap<ElementStateId, ElementStateRefCount>,
5337    dropped_models: HashSet<usize>,
5338    dropped_views: HashSet<(usize, usize)>,
5339    dropped_element_states: HashSet<ElementStateId>,
5340
5341    #[cfg(any(test, feature = "test-support"))]
5342    leak_detector: Arc<Mutex<LeakDetector>>,
5343}
5344
5345struct ElementStateRefCount {
5346    ref_count: usize,
5347    frame_id: usize,
5348}
5349
5350impl RefCounts {
5351    fn inc_model(&mut self, model_id: usize) {
5352        match self.entity_counts.entry(model_id) {
5353            Entry::Occupied(mut entry) => {
5354                *entry.get_mut() += 1;
5355            }
5356            Entry::Vacant(entry) => {
5357                entry.insert(1);
5358                self.dropped_models.remove(&model_id);
5359            }
5360        }
5361    }
5362
5363    fn inc_view(&mut self, window_id: usize, view_id: usize) {
5364        match self.entity_counts.entry(view_id) {
5365            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
5366            Entry::Vacant(entry) => {
5367                entry.insert(1);
5368                self.dropped_views.remove(&(window_id, view_id));
5369            }
5370        }
5371    }
5372
5373    fn inc_element_state(&mut self, id: ElementStateId, frame_id: usize) {
5374        match self.element_state_counts.entry(id) {
5375            Entry::Occupied(mut entry) => {
5376                let entry = entry.get_mut();
5377                if entry.frame_id == frame_id || entry.ref_count >= 2 {
5378                    panic!("used the same element state more than once in the same frame");
5379                }
5380                entry.ref_count += 1;
5381                entry.frame_id = frame_id;
5382            }
5383            Entry::Vacant(entry) => {
5384                entry.insert(ElementStateRefCount {
5385                    ref_count: 1,
5386                    frame_id,
5387                });
5388                self.dropped_element_states.remove(&id);
5389            }
5390        }
5391    }
5392
5393    fn dec_model(&mut self, model_id: usize) {
5394        let count = self.entity_counts.get_mut(&model_id).unwrap();
5395        *count -= 1;
5396        if *count == 0 {
5397            self.entity_counts.remove(&model_id);
5398            self.dropped_models.insert(model_id);
5399        }
5400    }
5401
5402    fn dec_view(&mut self, window_id: usize, view_id: usize) {
5403        let count = self.entity_counts.get_mut(&view_id).unwrap();
5404        *count -= 1;
5405        if *count == 0 {
5406            self.entity_counts.remove(&view_id);
5407            self.dropped_views.insert((window_id, view_id));
5408        }
5409    }
5410
5411    fn dec_element_state(&mut self, id: ElementStateId) {
5412        let entry = self.element_state_counts.get_mut(&id).unwrap();
5413        entry.ref_count -= 1;
5414        if entry.ref_count == 0 {
5415            self.element_state_counts.remove(&id);
5416            self.dropped_element_states.insert(id);
5417        }
5418    }
5419
5420    fn is_entity_alive(&self, entity_id: usize) -> bool {
5421        self.entity_counts.contains_key(&entity_id)
5422    }
5423
5424    fn take_dropped(
5425        &mut self,
5426    ) -> (
5427        HashSet<usize>,
5428        HashSet<(usize, usize)>,
5429        HashSet<ElementStateId>,
5430    ) {
5431        (
5432            std::mem::take(&mut self.dropped_models),
5433            std::mem::take(&mut self.dropped_views),
5434            std::mem::take(&mut self.dropped_element_states),
5435        )
5436    }
5437}
5438
5439#[cfg(test)]
5440mod tests {
5441    use super::*;
5442    use crate::{actions, elements::*, impl_actions, MouseButton, MouseButtonEvent};
5443    use serde::Deserialize;
5444    use smol::future::poll_once;
5445    use std::{
5446        cell::Cell,
5447        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
5448    };
5449
5450    #[crate::test(self)]
5451    fn test_model_handles(cx: &mut MutableAppContext) {
5452        struct Model {
5453            other: Option<ModelHandle<Model>>,
5454            events: Vec<String>,
5455        }
5456
5457        impl Entity for Model {
5458            type Event = usize;
5459        }
5460
5461        impl Model {
5462            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
5463                if let Some(other) = other.as_ref() {
5464                    cx.observe(other, |me, _, _| {
5465                        me.events.push("notified".into());
5466                    })
5467                    .detach();
5468                    cx.subscribe(other, |me, _, event, _| {
5469                        me.events.push(format!("observed event {}", event));
5470                    })
5471                    .detach();
5472                }
5473
5474                Self {
5475                    other,
5476                    events: Vec::new(),
5477                }
5478            }
5479        }
5480
5481        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
5482        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
5483        assert_eq!(cx.cx.models.len(), 2);
5484
5485        handle_1.update(cx, |model, cx| {
5486            model.events.push("updated".into());
5487            cx.emit(1);
5488            cx.notify();
5489            cx.emit(2);
5490        });
5491        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5492        assert_eq!(
5493            handle_2.read(cx).events,
5494            vec![
5495                "observed event 1".to_string(),
5496                "notified".to_string(),
5497                "observed event 2".to_string(),
5498            ]
5499        );
5500
5501        handle_2.update(cx, |model, _| {
5502            drop(handle_1);
5503            model.other.take();
5504        });
5505
5506        assert_eq!(cx.cx.models.len(), 1);
5507        assert!(cx.subscriptions.is_empty());
5508        assert!(cx.observations.is_empty());
5509    }
5510
5511    #[crate::test(self)]
5512    fn test_model_events(cx: &mut MutableAppContext) {
5513        #[derive(Default)]
5514        struct Model {
5515            events: Vec<usize>,
5516        }
5517
5518        impl Entity for Model {
5519            type Event = usize;
5520        }
5521
5522        let handle_1 = cx.add_model(|_| Model::default());
5523        let handle_2 = cx.add_model(|_| Model::default());
5524
5525        handle_1.update(cx, |_, cx| {
5526            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
5527                model.events.push(*event);
5528
5529                cx.subscribe(&emitter, |model, _, event, _| {
5530                    model.events.push(*event * 2);
5531                })
5532                .detach();
5533            })
5534            .detach();
5535        });
5536
5537        handle_2.update(cx, |_, c| c.emit(7));
5538        assert_eq!(handle_1.read(cx).events, vec![7]);
5539
5540        handle_2.update(cx, |_, c| c.emit(5));
5541        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
5542    }
5543
5544    #[crate::test(self)]
5545    fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
5546        #[derive(Default)]
5547        struct Model;
5548
5549        impl Entity for Model {
5550            type Event = ();
5551        }
5552
5553        let events = Rc::new(RefCell::new(Vec::new()));
5554        cx.add_model(|cx| {
5555            drop(cx.subscribe(&cx.handle(), {
5556                let events = events.clone();
5557                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
5558            }));
5559            cx.subscribe(&cx.handle(), {
5560                let events = events.clone();
5561                move |_, _, _, _| events.borrow_mut().push("before emit")
5562            })
5563            .detach();
5564            cx.emit(());
5565            cx.subscribe(&cx.handle(), {
5566                let events = events.clone();
5567                move |_, _, _, _| events.borrow_mut().push("after emit")
5568            })
5569            .detach();
5570            Model
5571        });
5572        assert_eq!(*events.borrow(), ["before emit"]);
5573    }
5574
5575    #[crate::test(self)]
5576    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
5577        #[derive(Default)]
5578        struct Model {
5579            count: usize,
5580            events: Vec<usize>,
5581        }
5582
5583        impl Entity for Model {
5584            type Event = ();
5585        }
5586
5587        let handle_1 = cx.add_model(|_| Model::default());
5588        let handle_2 = cx.add_model(|_| Model::default());
5589
5590        handle_1.update(cx, |_, c| {
5591            c.observe(&handle_2, move |model, observed, c| {
5592                model.events.push(observed.read(c).count);
5593                c.observe(&observed, |model, observed, c| {
5594                    model.events.push(observed.read(c).count * 2);
5595                })
5596                .detach();
5597            })
5598            .detach();
5599        });
5600
5601        handle_2.update(cx, |model, c| {
5602            model.count = 7;
5603            c.notify()
5604        });
5605        assert_eq!(handle_1.read(cx).events, vec![7]);
5606
5607        handle_2.update(cx, |model, c| {
5608            model.count = 5;
5609            c.notify()
5610        });
5611        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
5612    }
5613
5614    #[crate::test(self)]
5615    fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
5616        #[derive(Default)]
5617        struct Model;
5618
5619        impl Entity for Model {
5620            type Event = ();
5621        }
5622
5623        let events = Rc::new(RefCell::new(Vec::new()));
5624        cx.add_model(|cx| {
5625            drop(cx.observe(&cx.handle(), {
5626                let events = events.clone();
5627                move |_, _, _| events.borrow_mut().push("dropped before flush")
5628            }));
5629            cx.observe(&cx.handle(), {
5630                let events = events.clone();
5631                move |_, _, _| events.borrow_mut().push("before notify")
5632            })
5633            .detach();
5634            cx.notify();
5635            cx.observe(&cx.handle(), {
5636                let events = events.clone();
5637                move |_, _, _| events.borrow_mut().push("after notify")
5638            })
5639            .detach();
5640            Model
5641        });
5642        assert_eq!(*events.borrow(), ["before notify"]);
5643    }
5644
5645    #[crate::test(self)]
5646    fn test_defer_and_after_window_update(cx: &mut MutableAppContext) {
5647        struct View {
5648            render_count: usize,
5649        }
5650
5651        impl Entity for View {
5652            type Event = usize;
5653        }
5654
5655        impl super::View for View {
5656            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5657                post_inc(&mut self.render_count);
5658                Empty::new().boxed()
5659            }
5660
5661            fn ui_name() -> &'static str {
5662                "View"
5663            }
5664        }
5665
5666        let (_, view) = cx.add_window(Default::default(), |_| View { render_count: 0 });
5667        let called_defer = Rc::new(AtomicBool::new(false));
5668        let called_after_window_update = Rc::new(AtomicBool::new(false));
5669
5670        view.update(cx, |this, cx| {
5671            assert_eq!(this.render_count, 1);
5672            cx.defer({
5673                let called_defer = called_defer.clone();
5674                move |this, _| {
5675                    assert_eq!(this.render_count, 1);
5676                    called_defer.store(true, SeqCst);
5677                }
5678            });
5679            cx.after_window_update({
5680                let called_after_window_update = called_after_window_update.clone();
5681                move |this, cx| {
5682                    assert_eq!(this.render_count, 2);
5683                    called_after_window_update.store(true, SeqCst);
5684                    cx.notify();
5685                }
5686            });
5687            assert!(!called_defer.load(SeqCst));
5688            assert!(!called_after_window_update.load(SeqCst));
5689            cx.notify();
5690        });
5691
5692        assert!(called_defer.load(SeqCst));
5693        assert!(called_after_window_update.load(SeqCst));
5694        assert_eq!(view.read(cx).render_count, 3);
5695    }
5696
5697    #[crate::test(self)]
5698    fn test_view_handles(cx: &mut MutableAppContext) {
5699        struct View {
5700            other: Option<ViewHandle<View>>,
5701            events: Vec<String>,
5702        }
5703
5704        impl Entity for View {
5705            type Event = usize;
5706        }
5707
5708        impl super::View for View {
5709            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5710                Empty::new().boxed()
5711            }
5712
5713            fn ui_name() -> &'static str {
5714                "View"
5715            }
5716        }
5717
5718        impl View {
5719            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
5720                if let Some(other) = other.as_ref() {
5721                    cx.subscribe(other, |me, _, event, _| {
5722                        me.events.push(format!("observed event {}", event));
5723                    })
5724                    .detach();
5725                }
5726                Self {
5727                    other,
5728                    events: Vec::new(),
5729                }
5730            }
5731        }
5732
5733        let (_, root_view) = cx.add_window(Default::default(), |cx| View::new(None, cx));
5734        let handle_1 = cx.add_view(&root_view, |cx| View::new(None, cx));
5735        let handle_2 = cx.add_view(&root_view, |cx| View::new(Some(handle_1.clone()), cx));
5736        assert_eq!(cx.cx.views.len(), 3);
5737
5738        handle_1.update(cx, |view, cx| {
5739            view.events.push("updated".into());
5740            cx.emit(1);
5741            cx.emit(2);
5742        });
5743        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5744        assert_eq!(
5745            handle_2.read(cx).events,
5746            vec![
5747                "observed event 1".to_string(),
5748                "observed event 2".to_string(),
5749            ]
5750        );
5751
5752        handle_2.update(cx, |view, _| {
5753            drop(handle_1);
5754            view.other.take();
5755        });
5756
5757        assert_eq!(cx.cx.views.len(), 2);
5758        assert!(cx.subscriptions.is_empty());
5759        assert!(cx.observations.is_empty());
5760    }
5761
5762    #[crate::test(self)]
5763    fn test_add_window(cx: &mut MutableAppContext) {
5764        struct View {
5765            mouse_down_count: Arc<AtomicUsize>,
5766        }
5767
5768        impl Entity for View {
5769            type Event = ();
5770        }
5771
5772        impl super::View for View {
5773            fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
5774                enum Handler {}
5775                let mouse_down_count = self.mouse_down_count.clone();
5776                MouseEventHandler::<Handler>::new(0, cx, |_, _| Empty::new().boxed())
5777                    .on_down(MouseButton::Left, move |_, _| {
5778                        mouse_down_count.fetch_add(1, SeqCst);
5779                    })
5780                    .boxed()
5781            }
5782
5783            fn ui_name() -> &'static str {
5784                "View"
5785            }
5786        }
5787
5788        let mouse_down_count = Arc::new(AtomicUsize::new(0));
5789        let (window_id, _) = cx.add_window(Default::default(), |_| View {
5790            mouse_down_count: mouse_down_count.clone(),
5791        });
5792        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
5793        // Ensure window's root element is in a valid lifecycle state.
5794        presenter.borrow_mut().dispatch_event(
5795            Event::MouseDown(MouseButtonEvent {
5796                position: Default::default(),
5797                button: MouseButton::Left,
5798                ctrl: false,
5799                alt: false,
5800                shift: false,
5801                cmd: false,
5802                click_count: 1,
5803            }),
5804            false,
5805            cx,
5806        );
5807        assert_eq!(mouse_down_count.load(SeqCst), 1);
5808    }
5809
5810    #[crate::test(self)]
5811    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
5812        struct Model {
5813            released: Rc<Cell<bool>>,
5814        }
5815
5816        struct View {
5817            released: Rc<Cell<bool>>,
5818        }
5819
5820        impl Entity for Model {
5821            type Event = ();
5822
5823            fn release(&mut self, _: &mut MutableAppContext) {
5824                self.released.set(true);
5825            }
5826        }
5827
5828        impl Entity for View {
5829            type Event = ();
5830
5831            fn release(&mut self, _: &mut MutableAppContext) {
5832                self.released.set(true);
5833            }
5834        }
5835
5836        impl super::View for View {
5837            fn ui_name() -> &'static str {
5838                "View"
5839            }
5840
5841            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5842                Empty::new().boxed()
5843            }
5844        }
5845
5846        let model_released = Rc::new(Cell::new(false));
5847        let model_release_observed = Rc::new(Cell::new(false));
5848        let view_released = Rc::new(Cell::new(false));
5849        let view_release_observed = Rc::new(Cell::new(false));
5850
5851        let model = cx.add_model(|_| Model {
5852            released: model_released.clone(),
5853        });
5854        let (window_id, view) = cx.add_window(Default::default(), |_| View {
5855            released: view_released.clone(),
5856        });
5857        assert!(!model_released.get());
5858        assert!(!view_released.get());
5859
5860        cx.observe_release(&model, {
5861            let model_release_observed = model_release_observed.clone();
5862            move |_, _| model_release_observed.set(true)
5863        })
5864        .detach();
5865        cx.observe_release(&view, {
5866            let view_release_observed = view_release_observed.clone();
5867            move |_, _| view_release_observed.set(true)
5868        })
5869        .detach();
5870
5871        cx.update(move |_| {
5872            drop(model);
5873        });
5874        assert!(model_released.get());
5875        assert!(model_release_observed.get());
5876
5877        drop(view);
5878        cx.remove_window(window_id);
5879        assert!(view_released.get());
5880        assert!(view_release_observed.get());
5881    }
5882
5883    #[crate::test(self)]
5884    fn test_view_events(cx: &mut MutableAppContext) {
5885        #[derive(Default)]
5886        struct View {
5887            events: Vec<usize>,
5888        }
5889
5890        impl Entity for View {
5891            type Event = usize;
5892        }
5893
5894        impl super::View for View {
5895            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5896                Empty::new().boxed()
5897            }
5898
5899            fn ui_name() -> &'static str {
5900                "View"
5901            }
5902        }
5903
5904        struct Model;
5905
5906        impl Entity for Model {
5907            type Event = usize;
5908        }
5909
5910        let (_, handle_1) = cx.add_window(Default::default(), |_| View::default());
5911        let handle_2 = cx.add_view(&handle_1, |_| View::default());
5912        let handle_3 = cx.add_model(|_| Model);
5913
5914        handle_1.update(cx, |_, cx| {
5915            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
5916                me.events.push(*event);
5917
5918                cx.subscribe(&emitter, |me, _, event, _| {
5919                    me.events.push(*event * 2);
5920                })
5921                .detach();
5922            })
5923            .detach();
5924
5925            cx.subscribe(&handle_3, |me, _, event, _| {
5926                me.events.push(*event);
5927            })
5928            .detach();
5929        });
5930
5931        handle_2.update(cx, |_, c| c.emit(7));
5932        assert_eq!(handle_1.read(cx).events, vec![7]);
5933
5934        handle_2.update(cx, |_, c| c.emit(5));
5935        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
5936
5937        handle_3.update(cx, |_, c| c.emit(9));
5938        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
5939    }
5940
5941    #[crate::test(self)]
5942    fn test_global_events(cx: &mut MutableAppContext) {
5943        #[derive(Clone, Debug, Eq, PartialEq)]
5944        struct GlobalEvent(u64);
5945
5946        let events = Rc::new(RefCell::new(Vec::new()));
5947        let first_subscription;
5948        let second_subscription;
5949
5950        {
5951            let events = events.clone();
5952            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5953                events.borrow_mut().push(("First", e.clone()));
5954            });
5955        }
5956
5957        {
5958            let events = events.clone();
5959            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5960                events.borrow_mut().push(("Second", e.clone()));
5961            });
5962        }
5963
5964        cx.update(|cx| {
5965            cx.emit_global(GlobalEvent(1));
5966            cx.emit_global(GlobalEvent(2));
5967        });
5968
5969        drop(first_subscription);
5970
5971        cx.update(|cx| {
5972            cx.emit_global(GlobalEvent(3));
5973        });
5974
5975        drop(second_subscription);
5976
5977        cx.update(|cx| {
5978            cx.emit_global(GlobalEvent(4));
5979        });
5980
5981        assert_eq!(
5982            &*events.borrow(),
5983            &[
5984                ("First", GlobalEvent(1)),
5985                ("Second", GlobalEvent(1)),
5986                ("First", GlobalEvent(2)),
5987                ("Second", GlobalEvent(2)),
5988                ("Second", GlobalEvent(3)),
5989            ]
5990        );
5991    }
5992
5993    #[crate::test(self)]
5994    fn test_global_events_emitted_before_subscription_in_same_update_cycle(
5995        cx: &mut MutableAppContext,
5996    ) {
5997        let events = Rc::new(RefCell::new(Vec::new()));
5998        cx.update(|cx| {
5999            {
6000                let events = events.clone();
6001                drop(cx.subscribe_global(move |_: &(), _| {
6002                    events.borrow_mut().push("dropped before emit");
6003                }));
6004            }
6005
6006            {
6007                let events = events.clone();
6008                cx.subscribe_global(move |_: &(), _| {
6009                    events.borrow_mut().push("before emit");
6010                })
6011                .detach();
6012            }
6013
6014            cx.emit_global(());
6015
6016            {
6017                let events = events.clone();
6018                cx.subscribe_global(move |_: &(), _| {
6019                    events.borrow_mut().push("after emit");
6020                })
6021                .detach();
6022            }
6023        });
6024
6025        assert_eq!(*events.borrow(), ["before emit"]);
6026    }
6027
6028    #[crate::test(self)]
6029    fn test_global_nested_events(cx: &mut MutableAppContext) {
6030        #[derive(Clone, Debug, Eq, PartialEq)]
6031        struct GlobalEvent(u64);
6032
6033        let events = Rc::new(RefCell::new(Vec::new()));
6034
6035        {
6036            let events = events.clone();
6037            cx.subscribe_global(move |e: &GlobalEvent, cx| {
6038                events.borrow_mut().push(("Outer", e.clone()));
6039
6040                if e.0 == 1 {
6041                    let events = events.clone();
6042                    cx.subscribe_global(move |e: &GlobalEvent, _| {
6043                        events.borrow_mut().push(("Inner", e.clone()));
6044                    })
6045                    .detach();
6046                }
6047            })
6048            .detach();
6049        }
6050
6051        cx.update(|cx| {
6052            cx.emit_global(GlobalEvent(1));
6053            cx.emit_global(GlobalEvent(2));
6054            cx.emit_global(GlobalEvent(3));
6055        });
6056        cx.update(|cx| {
6057            cx.emit_global(GlobalEvent(4));
6058        });
6059
6060        assert_eq!(
6061            &*events.borrow(),
6062            &[
6063                ("Outer", GlobalEvent(1)),
6064                ("Outer", GlobalEvent(2)),
6065                ("Outer", GlobalEvent(3)),
6066                ("Outer", GlobalEvent(4)),
6067                ("Inner", GlobalEvent(4)),
6068            ]
6069        );
6070    }
6071
6072    #[crate::test(self)]
6073    fn test_global(cx: &mut MutableAppContext) {
6074        type Global = usize;
6075
6076        let observation_count = Rc::new(RefCell::new(0));
6077        let subscription = cx.observe_global::<Global, _>({
6078            let observation_count = observation_count.clone();
6079            move |_| {
6080                *observation_count.borrow_mut() += 1;
6081            }
6082        });
6083
6084        assert!(!cx.has_global::<Global>());
6085        assert_eq!(cx.default_global::<Global>(), &0);
6086        assert_eq!(*observation_count.borrow(), 1);
6087        assert!(cx.has_global::<Global>());
6088        assert_eq!(
6089            cx.update_global::<Global, _, _>(|global, _| {
6090                *global = 1;
6091                "Update Result"
6092            }),
6093            "Update Result"
6094        );
6095        assert_eq!(*observation_count.borrow(), 2);
6096        assert_eq!(cx.global::<Global>(), &1);
6097
6098        drop(subscription);
6099        cx.update_global::<Global, _, _>(|global, _| {
6100            *global = 2;
6101        });
6102        assert_eq!(*observation_count.borrow(), 2);
6103
6104        type OtherGlobal = f32;
6105
6106        let observation_count = Rc::new(RefCell::new(0));
6107        cx.observe_global::<OtherGlobal, _>({
6108            let observation_count = observation_count.clone();
6109            move |_| {
6110                *observation_count.borrow_mut() += 1;
6111            }
6112        })
6113        .detach();
6114
6115        assert_eq!(
6116            cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
6117                assert_eq!(global, &0.0);
6118                *global = 2.0;
6119                "Default update result"
6120            }),
6121            "Default update result"
6122        );
6123        assert_eq!(cx.global::<OtherGlobal>(), &2.0);
6124        assert_eq!(*observation_count.borrow(), 1);
6125    }
6126
6127    #[crate::test(self)]
6128    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
6129        struct View;
6130
6131        impl Entity for View {
6132            type Event = ();
6133        }
6134
6135        impl super::View for View {
6136            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6137                Empty::new().boxed()
6138            }
6139
6140            fn ui_name() -> &'static str {
6141                "View"
6142            }
6143        }
6144
6145        struct Model;
6146
6147        impl Entity for Model {
6148            type Event = ();
6149        }
6150
6151        let (_, root_view) = cx.add_window(Default::default(), |_| View);
6152        let observing_view = cx.add_view(&root_view, |_| View);
6153        let emitting_view = cx.add_view(&root_view, |_| View);
6154        let observing_model = cx.add_model(|_| Model);
6155        let observed_model = cx.add_model(|_| Model);
6156
6157        observing_view.update(cx, |_, cx| {
6158            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
6159            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
6160        });
6161        observing_model.update(cx, |_, cx| {
6162            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
6163        });
6164
6165        cx.update(|_| {
6166            drop(observing_view);
6167            drop(observing_model);
6168        });
6169
6170        emitting_view.update(cx, |_, cx| cx.emit(()));
6171        observed_model.update(cx, |_, cx| cx.emit(()));
6172    }
6173
6174    #[crate::test(self)]
6175    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
6176        #[derive(Default)]
6177        struct TestView;
6178
6179        impl Entity for TestView {
6180            type Event = ();
6181        }
6182
6183        impl View for TestView {
6184            fn ui_name() -> &'static str {
6185                "TestView"
6186            }
6187
6188            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6189                Empty::new().boxed()
6190            }
6191        }
6192
6193        let events = Rc::new(RefCell::new(Vec::new()));
6194        cx.add_window(Default::default(), |cx| {
6195            drop(cx.subscribe(&cx.handle(), {
6196                let events = events.clone();
6197                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
6198            }));
6199            cx.subscribe(&cx.handle(), {
6200                let events = events.clone();
6201                move |_, _, _, _| events.borrow_mut().push("before emit")
6202            })
6203            .detach();
6204            cx.emit(());
6205            cx.subscribe(&cx.handle(), {
6206                let events = events.clone();
6207                move |_, _, _, _| events.borrow_mut().push("after emit")
6208            })
6209            .detach();
6210            TestView
6211        });
6212        assert_eq!(*events.borrow(), ["before emit"]);
6213    }
6214
6215    #[crate::test(self)]
6216    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
6217        #[derive(Default)]
6218        struct View {
6219            events: Vec<usize>,
6220        }
6221
6222        impl Entity for View {
6223            type Event = usize;
6224        }
6225
6226        impl super::View for View {
6227            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6228                Empty::new().boxed()
6229            }
6230
6231            fn ui_name() -> &'static str {
6232                "View"
6233            }
6234        }
6235
6236        #[derive(Default)]
6237        struct Model {
6238            count: usize,
6239        }
6240
6241        impl Entity for Model {
6242            type Event = ();
6243        }
6244
6245        let (_, view) = cx.add_window(Default::default(), |_| View::default());
6246        let model = cx.add_model(|_| Model::default());
6247
6248        view.update(cx, |_, c| {
6249            c.observe(&model, |me, observed, c| {
6250                me.events.push(observed.read(c).count)
6251            })
6252            .detach();
6253        });
6254
6255        model.update(cx, |model, c| {
6256            model.count = 11;
6257            c.notify();
6258        });
6259        assert_eq!(view.read(cx).events, vec![11]);
6260    }
6261
6262    #[crate::test(self)]
6263    fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
6264        #[derive(Default)]
6265        struct TestView;
6266
6267        impl Entity for TestView {
6268            type Event = ();
6269        }
6270
6271        impl View for TestView {
6272            fn ui_name() -> &'static str {
6273                "TestView"
6274            }
6275
6276            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6277                Empty::new().boxed()
6278            }
6279        }
6280
6281        let events = Rc::new(RefCell::new(Vec::new()));
6282        cx.add_window(Default::default(), |cx| {
6283            drop(cx.observe(&cx.handle(), {
6284                let events = events.clone();
6285                move |_, _, _| events.borrow_mut().push("dropped before flush")
6286            }));
6287            cx.observe(&cx.handle(), {
6288                let events = events.clone();
6289                move |_, _, _| events.borrow_mut().push("before notify")
6290            })
6291            .detach();
6292            cx.notify();
6293            cx.observe(&cx.handle(), {
6294                let events = events.clone();
6295                move |_, _, _| events.borrow_mut().push("after notify")
6296            })
6297            .detach();
6298            TestView
6299        });
6300        assert_eq!(*events.borrow(), ["before notify"]);
6301    }
6302
6303    #[crate::test(self)]
6304    fn test_dropping_observers(cx: &mut MutableAppContext) {
6305        struct View;
6306
6307        impl Entity for View {
6308            type Event = ();
6309        }
6310
6311        impl super::View for View {
6312            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6313                Empty::new().boxed()
6314            }
6315
6316            fn ui_name() -> &'static str {
6317                "View"
6318            }
6319        }
6320
6321        struct Model;
6322
6323        impl Entity for Model {
6324            type Event = ();
6325        }
6326
6327        let (_, root_view) = cx.add_window(Default::default(), |_| View);
6328        let observing_view = cx.add_view(root_view, |_| View);
6329        let observing_model = cx.add_model(|_| Model);
6330        let observed_model = cx.add_model(|_| Model);
6331
6332        observing_view.update(cx, |_, cx| {
6333            cx.observe(&observed_model, |_, _, _| {}).detach();
6334        });
6335        observing_model.update(cx, |_, cx| {
6336            cx.observe(&observed_model, |_, _, _| {}).detach();
6337        });
6338
6339        cx.update(|_| {
6340            drop(observing_view);
6341            drop(observing_model);
6342        });
6343
6344        observed_model.update(cx, |_, cx| cx.notify());
6345    }
6346
6347    #[crate::test(self)]
6348    fn test_dropping_subscriptions_during_callback(cx: &mut MutableAppContext) {
6349        struct Model;
6350
6351        impl Entity for Model {
6352            type Event = u64;
6353        }
6354
6355        // Events
6356        let observing_model = cx.add_model(|_| Model);
6357        let observed_model = cx.add_model(|_| Model);
6358
6359        let events = Rc::new(RefCell::new(Vec::new()));
6360
6361        observing_model.update(cx, |_, cx| {
6362            let events = events.clone();
6363            let subscription = Rc::new(RefCell::new(None));
6364            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
6365                let subscription = subscription.clone();
6366                move |_, _, e, _| {
6367                    subscription.borrow_mut().take();
6368                    events.borrow_mut().push(*e);
6369                }
6370            }));
6371        });
6372
6373        observed_model.update(cx, |_, cx| {
6374            cx.emit(1);
6375            cx.emit(2);
6376        });
6377
6378        assert_eq!(*events.borrow(), [1]);
6379
6380        // Global Events
6381        #[derive(Clone, Debug, Eq, PartialEq)]
6382        struct GlobalEvent(u64);
6383
6384        let events = Rc::new(RefCell::new(Vec::new()));
6385
6386        {
6387            let events = events.clone();
6388            let subscription = Rc::new(RefCell::new(None));
6389            *subscription.borrow_mut() = Some(cx.subscribe_global({
6390                let subscription = subscription.clone();
6391                move |e: &GlobalEvent, _| {
6392                    subscription.borrow_mut().take();
6393                    events.borrow_mut().push(e.clone());
6394                }
6395            }));
6396        }
6397
6398        cx.update(|cx| {
6399            cx.emit_global(GlobalEvent(1));
6400            cx.emit_global(GlobalEvent(2));
6401        });
6402
6403        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
6404
6405        // Model Observation
6406        let observing_model = cx.add_model(|_| Model);
6407        let observed_model = cx.add_model(|_| Model);
6408
6409        let observation_count = Rc::new(RefCell::new(0));
6410
6411        observing_model.update(cx, |_, cx| {
6412            let observation_count = observation_count.clone();
6413            let subscription = Rc::new(RefCell::new(None));
6414            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
6415                let subscription = subscription.clone();
6416                move |_, _, _| {
6417                    subscription.borrow_mut().take();
6418                    *observation_count.borrow_mut() += 1;
6419                }
6420            }));
6421        });
6422
6423        observed_model.update(cx, |_, cx| {
6424            cx.notify();
6425        });
6426
6427        observed_model.update(cx, |_, cx| {
6428            cx.notify();
6429        });
6430
6431        assert_eq!(*observation_count.borrow(), 1);
6432
6433        // View Observation
6434        struct View;
6435
6436        impl Entity for View {
6437            type Event = ();
6438        }
6439
6440        impl super::View for View {
6441            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6442                Empty::new().boxed()
6443            }
6444
6445            fn ui_name() -> &'static str {
6446                "View"
6447            }
6448        }
6449
6450        let (_, root_view) = cx.add_window(Default::default(), |_| View);
6451        let observing_view = cx.add_view(&root_view, |_| View);
6452        let observed_view = cx.add_view(&root_view, |_| View);
6453
6454        let observation_count = Rc::new(RefCell::new(0));
6455        observing_view.update(cx, |_, cx| {
6456            let observation_count = observation_count.clone();
6457            let subscription = Rc::new(RefCell::new(None));
6458            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
6459                let subscription = subscription.clone();
6460                move |_, _, _| {
6461                    subscription.borrow_mut().take();
6462                    *observation_count.borrow_mut() += 1;
6463                }
6464            }));
6465        });
6466
6467        observed_view.update(cx, |_, cx| {
6468            cx.notify();
6469        });
6470
6471        observed_view.update(cx, |_, cx| {
6472            cx.notify();
6473        });
6474
6475        assert_eq!(*observation_count.borrow(), 1);
6476
6477        // Global Observation
6478        let observation_count = Rc::new(RefCell::new(0));
6479        let subscription = Rc::new(RefCell::new(None));
6480        *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
6481            let observation_count = observation_count.clone();
6482            let subscription = subscription.clone();
6483            move |_| {
6484                subscription.borrow_mut().take();
6485                *observation_count.borrow_mut() += 1;
6486            }
6487        }));
6488
6489        cx.default_global::<()>();
6490        cx.set_global(());
6491        assert_eq!(*observation_count.borrow(), 1);
6492    }
6493
6494    #[crate::test(self)]
6495    fn test_focus(cx: &mut MutableAppContext) {
6496        struct View {
6497            name: String,
6498            events: Arc<Mutex<Vec<String>>>,
6499        }
6500
6501        impl Entity for View {
6502            type Event = ();
6503        }
6504
6505        impl super::View for View {
6506            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6507                Empty::new().boxed()
6508            }
6509
6510            fn ui_name() -> &'static str {
6511                "View"
6512            }
6513
6514            fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
6515                if cx.handle().id() == focused.id() {
6516                    self.events.lock().push(format!("{} focused", &self.name));
6517                }
6518            }
6519
6520            fn focus_out(&mut self, blurred: AnyViewHandle, cx: &mut ViewContext<Self>) {
6521                if cx.handle().id() == blurred.id() {
6522                    self.events.lock().push(format!("{} blurred", &self.name));
6523                }
6524            }
6525        }
6526
6527        let view_events: Arc<Mutex<Vec<String>>> = Default::default();
6528        let (_, view_1) = cx.add_window(Default::default(), |_| View {
6529            events: view_events.clone(),
6530            name: "view 1".to_string(),
6531        });
6532        let view_2 = cx.add_view(&view_1, |_| View {
6533            events: view_events.clone(),
6534            name: "view 2".to_string(),
6535        });
6536
6537        let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
6538        view_1.update(cx, |_, cx| {
6539            cx.observe_focus(&view_2, {
6540                let observed_events = observed_events.clone();
6541                move |this, view, focused, cx| {
6542                    let label = if focused { "focus" } else { "blur" };
6543                    observed_events.lock().push(format!(
6544                        "{} observed {}'s {}",
6545                        this.name,
6546                        view.read(cx).name,
6547                        label
6548                    ))
6549                }
6550            })
6551            .detach();
6552        });
6553        view_2.update(cx, |_, cx| {
6554            cx.observe_focus(&view_1, {
6555                let observed_events = observed_events.clone();
6556                move |this, view, focused, cx| {
6557                    let label = if focused { "focus" } else { "blur" };
6558                    observed_events.lock().push(format!(
6559                        "{} observed {}'s {}",
6560                        this.name,
6561                        view.read(cx).name,
6562                        label
6563                    ))
6564                }
6565            })
6566            .detach();
6567        });
6568        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6569        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6570
6571        view_1.update(cx, |_, cx| {
6572            // Ensure focus events are sent for all intermediate focuses
6573            cx.focus(&view_2);
6574            cx.focus(&view_1);
6575            cx.focus(&view_2);
6576        });
6577        assert_eq!(
6578            mem::take(&mut *view_events.lock()),
6579            [
6580                "view 1 blurred",
6581                "view 2 focused",
6582                "view 2 blurred",
6583                "view 1 focused",
6584                "view 1 blurred",
6585                "view 2 focused"
6586            ],
6587        );
6588        assert_eq!(
6589            mem::take(&mut *observed_events.lock()),
6590            [
6591                "view 2 observed view 1's blur",
6592                "view 1 observed view 2's focus",
6593                "view 1 observed view 2's blur",
6594                "view 2 observed view 1's focus",
6595                "view 2 observed view 1's blur",
6596                "view 1 observed view 2's focus"
6597            ]
6598        );
6599
6600        view_1.update(cx, |_, cx| cx.focus(&view_1));
6601        assert_eq!(
6602            mem::take(&mut *view_events.lock()),
6603            ["view 2 blurred", "view 1 focused"],
6604        );
6605        assert_eq!(
6606            mem::take(&mut *observed_events.lock()),
6607            [
6608                "view 1 observed view 2's blur",
6609                "view 2 observed view 1's focus"
6610            ]
6611        );
6612
6613        view_1.update(cx, |_, cx| cx.focus(&view_2));
6614        assert_eq!(
6615            mem::take(&mut *view_events.lock()),
6616            ["view 1 blurred", "view 2 focused"],
6617        );
6618        assert_eq!(
6619            mem::take(&mut *observed_events.lock()),
6620            [
6621                "view 2 observed view 1's blur",
6622                "view 1 observed view 2's focus"
6623            ]
6624        );
6625
6626        view_1.update(cx, |_, _| drop(view_2));
6627        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6628        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6629    }
6630
6631    #[crate::test(self)]
6632    fn test_deserialize_actions(cx: &mut MutableAppContext) {
6633        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6634        pub struct ComplexAction {
6635            arg: String,
6636            count: usize,
6637        }
6638
6639        actions!(test::something, [SimpleAction]);
6640        impl_actions!(test::something, [ComplexAction]);
6641
6642        cx.add_global_action(move |_: &SimpleAction, _: &mut MutableAppContext| {});
6643        cx.add_global_action(move |_: &ComplexAction, _: &mut MutableAppContext| {});
6644
6645        let action1 = cx
6646            .deserialize_action(
6647                "test::something::ComplexAction",
6648                Some(r#"{"arg": "a", "count": 5}"#),
6649            )
6650            .unwrap();
6651        let action2 = cx
6652            .deserialize_action("test::something::SimpleAction", None)
6653            .unwrap();
6654        assert_eq!(
6655            action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
6656            &ComplexAction {
6657                arg: "a".to_string(),
6658                count: 5,
6659            }
6660        );
6661        assert_eq!(
6662            action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
6663            &SimpleAction
6664        );
6665    }
6666
6667    #[crate::test(self)]
6668    fn test_dispatch_action(cx: &mut MutableAppContext) {
6669        struct ViewA {
6670            id: usize,
6671        }
6672
6673        impl Entity for ViewA {
6674            type Event = ();
6675        }
6676
6677        impl View for ViewA {
6678            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6679                Empty::new().boxed()
6680            }
6681
6682            fn ui_name() -> &'static str {
6683                "View"
6684            }
6685        }
6686
6687        struct ViewB {
6688            id: usize,
6689        }
6690
6691        impl Entity for ViewB {
6692            type Event = ();
6693        }
6694
6695        impl View for ViewB {
6696            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6697                Empty::new().boxed()
6698            }
6699
6700            fn ui_name() -> &'static str {
6701                "View"
6702            }
6703        }
6704
6705        #[derive(Clone, Default, Deserialize, PartialEq)]
6706        pub struct Action(pub String);
6707
6708        impl_actions!(test, [Action]);
6709
6710        let actions = Rc::new(RefCell::new(Vec::new()));
6711
6712        cx.add_global_action({
6713            let actions = actions.clone();
6714            move |_: &Action, _: &mut MutableAppContext| {
6715                actions.borrow_mut().push("global".to_string());
6716            }
6717        });
6718
6719        cx.add_action({
6720            let actions = actions.clone();
6721            move |view: &mut ViewA, action: &Action, cx| {
6722                assert_eq!(action.0, "bar");
6723                cx.propagate_action();
6724                actions.borrow_mut().push(format!("{} a", view.id));
6725            }
6726        });
6727
6728        cx.add_action({
6729            let actions = actions.clone();
6730            move |view: &mut ViewA, _: &Action, cx| {
6731                if view.id != 1 {
6732                    cx.add_view(|cx| {
6733                        cx.propagate_action(); // Still works on a nested ViewContext
6734                        ViewB { id: 5 }
6735                    });
6736                }
6737                actions.borrow_mut().push(format!("{} b", view.id));
6738            }
6739        });
6740
6741        cx.add_action({
6742            let actions = actions.clone();
6743            move |view: &mut ViewB, _: &Action, cx| {
6744                cx.propagate_action();
6745                actions.borrow_mut().push(format!("{} c", view.id));
6746            }
6747        });
6748
6749        cx.add_action({
6750            let actions = actions.clone();
6751            move |view: &mut ViewB, _: &Action, cx| {
6752                cx.propagate_action();
6753                actions.borrow_mut().push(format!("{} d", view.id));
6754            }
6755        });
6756
6757        cx.capture_action({
6758            let actions = actions.clone();
6759            move |view: &mut ViewA, _: &Action, cx| {
6760                cx.propagate_action();
6761                actions.borrow_mut().push(format!("{} capture", view.id));
6762            }
6763        });
6764
6765        let observed_actions = Rc::new(RefCell::new(Vec::new()));
6766        cx.observe_actions({
6767            let observed_actions = observed_actions.clone();
6768            move |action_id, _| observed_actions.borrow_mut().push(action_id)
6769        })
6770        .detach();
6771
6772        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
6773        let view_2 = cx.add_view(&view_1, |_| ViewB { id: 2 });
6774        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
6775        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
6776
6777        cx.handle_dispatch_action_from_effect(
6778            window_id,
6779            Some(view_4.id()),
6780            &Action("bar".to_string()),
6781        );
6782
6783        assert_eq!(
6784            *actions.borrow(),
6785            vec![
6786                "1 capture",
6787                "3 capture",
6788                "4 d",
6789                "4 c",
6790                "3 b",
6791                "3 a",
6792                "2 d",
6793                "2 c",
6794                "1 b"
6795            ]
6796        );
6797        assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
6798
6799        // Remove view_1, which doesn't propagate the action
6800
6801        let (window_id, view_2) = cx.add_window(Default::default(), |_| ViewB { id: 2 });
6802        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
6803        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
6804
6805        actions.borrow_mut().clear();
6806        cx.handle_dispatch_action_from_effect(
6807            window_id,
6808            Some(view_4.id()),
6809            &Action("bar".to_string()),
6810        );
6811
6812        assert_eq!(
6813            *actions.borrow(),
6814            vec![
6815                "3 capture",
6816                "4 d",
6817                "4 c",
6818                "3 b",
6819                "3 a",
6820                "2 d",
6821                "2 c",
6822                "global"
6823            ]
6824        );
6825        assert_eq!(
6826            *observed_actions.borrow(),
6827            [Action::default().id(), Action::default().id()]
6828        );
6829    }
6830
6831    #[crate::test(self)]
6832    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
6833        #[derive(Clone, Deserialize, PartialEq)]
6834        pub struct Action(String);
6835
6836        impl_actions!(test, [Action]);
6837
6838        struct View {
6839            id: usize,
6840            keymap_context: keymap::Context,
6841        }
6842
6843        impl Entity for View {
6844            type Event = ();
6845        }
6846
6847        impl super::View for View {
6848            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6849                Empty::new().boxed()
6850            }
6851
6852            fn ui_name() -> &'static str {
6853                "View"
6854            }
6855
6856            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
6857                self.keymap_context.clone()
6858            }
6859        }
6860
6861        impl View {
6862            fn new(id: usize) -> Self {
6863                View {
6864                    id,
6865                    keymap_context: keymap::Context::default(),
6866                }
6867            }
6868        }
6869
6870        let mut view_1 = View::new(1);
6871        let mut view_2 = View::new(2);
6872        let mut view_3 = View::new(3);
6873        view_1.keymap_context.set.insert("a".into());
6874        view_2.keymap_context.set.insert("a".into());
6875        view_2.keymap_context.set.insert("b".into());
6876        view_3.keymap_context.set.insert("a".into());
6877        view_3.keymap_context.set.insert("b".into());
6878        view_3.keymap_context.set.insert("c".into());
6879
6880        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
6881        let view_2 = cx.add_view(&view_1, |_| view_2);
6882        let _view_3 = cx.add_view(&view_2, |cx| {
6883            cx.focus_self();
6884            view_3
6885        });
6886
6887        // This keymap's only binding dispatches an action on view 2 because that view will have
6888        // "a" and "b" in its context, but not "c".
6889        cx.add_bindings(vec![keymap::Binding::new(
6890            "a",
6891            Action("a".to_string()),
6892            Some("a && b && !c"),
6893        )]);
6894
6895        cx.add_bindings(vec![keymap::Binding::new(
6896            "b",
6897            Action("b".to_string()),
6898            None,
6899        )]);
6900
6901        let actions = Rc::new(RefCell::new(Vec::new()));
6902        cx.add_action({
6903            let actions = actions.clone();
6904            move |view: &mut View, action: &Action, cx| {
6905                if action.0 == "a" {
6906                    actions.borrow_mut().push(format!("{} a", view.id));
6907                } else {
6908                    actions
6909                        .borrow_mut()
6910                        .push(format!("{} {}", view.id, action.0));
6911                    cx.propagate_action();
6912                }
6913            }
6914        });
6915
6916        cx.add_global_action({
6917            let actions = actions.clone();
6918            move |action: &Action, _| {
6919                actions.borrow_mut().push(format!("global {}", action.0));
6920            }
6921        });
6922
6923        cx.dispatch_keystroke(window_id, &Keystroke::parse("a").unwrap());
6924
6925        assert_eq!(&*actions.borrow(), &["2 a"]);
6926
6927        actions.borrow_mut().clear();
6928
6929        cx.dispatch_keystroke(window_id, &Keystroke::parse("b").unwrap());
6930
6931        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
6932    }
6933
6934    #[crate::test(self)]
6935    async fn test_model_condition(cx: &mut TestAppContext) {
6936        struct Counter(usize);
6937
6938        impl super::Entity for Counter {
6939            type Event = ();
6940        }
6941
6942        impl Counter {
6943            fn inc(&mut self, cx: &mut ModelContext<Self>) {
6944                self.0 += 1;
6945                cx.notify();
6946            }
6947        }
6948
6949        let model = cx.add_model(|_| Counter(0));
6950
6951        let condition1 = model.condition(cx, |model, _| model.0 == 2);
6952        let condition2 = model.condition(cx, |model, _| model.0 == 3);
6953        smol::pin!(condition1, condition2);
6954
6955        model.update(cx, |model, cx| model.inc(cx));
6956        assert_eq!(poll_once(&mut condition1).await, None);
6957        assert_eq!(poll_once(&mut condition2).await, None);
6958
6959        model.update(cx, |model, cx| model.inc(cx));
6960        assert_eq!(poll_once(&mut condition1).await, Some(()));
6961        assert_eq!(poll_once(&mut condition2).await, None);
6962
6963        model.update(cx, |model, cx| model.inc(cx));
6964        assert_eq!(poll_once(&mut condition2).await, Some(()));
6965
6966        model.update(cx, |_, cx| cx.notify());
6967    }
6968
6969    #[crate::test(self)]
6970    #[should_panic]
6971    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
6972        struct Model;
6973
6974        impl super::Entity for Model {
6975            type Event = ();
6976        }
6977
6978        let model = cx.add_model(|_| Model);
6979        model.condition(cx, |_, _| false).await;
6980    }
6981
6982    #[crate::test(self)]
6983    #[should_panic(expected = "model dropped with pending condition")]
6984    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
6985        struct Model;
6986
6987        impl super::Entity for Model {
6988            type Event = ();
6989        }
6990
6991        let model = cx.add_model(|_| Model);
6992        let condition = model.condition(cx, |_, _| false);
6993        cx.update(|_| drop(model));
6994        condition.await;
6995    }
6996
6997    #[crate::test(self)]
6998    async fn test_view_condition(cx: &mut TestAppContext) {
6999        struct Counter(usize);
7000
7001        impl super::Entity for Counter {
7002            type Event = ();
7003        }
7004
7005        impl super::View for Counter {
7006            fn ui_name() -> &'static str {
7007                "test view"
7008            }
7009
7010            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7011                Empty::new().boxed()
7012            }
7013        }
7014
7015        impl Counter {
7016            fn inc(&mut self, cx: &mut ViewContext<Self>) {
7017                self.0 += 1;
7018                cx.notify();
7019            }
7020        }
7021
7022        let (_, view) = cx.add_window(|_| Counter(0));
7023
7024        let condition1 = view.condition(cx, |view, _| view.0 == 2);
7025        let condition2 = view.condition(cx, |view, _| view.0 == 3);
7026        smol::pin!(condition1, condition2);
7027
7028        view.update(cx, |view, cx| view.inc(cx));
7029        assert_eq!(poll_once(&mut condition1).await, None);
7030        assert_eq!(poll_once(&mut condition2).await, None);
7031
7032        view.update(cx, |view, cx| view.inc(cx));
7033        assert_eq!(poll_once(&mut condition1).await, Some(()));
7034        assert_eq!(poll_once(&mut condition2).await, None);
7035
7036        view.update(cx, |view, cx| view.inc(cx));
7037        assert_eq!(poll_once(&mut condition2).await, Some(()));
7038        view.update(cx, |_, cx| cx.notify());
7039    }
7040
7041    #[crate::test(self)]
7042    #[should_panic]
7043    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
7044        struct View;
7045
7046        impl super::Entity for View {
7047            type Event = ();
7048        }
7049
7050        impl super::View for View {
7051            fn ui_name() -> &'static str {
7052                "test view"
7053            }
7054
7055            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7056                Empty::new().boxed()
7057            }
7058        }
7059
7060        let (_, view) = cx.add_window(|_| View);
7061        view.condition(cx, |_, _| false).await;
7062    }
7063
7064    #[crate::test(self)]
7065    #[should_panic(expected = "view dropped with pending condition")]
7066    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
7067        struct View;
7068
7069        impl super::Entity for View {
7070            type Event = ();
7071        }
7072
7073        impl super::View for View {
7074            fn ui_name() -> &'static str {
7075                "test view"
7076            }
7077
7078            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7079                Empty::new().boxed()
7080            }
7081        }
7082
7083        let (_, root_view) = cx.add_window(|_| View);
7084        let view = cx.add_view(&root_view, |_| View);
7085
7086        let condition = view.condition(cx, |_, _| false);
7087        cx.update(|_| drop(view));
7088        condition.await;
7089    }
7090
7091    #[crate::test(self)]
7092    fn test_refresh_windows(cx: &mut MutableAppContext) {
7093        struct View(usize);
7094
7095        impl super::Entity for View {
7096            type Event = ();
7097        }
7098
7099        impl super::View for View {
7100            fn ui_name() -> &'static str {
7101                "test view"
7102            }
7103
7104            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7105                Empty::new().named(format!("render count: {}", post_inc(&mut self.0)))
7106            }
7107        }
7108
7109        let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
7110        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
7111
7112        assert_eq!(
7113            presenter.borrow().rendered_views[&root_view.id()].name(),
7114            Some("render count: 0")
7115        );
7116
7117        let view = cx.add_view(&root_view, |cx| {
7118            cx.refresh_windows();
7119            View(0)
7120        });
7121
7122        assert_eq!(
7123            presenter.borrow().rendered_views[&root_view.id()].name(),
7124            Some("render count: 1")
7125        );
7126        assert_eq!(
7127            presenter.borrow().rendered_views[&view.id()].name(),
7128            Some("render count: 0")
7129        );
7130
7131        cx.update(|cx| cx.refresh_windows());
7132        assert_eq!(
7133            presenter.borrow().rendered_views[&root_view.id()].name(),
7134            Some("render count: 2")
7135        );
7136        assert_eq!(
7137            presenter.borrow().rendered_views[&view.id()].name(),
7138            Some("render count: 1")
7139        );
7140
7141        cx.update(|cx| {
7142            cx.refresh_windows();
7143            drop(view);
7144        });
7145        assert_eq!(
7146            presenter.borrow().rendered_views[&root_view.id()].name(),
7147            Some("render count: 3")
7148        );
7149        assert_eq!(presenter.borrow().rendered_views.len(), 1);
7150    }
7151
7152    #[crate::test(self)]
7153    async fn test_window_activation(cx: &mut TestAppContext) {
7154        struct View(&'static str);
7155
7156        impl super::Entity for View {
7157            type Event = ();
7158        }
7159
7160        impl super::View for View {
7161            fn ui_name() -> &'static str {
7162                "test view"
7163            }
7164
7165            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7166                Empty::new().boxed()
7167            }
7168        }
7169
7170        let events = Rc::new(RefCell::new(Vec::new()));
7171        let (window_1, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7172            cx.observe_window_activation({
7173                let events = events.clone();
7174                move |this, active, _| events.borrow_mut().push((this.0, active))
7175            })
7176            .detach();
7177            View("window 1")
7178        });
7179        assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
7180
7181        let (window_2, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7182            cx.observe_window_activation({
7183                let events = events.clone();
7184                move |this, active, _| events.borrow_mut().push((this.0, active))
7185            })
7186            .detach();
7187            View("window 2")
7188        });
7189        assert_eq!(
7190            mem::take(&mut *events.borrow_mut()),
7191            [("window 1", false), ("window 2", true)]
7192        );
7193
7194        let (window_3, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7195            cx.observe_window_activation({
7196                let events = events.clone();
7197                move |this, active, _| events.borrow_mut().push((this.0, active))
7198            })
7199            .detach();
7200            View("window 3")
7201        });
7202        assert_eq!(
7203            mem::take(&mut *events.borrow_mut()),
7204            [("window 2", false), ("window 3", true)]
7205        );
7206
7207        cx.simulate_window_activation(Some(window_2));
7208        assert_eq!(
7209            mem::take(&mut *events.borrow_mut()),
7210            [("window 3", false), ("window 2", true)]
7211        );
7212
7213        cx.simulate_window_activation(Some(window_1));
7214        assert_eq!(
7215            mem::take(&mut *events.borrow_mut()),
7216            [("window 2", false), ("window 1", true)]
7217        );
7218
7219        cx.simulate_window_activation(Some(window_3));
7220        assert_eq!(
7221            mem::take(&mut *events.borrow_mut()),
7222            [("window 1", false), ("window 3", true)]
7223        );
7224
7225        cx.simulate_window_activation(Some(window_3));
7226        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
7227    }
7228
7229    #[crate::test(self)]
7230    fn test_child_view(cx: &mut MutableAppContext) {
7231        struct Child {
7232            rendered: Rc<Cell<bool>>,
7233            dropped: Rc<Cell<bool>>,
7234        }
7235
7236        impl super::Entity for Child {
7237            type Event = ();
7238        }
7239
7240        impl super::View for Child {
7241            fn ui_name() -> &'static str {
7242                "child view"
7243            }
7244
7245            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7246                self.rendered.set(true);
7247                Empty::new().boxed()
7248            }
7249        }
7250
7251        impl Drop for Child {
7252            fn drop(&mut self) {
7253                self.dropped.set(true);
7254            }
7255        }
7256
7257        struct Parent {
7258            child: Option<ViewHandle<Child>>,
7259        }
7260
7261        impl super::Entity for Parent {
7262            type Event = ();
7263        }
7264
7265        impl super::View for Parent {
7266            fn ui_name() -> &'static str {
7267                "parent view"
7268            }
7269
7270            fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
7271                if let Some(child) = self.child.as_ref() {
7272                    ChildView::new(child, cx).boxed()
7273                } else {
7274                    Empty::new().boxed()
7275                }
7276            }
7277        }
7278
7279        let child_rendered = Rc::new(Cell::new(false));
7280        let child_dropped = Rc::new(Cell::new(false));
7281        let (_, root_view) = cx.add_window(Default::default(), |cx| Parent {
7282            child: Some(cx.add_view(|_| Child {
7283                rendered: child_rendered.clone(),
7284                dropped: child_dropped.clone(),
7285            })),
7286        });
7287        assert!(child_rendered.take());
7288        assert!(!child_dropped.take());
7289
7290        root_view.update(cx, |view, cx| {
7291            view.child.take();
7292            cx.notify();
7293        });
7294        assert!(!child_rendered.take());
7295        assert!(child_dropped.take());
7296    }
7297}