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