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