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