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