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