app.rs

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