app.rs

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