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