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