app.rs

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