app.rs

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