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_action(&mut self, action: impl Action) {
3839        self.app
3840            .dispatch_action_at(self.window_id, self.view_id, action)
3841    }
3842
3843    pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
3844        self.app
3845            .dispatch_any_action_at(self.window_id, self.view_id, action)
3846    }
3847
3848    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>)) {
3849        let handle = self.handle();
3850        self.app.defer(move |cx| {
3851            handle.update(cx, |view, cx| {
3852                callback(view, cx);
3853            })
3854        })
3855    }
3856
3857    pub fn after_window_update(
3858        &mut self,
3859        callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>),
3860    ) {
3861        let handle = self.handle();
3862        self.app.after_window_update(move |cx| {
3863            handle.update(cx, |view, cx| {
3864                callback(view, cx);
3865            })
3866        })
3867    }
3868
3869    pub fn propagate_action(&mut self) {
3870        self.app.halt_action_dispatch = false;
3871    }
3872
3873    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
3874    where
3875        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
3876        Fut: 'static + Future<Output = S>,
3877        S: 'static,
3878    {
3879        let handle = self.handle();
3880        self.app.spawn(|cx| f(handle, cx))
3881    }
3882
3883    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
3884    where
3885        F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut,
3886        Fut: 'static + Future<Output = S>,
3887        S: 'static,
3888    {
3889        let handle = self.weak_handle();
3890        self.app.spawn(|cx| f(handle, cx))
3891    }
3892}
3893
3894pub struct RenderParams {
3895    pub window_id: usize,
3896    pub view_id: usize,
3897    pub titlebar_height: f32,
3898    pub hovered_region_ids: HashSet<MouseRegionId>,
3899    pub clicked_region_ids: Option<(HashSet<MouseRegionId>, MouseButton)>,
3900    pub refreshing: bool,
3901    pub appearance: Appearance,
3902}
3903
3904pub struct RenderContext<'a, T: View> {
3905    pub(crate) window_id: usize,
3906    pub(crate) view_id: usize,
3907    pub(crate) view_type: PhantomData<T>,
3908    pub(crate) hovered_region_ids: HashSet<MouseRegionId>,
3909    pub(crate) clicked_region_ids: Option<(HashSet<MouseRegionId>, MouseButton)>,
3910    pub app: &'a mut MutableAppContext,
3911    pub titlebar_height: f32,
3912    pub appearance: Appearance,
3913    pub refreshing: bool,
3914}
3915
3916#[derive(Clone, Default)]
3917pub struct MouseState {
3918    hovered: bool,
3919    clicked: Option<MouseButton>,
3920    accessed_hovered: bool,
3921    accessed_clicked: bool,
3922}
3923
3924impl MouseState {
3925    pub fn hovered(&mut self) -> bool {
3926        self.accessed_hovered = true;
3927        self.hovered
3928    }
3929
3930    pub fn clicked(&mut self) -> Option<MouseButton> {
3931        self.accessed_clicked = true;
3932        self.clicked
3933    }
3934
3935    pub fn accessed_hovered(&self) -> bool {
3936        self.accessed_hovered
3937    }
3938
3939    pub fn accessed_clicked(&self) -> bool {
3940        self.accessed_clicked
3941    }
3942}
3943
3944impl<'a, V: View> RenderContext<'a, V> {
3945    fn new(params: RenderParams, app: &'a mut MutableAppContext) -> Self {
3946        Self {
3947            app,
3948            window_id: params.window_id,
3949            view_id: params.view_id,
3950            view_type: PhantomData,
3951            titlebar_height: params.titlebar_height,
3952            hovered_region_ids: params.hovered_region_ids.clone(),
3953            clicked_region_ids: params.clicked_region_ids.clone(),
3954            refreshing: params.refreshing,
3955            appearance: params.appearance,
3956        }
3957    }
3958
3959    pub fn handle(&self) -> WeakViewHandle<V> {
3960        WeakViewHandle::new(self.window_id, self.view_id)
3961    }
3962
3963    pub fn window_id(&self) -> usize {
3964        self.window_id
3965    }
3966
3967    pub fn view_id(&self) -> usize {
3968        self.view_id
3969    }
3970
3971    pub fn mouse_state<Tag: 'static>(&self, region_id: usize) -> MouseState {
3972        let region_id = MouseRegionId::new::<Tag>(self.view_id, region_id);
3973        MouseState {
3974            hovered: self.hovered_region_ids.contains(&region_id),
3975            clicked: self.clicked_region_ids.as_ref().and_then(|(ids, button)| {
3976                if ids.contains(&region_id) {
3977                    Some(*button)
3978                } else {
3979                    None
3980                }
3981            }),
3982            accessed_hovered: false,
3983            accessed_clicked: false,
3984        }
3985    }
3986
3987    pub fn element_state<Tag: 'static, T: 'static>(
3988        &mut self,
3989        element_id: usize,
3990        initial: T,
3991    ) -> ElementStateHandle<T> {
3992        let id = ElementStateId {
3993            view_id: self.view_id(),
3994            element_id,
3995            tag: TypeId::of::<Tag>(),
3996        };
3997        self.cx
3998            .element_states
3999            .entry(id)
4000            .or_insert_with(|| Box::new(initial));
4001        ElementStateHandle::new(id, self.frame_count, &self.cx.ref_counts)
4002    }
4003
4004    pub fn default_element_state<Tag: 'static, T: 'static + Default>(
4005        &mut self,
4006        element_id: usize,
4007    ) -> ElementStateHandle<T> {
4008        self.element_state::<Tag, T>(element_id, T::default())
4009    }
4010}
4011
4012impl AsRef<AppContext> for &AppContext {
4013    fn as_ref(&self) -> &AppContext {
4014        self
4015    }
4016}
4017
4018impl<V: View> Deref for RenderContext<'_, V> {
4019    type Target = MutableAppContext;
4020
4021    fn deref(&self) -> &Self::Target {
4022        self.app
4023    }
4024}
4025
4026impl<V: View> DerefMut for RenderContext<'_, V> {
4027    fn deref_mut(&mut self) -> &mut Self::Target {
4028        self.app
4029    }
4030}
4031
4032impl<V: View> ReadModel for RenderContext<'_, V> {
4033    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
4034        self.app.read_model(handle)
4035    }
4036}
4037
4038impl<V: View> UpdateModel for RenderContext<'_, V> {
4039    fn update_model<T: Entity, O>(
4040        &mut self,
4041        handle: &ModelHandle<T>,
4042        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
4043    ) -> O {
4044        self.app.update_model(handle, update)
4045    }
4046}
4047
4048impl<V: View> ReadView for RenderContext<'_, V> {
4049    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
4050        self.app.read_view(handle)
4051    }
4052}
4053
4054impl<M> AsRef<AppContext> for ViewContext<'_, M> {
4055    fn as_ref(&self) -> &AppContext {
4056        &self.app.cx
4057    }
4058}
4059
4060impl<M> Deref for ViewContext<'_, M> {
4061    type Target = MutableAppContext;
4062
4063    fn deref(&self) -> &Self::Target {
4064        self.app
4065    }
4066}
4067
4068impl<M> DerefMut for ViewContext<'_, M> {
4069    fn deref_mut(&mut self) -> &mut Self::Target {
4070        &mut self.app
4071    }
4072}
4073
4074impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
4075    fn as_mut(&mut self) -> &mut MutableAppContext {
4076        self.app
4077    }
4078}
4079
4080impl<V> ReadModel for ViewContext<'_, V> {
4081    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
4082        self.app.read_model(handle)
4083    }
4084}
4085
4086impl<V> UpgradeModelHandle for ViewContext<'_, V> {
4087    fn upgrade_model_handle<T: Entity>(
4088        &self,
4089        handle: &WeakModelHandle<T>,
4090    ) -> Option<ModelHandle<T>> {
4091        self.cx.upgrade_model_handle(handle)
4092    }
4093
4094    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
4095        self.cx.model_handle_is_upgradable(handle)
4096    }
4097
4098    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
4099        self.cx.upgrade_any_model_handle(handle)
4100    }
4101}
4102
4103impl<V> UpgradeViewHandle for ViewContext<'_, V> {
4104    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
4105        self.cx.upgrade_view_handle(handle)
4106    }
4107
4108    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
4109        self.cx.upgrade_any_view_handle(handle)
4110    }
4111}
4112
4113impl<V: View> UpgradeViewHandle for RenderContext<'_, V> {
4114    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
4115        self.cx.upgrade_view_handle(handle)
4116    }
4117
4118    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
4119        self.cx.upgrade_any_view_handle(handle)
4120    }
4121}
4122
4123impl<V: View> UpdateModel for ViewContext<'_, V> {
4124    fn update_model<T: Entity, O>(
4125        &mut self,
4126        handle: &ModelHandle<T>,
4127        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
4128    ) -> O {
4129        self.app.update_model(handle, update)
4130    }
4131}
4132
4133impl<V: View> ReadView for ViewContext<'_, V> {
4134    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
4135        self.app.read_view(handle)
4136    }
4137}
4138
4139impl<V: View> UpdateView for ViewContext<'_, V> {
4140    fn update_view<T, S>(
4141        &mut self,
4142        handle: &ViewHandle<T>,
4143        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
4144    ) -> S
4145    where
4146        T: View,
4147    {
4148        self.app.update_view(handle, update)
4149    }
4150}
4151
4152pub trait Handle<T> {
4153    type Weak: 'static;
4154    fn id(&self) -> usize;
4155    fn location(&self) -> EntityLocation;
4156    fn downgrade(&self) -> Self::Weak;
4157    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4158    where
4159        Self: Sized;
4160}
4161
4162pub trait WeakHandle {
4163    fn id(&self) -> usize;
4164}
4165
4166#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
4167pub enum EntityLocation {
4168    Model(usize),
4169    View(usize, usize),
4170}
4171
4172pub struct ModelHandle<T: Entity> {
4173    model_id: usize,
4174    model_type: PhantomData<T>,
4175    ref_counts: Arc<Mutex<RefCounts>>,
4176
4177    #[cfg(any(test, feature = "test-support"))]
4178    handle_id: usize,
4179}
4180
4181impl<T: Entity> ModelHandle<T> {
4182    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4183        ref_counts.lock().inc_model(model_id);
4184
4185        #[cfg(any(test, feature = "test-support"))]
4186        let handle_id = ref_counts
4187            .lock()
4188            .leak_detector
4189            .lock()
4190            .handle_created(Some(type_name::<T>()), model_id);
4191
4192        Self {
4193            model_id,
4194            model_type: PhantomData,
4195            ref_counts: ref_counts.clone(),
4196
4197            #[cfg(any(test, feature = "test-support"))]
4198            handle_id,
4199        }
4200    }
4201
4202    pub fn downgrade(&self) -> WeakModelHandle<T> {
4203        WeakModelHandle::new(self.model_id)
4204    }
4205
4206    pub fn id(&self) -> usize {
4207        self.model_id
4208    }
4209
4210    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
4211        cx.read_model(self)
4212    }
4213
4214    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
4215    where
4216        C: ReadModelWith,
4217        F: FnOnce(&T, &AppContext) -> S,
4218    {
4219        let mut read = Some(read);
4220        cx.read_model_with(self, &mut |model, cx| {
4221            let read = read.take().unwrap();
4222            read(model, cx)
4223        })
4224    }
4225
4226    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
4227    where
4228        C: UpdateModel,
4229        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
4230    {
4231        let mut update = Some(update);
4232        cx.update_model(self, &mut |model, cx| {
4233            let update = update.take().unwrap();
4234            update(model, cx)
4235        })
4236    }
4237}
4238
4239impl<T: Entity> Clone for ModelHandle<T> {
4240    fn clone(&self) -> Self {
4241        Self::new(self.model_id, &self.ref_counts)
4242    }
4243}
4244
4245impl<T: Entity> PartialEq for ModelHandle<T> {
4246    fn eq(&self, other: &Self) -> bool {
4247        self.model_id == other.model_id
4248    }
4249}
4250
4251impl<T: Entity> Eq for ModelHandle<T> {}
4252
4253impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
4254    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
4255        self.model_id == other.model_id
4256    }
4257}
4258
4259impl<T: Entity> Hash for ModelHandle<T> {
4260    fn hash<H: Hasher>(&self, state: &mut H) {
4261        self.model_id.hash(state);
4262    }
4263}
4264
4265impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
4266    fn borrow(&self) -> &usize {
4267        &self.model_id
4268    }
4269}
4270
4271impl<T: Entity> Debug for ModelHandle<T> {
4272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4273        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
4274            .field(&self.model_id)
4275            .finish()
4276    }
4277}
4278
4279unsafe impl<T: Entity> Send for ModelHandle<T> {}
4280unsafe impl<T: Entity> Sync for ModelHandle<T> {}
4281
4282impl<T: Entity> Drop for ModelHandle<T> {
4283    fn drop(&mut self) {
4284        let mut ref_counts = self.ref_counts.lock();
4285        ref_counts.dec_model(self.model_id);
4286
4287        #[cfg(any(test, feature = "test-support"))]
4288        ref_counts
4289            .leak_detector
4290            .lock()
4291            .handle_dropped(self.model_id, self.handle_id);
4292    }
4293}
4294
4295impl<T: Entity> Handle<T> for ModelHandle<T> {
4296    type Weak = WeakModelHandle<T>;
4297
4298    fn id(&self) -> usize {
4299        self.model_id
4300    }
4301
4302    fn location(&self) -> EntityLocation {
4303        EntityLocation::Model(self.model_id)
4304    }
4305
4306    fn downgrade(&self) -> Self::Weak {
4307        self.downgrade()
4308    }
4309
4310    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4311    where
4312        Self: Sized,
4313    {
4314        weak.upgrade(cx)
4315    }
4316}
4317
4318pub struct WeakModelHandle<T> {
4319    model_id: usize,
4320    model_type: PhantomData<T>,
4321}
4322
4323impl<T> WeakHandle for WeakModelHandle<T> {
4324    fn id(&self) -> usize {
4325        self.model_id
4326    }
4327}
4328
4329unsafe impl<T> Send for WeakModelHandle<T> {}
4330unsafe impl<T> Sync for WeakModelHandle<T> {}
4331
4332impl<T: Entity> WeakModelHandle<T> {
4333    fn new(model_id: usize) -> Self {
4334        Self {
4335            model_id,
4336            model_type: PhantomData,
4337        }
4338    }
4339
4340    pub fn id(&self) -> usize {
4341        self.model_id
4342    }
4343
4344    pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
4345        cx.model_handle_is_upgradable(self)
4346    }
4347
4348    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
4349        cx.upgrade_model_handle(self)
4350    }
4351}
4352
4353impl<T> Hash for WeakModelHandle<T> {
4354    fn hash<H: Hasher>(&self, state: &mut H) {
4355        self.model_id.hash(state)
4356    }
4357}
4358
4359impl<T> PartialEq for WeakModelHandle<T> {
4360    fn eq(&self, other: &Self) -> bool {
4361        self.model_id == other.model_id
4362    }
4363}
4364
4365impl<T> Eq for WeakModelHandle<T> {}
4366
4367impl<T: Entity> PartialEq<ModelHandle<T>> for WeakModelHandle<T> {
4368    fn eq(&self, other: &ModelHandle<T>) -> bool {
4369        self.model_id == other.model_id
4370    }
4371}
4372
4373impl<T> Clone for WeakModelHandle<T> {
4374    fn clone(&self) -> Self {
4375        Self {
4376            model_id: self.model_id,
4377            model_type: PhantomData,
4378        }
4379    }
4380}
4381
4382impl<T> Copy for WeakModelHandle<T> {}
4383
4384pub struct ViewHandle<T> {
4385    window_id: usize,
4386    view_id: usize,
4387    view_type: PhantomData<T>,
4388    ref_counts: Arc<Mutex<RefCounts>>,
4389    #[cfg(any(test, feature = "test-support"))]
4390    handle_id: usize,
4391}
4392
4393impl<T: View> ViewHandle<T> {
4394    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4395        ref_counts.lock().inc_view(window_id, view_id);
4396        #[cfg(any(test, feature = "test-support"))]
4397        let handle_id = ref_counts
4398            .lock()
4399            .leak_detector
4400            .lock()
4401            .handle_created(Some(type_name::<T>()), view_id);
4402
4403        Self {
4404            window_id,
4405            view_id,
4406            view_type: PhantomData,
4407            ref_counts: ref_counts.clone(),
4408
4409            #[cfg(any(test, feature = "test-support"))]
4410            handle_id,
4411        }
4412    }
4413
4414    pub fn downgrade(&self) -> WeakViewHandle<T> {
4415        WeakViewHandle::new(self.window_id, self.view_id)
4416    }
4417
4418    pub fn window_id(&self) -> usize {
4419        self.window_id
4420    }
4421
4422    pub fn id(&self) -> usize {
4423        self.view_id
4424    }
4425
4426    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
4427        cx.read_view(self)
4428    }
4429
4430    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
4431    where
4432        C: ReadViewWith,
4433        F: FnOnce(&T, &AppContext) -> S,
4434    {
4435        let mut read = Some(read);
4436        cx.read_view_with(self, &mut |view, cx| {
4437            let read = read.take().unwrap();
4438            read(view, cx)
4439        })
4440    }
4441
4442    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
4443    where
4444        C: UpdateView,
4445        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
4446    {
4447        let mut update = Some(update);
4448        cx.update_view(self, &mut |view, cx| {
4449            let update = update.take().unwrap();
4450            update(view, cx)
4451        })
4452    }
4453
4454    pub fn defer<C, F>(&self, cx: &mut C, update: F)
4455    where
4456        C: AsMut<MutableAppContext>,
4457        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
4458    {
4459        let this = self.clone();
4460        cx.as_mut().defer(move |cx| {
4461            this.update(cx, |view, cx| update(view, cx));
4462        });
4463    }
4464
4465    pub fn is_focused(&self, cx: &AppContext) -> bool {
4466        cx.focused_view_id(self.window_id)
4467            .map_or(false, |focused_id| focused_id == self.view_id)
4468    }
4469}
4470
4471impl<T: View> Clone for ViewHandle<T> {
4472    fn clone(&self) -> Self {
4473        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
4474    }
4475}
4476
4477impl<T> PartialEq for ViewHandle<T> {
4478    fn eq(&self, other: &Self) -> bool {
4479        self.window_id == other.window_id && self.view_id == other.view_id
4480    }
4481}
4482
4483impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
4484    fn eq(&self, other: &WeakViewHandle<T>) -> bool {
4485        self.window_id == other.window_id && self.view_id == other.view_id
4486    }
4487}
4488
4489impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
4490    fn eq(&self, other: &ViewHandle<T>) -> bool {
4491        self.window_id == other.window_id && self.view_id == other.view_id
4492    }
4493}
4494
4495impl<T> Eq for ViewHandle<T> {}
4496
4497impl<T> Hash for ViewHandle<T> {
4498    fn hash<H: Hasher>(&self, state: &mut H) {
4499        self.window_id.hash(state);
4500        self.view_id.hash(state);
4501    }
4502}
4503
4504impl<T> Debug for ViewHandle<T> {
4505    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4506        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
4507            .field("window_id", &self.window_id)
4508            .field("view_id", &self.view_id)
4509            .finish()
4510    }
4511}
4512
4513impl<T> Drop for ViewHandle<T> {
4514    fn drop(&mut self) {
4515        self.ref_counts
4516            .lock()
4517            .dec_view(self.window_id, self.view_id);
4518        #[cfg(any(test, feature = "test-support"))]
4519        self.ref_counts
4520            .lock()
4521            .leak_detector
4522            .lock()
4523            .handle_dropped(self.view_id, self.handle_id);
4524    }
4525}
4526
4527impl<T: View> Handle<T> for ViewHandle<T> {
4528    type Weak = WeakViewHandle<T>;
4529
4530    fn id(&self) -> usize {
4531        self.view_id
4532    }
4533
4534    fn location(&self) -> EntityLocation {
4535        EntityLocation::View(self.window_id, self.view_id)
4536    }
4537
4538    fn downgrade(&self) -> Self::Weak {
4539        self.downgrade()
4540    }
4541
4542    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4543    where
4544        Self: Sized,
4545    {
4546        weak.upgrade(cx)
4547    }
4548}
4549
4550pub struct AnyViewHandle {
4551    window_id: usize,
4552    view_id: usize,
4553    view_type: TypeId,
4554    ref_counts: Arc<Mutex<RefCounts>>,
4555
4556    #[cfg(any(test, feature = "test-support"))]
4557    handle_id: usize,
4558}
4559
4560impl AnyViewHandle {
4561    fn new(
4562        window_id: usize,
4563        view_id: usize,
4564        view_type: TypeId,
4565        ref_counts: Arc<Mutex<RefCounts>>,
4566    ) -> Self {
4567        ref_counts.lock().inc_view(window_id, view_id);
4568
4569        #[cfg(any(test, feature = "test-support"))]
4570        let handle_id = ref_counts
4571            .lock()
4572            .leak_detector
4573            .lock()
4574            .handle_created(None, view_id);
4575
4576        Self {
4577            window_id,
4578            view_id,
4579            view_type,
4580            ref_counts,
4581            #[cfg(any(test, feature = "test-support"))]
4582            handle_id,
4583        }
4584    }
4585
4586    pub fn window_id(&self) -> usize {
4587        self.window_id
4588    }
4589
4590    pub fn id(&self) -> usize {
4591        self.view_id
4592    }
4593
4594    pub fn is<T: 'static>(&self) -> bool {
4595        TypeId::of::<T>() == self.view_type
4596    }
4597
4598    pub fn is_focused(&self, cx: &AppContext) -> bool {
4599        cx.focused_view_id(self.window_id)
4600            .map_or(false, |focused_id| focused_id == self.view_id)
4601    }
4602
4603    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
4604        if self.is::<T>() {
4605            let result = Some(ViewHandle {
4606                window_id: self.window_id,
4607                view_id: self.view_id,
4608                ref_counts: self.ref_counts.clone(),
4609                view_type: PhantomData,
4610                #[cfg(any(test, feature = "test-support"))]
4611                handle_id: self.handle_id,
4612            });
4613            unsafe {
4614                Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
4615            }
4616            std::mem::forget(self);
4617            result
4618        } else {
4619            None
4620        }
4621    }
4622
4623    pub fn downgrade(&self) -> AnyWeakViewHandle {
4624        AnyWeakViewHandle {
4625            window_id: self.window_id,
4626            view_id: self.view_id,
4627            view_type: self.view_type,
4628        }
4629    }
4630
4631    pub fn view_type(&self) -> TypeId {
4632        self.view_type
4633    }
4634
4635    pub fn debug_json(&self, cx: &AppContext) -> serde_json::Value {
4636        cx.views
4637            .get(&(self.window_id, self.view_id))
4638            .map_or_else(|| serde_json::Value::Null, |view| view.debug_json(cx))
4639    }
4640}
4641
4642impl Clone for AnyViewHandle {
4643    fn clone(&self) -> Self {
4644        Self::new(
4645            self.window_id,
4646            self.view_id,
4647            self.view_type,
4648            self.ref_counts.clone(),
4649        )
4650    }
4651}
4652
4653impl From<&AnyViewHandle> for AnyViewHandle {
4654    fn from(handle: &AnyViewHandle) -> Self {
4655        handle.clone()
4656    }
4657}
4658
4659impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
4660    fn from(handle: &ViewHandle<T>) -> Self {
4661        Self::new(
4662            handle.window_id,
4663            handle.view_id,
4664            TypeId::of::<T>(),
4665            handle.ref_counts.clone(),
4666        )
4667    }
4668}
4669
4670impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
4671    fn from(handle: ViewHandle<T>) -> Self {
4672        let any_handle = AnyViewHandle {
4673            window_id: handle.window_id,
4674            view_id: handle.view_id,
4675            view_type: TypeId::of::<T>(),
4676            ref_counts: handle.ref_counts.clone(),
4677            #[cfg(any(test, feature = "test-support"))]
4678            handle_id: handle.handle_id,
4679        };
4680
4681        unsafe {
4682            Arc::decrement_strong_count(Arc::as_ptr(&handle.ref_counts));
4683        }
4684        std::mem::forget(handle);
4685        any_handle
4686    }
4687}
4688
4689impl Drop for AnyViewHandle {
4690    fn drop(&mut self) {
4691        self.ref_counts
4692            .lock()
4693            .dec_view(self.window_id, self.view_id);
4694        #[cfg(any(test, feature = "test-support"))]
4695        self.ref_counts
4696            .lock()
4697            .leak_detector
4698            .lock()
4699            .handle_dropped(self.view_id, self.handle_id);
4700    }
4701}
4702
4703pub struct AnyModelHandle {
4704    model_id: usize,
4705    model_type: TypeId,
4706    ref_counts: Arc<Mutex<RefCounts>>,
4707
4708    #[cfg(any(test, feature = "test-support"))]
4709    handle_id: usize,
4710}
4711
4712impl AnyModelHandle {
4713    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
4714        ref_counts.lock().inc_model(model_id);
4715
4716        #[cfg(any(test, feature = "test-support"))]
4717        let handle_id = ref_counts
4718            .lock()
4719            .leak_detector
4720            .lock()
4721            .handle_created(None, model_id);
4722
4723        Self {
4724            model_id,
4725            model_type,
4726            ref_counts,
4727
4728            #[cfg(any(test, feature = "test-support"))]
4729            handle_id,
4730        }
4731    }
4732
4733    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
4734        if self.is::<T>() {
4735            let result = Some(ModelHandle {
4736                model_id: self.model_id,
4737                model_type: PhantomData,
4738                ref_counts: self.ref_counts.clone(),
4739
4740                #[cfg(any(test, feature = "test-support"))]
4741                handle_id: self.handle_id,
4742            });
4743            unsafe {
4744                Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
4745            }
4746            std::mem::forget(self);
4747            result
4748        } else {
4749            None
4750        }
4751    }
4752
4753    pub fn downgrade(&self) -> AnyWeakModelHandle {
4754        AnyWeakModelHandle {
4755            model_id: self.model_id,
4756            model_type: self.model_type,
4757        }
4758    }
4759
4760    pub fn is<T: Entity>(&self) -> bool {
4761        self.model_type == TypeId::of::<T>()
4762    }
4763
4764    pub fn model_type(&self) -> TypeId {
4765        self.model_type
4766    }
4767}
4768
4769impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
4770    fn from(handle: ModelHandle<T>) -> Self {
4771        Self::new(
4772            handle.model_id,
4773            TypeId::of::<T>(),
4774            handle.ref_counts.clone(),
4775        )
4776    }
4777}
4778
4779impl Clone for AnyModelHandle {
4780    fn clone(&self) -> Self {
4781        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
4782    }
4783}
4784
4785impl Drop for AnyModelHandle {
4786    fn drop(&mut self) {
4787        let mut ref_counts = self.ref_counts.lock();
4788        ref_counts.dec_model(self.model_id);
4789
4790        #[cfg(any(test, feature = "test-support"))]
4791        ref_counts
4792            .leak_detector
4793            .lock()
4794            .handle_dropped(self.model_id, self.handle_id);
4795    }
4796}
4797
4798#[derive(Hash, PartialEq, Eq, Debug)]
4799pub struct AnyWeakModelHandle {
4800    model_id: usize,
4801    model_type: TypeId,
4802}
4803
4804impl AnyWeakModelHandle {
4805    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
4806        cx.upgrade_any_model_handle(self)
4807    }
4808    pub fn model_type(&self) -> TypeId {
4809        self.model_type
4810    }
4811
4812    fn is<T: 'static>(&self) -> bool {
4813        TypeId::of::<T>() == self.model_type
4814    }
4815
4816    pub fn downcast<T: Entity>(&self) -> Option<WeakModelHandle<T>> {
4817        if self.is::<T>() {
4818            let result = Some(WeakModelHandle {
4819                model_id: self.model_id,
4820                model_type: PhantomData,
4821            });
4822
4823            result
4824        } else {
4825            None
4826        }
4827    }
4828}
4829
4830impl<T: Entity> From<WeakModelHandle<T>> for AnyWeakModelHandle {
4831    fn from(handle: WeakModelHandle<T>) -> Self {
4832        AnyWeakModelHandle {
4833            model_id: handle.model_id,
4834            model_type: TypeId::of::<T>(),
4835        }
4836    }
4837}
4838
4839#[derive(Debug)]
4840pub struct WeakViewHandle<T> {
4841    window_id: usize,
4842    view_id: usize,
4843    view_type: PhantomData<T>,
4844}
4845
4846impl<T> WeakHandle for WeakViewHandle<T> {
4847    fn id(&self) -> usize {
4848        self.view_id
4849    }
4850}
4851
4852impl<T: View> WeakViewHandle<T> {
4853    fn new(window_id: usize, view_id: usize) -> Self {
4854        Self {
4855            window_id,
4856            view_id,
4857            view_type: PhantomData,
4858        }
4859    }
4860
4861    pub fn id(&self) -> usize {
4862        self.view_id
4863    }
4864
4865    pub fn window_id(&self) -> usize {
4866        self.window_id
4867    }
4868
4869    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
4870        cx.upgrade_view_handle(self)
4871    }
4872}
4873
4874impl<T> Clone for WeakViewHandle<T> {
4875    fn clone(&self) -> Self {
4876        Self {
4877            window_id: self.window_id,
4878            view_id: self.view_id,
4879            view_type: PhantomData,
4880        }
4881    }
4882}
4883
4884impl<T> PartialEq for WeakViewHandle<T> {
4885    fn eq(&self, other: &Self) -> bool {
4886        self.window_id == other.window_id && self.view_id == other.view_id
4887    }
4888}
4889
4890impl<T> Eq for WeakViewHandle<T> {}
4891
4892impl<T> Hash for WeakViewHandle<T> {
4893    fn hash<H: Hasher>(&self, state: &mut H) {
4894        self.window_id.hash(state);
4895        self.view_id.hash(state);
4896    }
4897}
4898
4899pub struct AnyWeakViewHandle {
4900    window_id: usize,
4901    view_id: usize,
4902    view_type: TypeId,
4903}
4904
4905impl AnyWeakViewHandle {
4906    pub fn id(&self) -> usize {
4907        self.view_id
4908    }
4909
4910    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<AnyViewHandle> {
4911        cx.upgrade_any_view_handle(self)
4912    }
4913}
4914
4915impl<T: View> From<WeakViewHandle<T>> for AnyWeakViewHandle {
4916    fn from(handle: WeakViewHandle<T>) -> Self {
4917        AnyWeakViewHandle {
4918            window_id: handle.window_id,
4919            view_id: handle.view_id,
4920            view_type: TypeId::of::<T>(),
4921        }
4922    }
4923}
4924
4925#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4926pub struct ElementStateId {
4927    view_id: usize,
4928    element_id: usize,
4929    tag: TypeId,
4930}
4931
4932pub struct ElementStateHandle<T> {
4933    value_type: PhantomData<T>,
4934    id: ElementStateId,
4935    ref_counts: Weak<Mutex<RefCounts>>,
4936}
4937
4938impl<T: 'static> ElementStateHandle<T> {
4939    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4940        ref_counts.lock().inc_element_state(id, frame_id);
4941        Self {
4942            value_type: PhantomData,
4943            id,
4944            ref_counts: Arc::downgrade(ref_counts),
4945        }
4946    }
4947
4948    pub fn id(&self) -> ElementStateId {
4949        self.id
4950    }
4951
4952    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
4953        cx.element_states
4954            .get(&self.id)
4955            .unwrap()
4956            .downcast_ref()
4957            .unwrap()
4958    }
4959
4960    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
4961    where
4962        C: DerefMut<Target = MutableAppContext>,
4963    {
4964        let mut element_state = cx.deref_mut().cx.element_states.remove(&self.id).unwrap();
4965        let result = f(element_state.downcast_mut().unwrap(), cx);
4966        cx.deref_mut()
4967            .cx
4968            .element_states
4969            .insert(self.id, element_state);
4970        result
4971    }
4972}
4973
4974impl<T> Drop for ElementStateHandle<T> {
4975    fn drop(&mut self) {
4976        if let Some(ref_counts) = self.ref_counts.upgrade() {
4977            ref_counts.lock().dec_element_state(self.id);
4978        }
4979    }
4980}
4981
4982#[must_use]
4983pub enum Subscription {
4984    Subscription {
4985        id: usize,
4986        entity_id: usize,
4987        subscriptions: Option<Weak<Mapping<usize, SubscriptionCallback>>>,
4988    },
4989    GlobalSubscription {
4990        id: usize,
4991        type_id: TypeId,
4992        subscriptions: Option<Weak<Mapping<TypeId, GlobalSubscriptionCallback>>>,
4993    },
4994    Observation {
4995        id: usize,
4996        entity_id: usize,
4997        observations: Option<Weak<Mapping<usize, ObservationCallback>>>,
4998    },
4999    GlobalObservation {
5000        id: usize,
5001        type_id: TypeId,
5002        observations: Option<Weak<Mapping<TypeId, GlobalObservationCallback>>>,
5003    },
5004    FocusObservation {
5005        id: usize,
5006        view_id: usize,
5007        observations: Option<Weak<Mapping<usize, FocusObservationCallback>>>,
5008    },
5009    WindowActivationObservation {
5010        id: usize,
5011        window_id: usize,
5012        observations: Option<Weak<Mapping<usize, WindowActivationCallback>>>,
5013    },
5014    WindowFullscreenObservation {
5015        id: usize,
5016        window_id: usize,
5017        observations: Option<Weak<Mapping<usize, WindowFullscreenCallback>>>,
5018    },
5019
5020    ReleaseObservation {
5021        id: usize,
5022        entity_id: usize,
5023        #[allow(clippy::type_complexity)]
5024        observations:
5025            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>>,
5026    },
5027    ActionObservation {
5028        id: usize,
5029        observations: Option<Weak<Mutex<BTreeMap<usize, ActionObservationCallback>>>>,
5030    },
5031}
5032
5033impl Subscription {
5034    pub fn detach(&mut self) {
5035        match self {
5036            Subscription::Subscription { subscriptions, .. } => {
5037                subscriptions.take();
5038            }
5039            Subscription::GlobalSubscription { subscriptions, .. } => {
5040                subscriptions.take();
5041            }
5042            Subscription::Observation { observations, .. } => {
5043                observations.take();
5044            }
5045            Subscription::GlobalObservation { observations, .. } => {
5046                observations.take();
5047            }
5048            Subscription::ReleaseObservation { observations, .. } => {
5049                observations.take();
5050            }
5051            Subscription::FocusObservation { observations, .. } => {
5052                observations.take();
5053            }
5054            Subscription::ActionObservation { observations, .. } => {
5055                observations.take();
5056            }
5057            Subscription::WindowActivationObservation { observations, .. } => {
5058                observations.take();
5059            }
5060            Subscription::WindowFullscreenObservation { observations, .. } => {
5061                observations.take();
5062            }
5063        }
5064    }
5065}
5066
5067impl Drop for Subscription {
5068    fn drop(&mut self) {
5069        match self {
5070            Subscription::Subscription {
5071                id,
5072                entity_id,
5073                subscriptions,
5074            } => {
5075                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
5076                    match subscriptions
5077                        .lock()
5078                        .entry(*entity_id)
5079                        .or_default()
5080                        .entry(*id)
5081                    {
5082                        btree_map::Entry::Vacant(entry) => {
5083                            entry.insert(None);
5084                        }
5085                        btree_map::Entry::Occupied(entry) => {
5086                            entry.remove();
5087                        }
5088                    }
5089                }
5090            }
5091            Subscription::GlobalSubscription {
5092                id,
5093                type_id,
5094                subscriptions,
5095            } => {
5096                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
5097                    match subscriptions.lock().entry(*type_id).or_default().entry(*id) {
5098                        btree_map::Entry::Vacant(entry) => {
5099                            entry.insert(None);
5100                        }
5101                        btree_map::Entry::Occupied(entry) => {
5102                            entry.remove();
5103                        }
5104                    }
5105                }
5106            }
5107            Subscription::Observation {
5108                id,
5109                entity_id,
5110                observations,
5111            } => {
5112                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5113                    match observations
5114                        .lock()
5115                        .entry(*entity_id)
5116                        .or_default()
5117                        .entry(*id)
5118                    {
5119                        btree_map::Entry::Vacant(entry) => {
5120                            entry.insert(None);
5121                        }
5122                        btree_map::Entry::Occupied(entry) => {
5123                            entry.remove();
5124                        }
5125                    }
5126                }
5127            }
5128            Subscription::GlobalObservation {
5129                id,
5130                type_id,
5131                observations,
5132            } => {
5133                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5134                    match observations.lock().entry(*type_id).or_default().entry(*id) {
5135                        collections::btree_map::Entry::Vacant(entry) => {
5136                            entry.insert(None);
5137                        }
5138                        collections::btree_map::Entry::Occupied(entry) => {
5139                            entry.remove();
5140                        }
5141                    }
5142                }
5143            }
5144            Subscription::ReleaseObservation {
5145                id,
5146                entity_id,
5147                observations,
5148            } => {
5149                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5150                    if let Some(observations) = observations.lock().get_mut(entity_id) {
5151                        observations.remove(id);
5152                    }
5153                }
5154            }
5155            Subscription::FocusObservation {
5156                id,
5157                view_id,
5158                observations,
5159            } => {
5160                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5161                    match observations.lock().entry(*view_id).or_default().entry(*id) {
5162                        btree_map::Entry::Vacant(entry) => {
5163                            entry.insert(None);
5164                        }
5165                        btree_map::Entry::Occupied(entry) => {
5166                            entry.remove();
5167                        }
5168                    }
5169                }
5170            }
5171            Subscription::ActionObservation { id, observations } => {
5172                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5173                    observations.lock().remove(id);
5174                }
5175            }
5176            Subscription::WindowActivationObservation {
5177                id,
5178                window_id,
5179                observations,
5180            } => {
5181                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5182                    match observations
5183                        .lock()
5184                        .entry(*window_id)
5185                        .or_default()
5186                        .entry(*id)
5187                    {
5188                        btree_map::Entry::Vacant(entry) => {
5189                            entry.insert(None);
5190                        }
5191                        btree_map::Entry::Occupied(entry) => {
5192                            entry.remove();
5193                        }
5194                    }
5195                }
5196            }
5197            Subscription::WindowFullscreenObservation {
5198                id,
5199                window_id,
5200                observations,
5201            } => {
5202                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5203                    match observations
5204                        .lock()
5205                        .entry(*window_id)
5206                        .or_default()
5207                        .entry(*id)
5208                    {
5209                        btree_map::Entry::Vacant(entry) => {
5210                            entry.insert(None);
5211                        }
5212                        btree_map::Entry::Occupied(entry) => {
5213                            entry.remove();
5214                        }
5215                    }
5216                }
5217            }
5218        }
5219    }
5220}
5221
5222lazy_static! {
5223    static ref LEAK_BACKTRACE: bool =
5224        std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty());
5225}
5226
5227#[cfg(any(test, feature = "test-support"))]
5228#[derive(Default)]
5229pub struct LeakDetector {
5230    next_handle_id: usize,
5231    #[allow(clippy::type_complexity)]
5232    handle_backtraces: HashMap<
5233        usize,
5234        (
5235            Option<&'static str>,
5236            HashMap<usize, Option<backtrace::Backtrace>>,
5237        ),
5238    >,
5239}
5240
5241#[cfg(any(test, feature = "test-support"))]
5242impl LeakDetector {
5243    fn handle_created(&mut self, type_name: Option<&'static str>, entity_id: usize) -> usize {
5244        let handle_id = post_inc(&mut self.next_handle_id);
5245        let entry = self.handle_backtraces.entry(entity_id).or_default();
5246        let backtrace = if *LEAK_BACKTRACE {
5247            Some(backtrace::Backtrace::new_unresolved())
5248        } else {
5249            None
5250        };
5251        if let Some(type_name) = type_name {
5252            entry.0.get_or_insert(type_name);
5253        }
5254        entry.1.insert(handle_id, backtrace);
5255        handle_id
5256    }
5257
5258    fn handle_dropped(&mut self, entity_id: usize, handle_id: usize) {
5259        if let Some((_, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
5260            assert!(backtraces.remove(&handle_id).is_some());
5261            if backtraces.is_empty() {
5262                self.handle_backtraces.remove(&entity_id);
5263            }
5264        }
5265    }
5266
5267    pub fn assert_dropped(&mut self, entity_id: usize) {
5268        if let Some((type_name, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
5269            for trace in backtraces.values_mut().flatten() {
5270                trace.resolve();
5271                eprintln!("{:?}", crate::util::CwdBacktrace(trace));
5272            }
5273
5274            let hint = if *LEAK_BACKTRACE {
5275                ""
5276            } else {
5277                " – set LEAK_BACKTRACE=1 for more information"
5278            };
5279
5280            panic!(
5281                "{} handles to {} {} still exist{}",
5282                backtraces.len(),
5283                type_name.unwrap_or("entity"),
5284                entity_id,
5285                hint
5286            );
5287        }
5288    }
5289
5290    pub fn detect(&mut self) {
5291        let mut found_leaks = false;
5292        for (id, (type_name, backtraces)) in self.handle_backtraces.iter_mut() {
5293            eprintln!(
5294                "leaked {} handles to {} {}",
5295                backtraces.len(),
5296                type_name.unwrap_or("entity"),
5297                id
5298            );
5299            for trace in backtraces.values_mut().flatten() {
5300                trace.resolve();
5301                eprintln!("{:?}", crate::util::CwdBacktrace(trace));
5302            }
5303            found_leaks = true;
5304        }
5305
5306        let hint = if *LEAK_BACKTRACE {
5307            ""
5308        } else {
5309            " – set LEAK_BACKTRACE=1 for more information"
5310        };
5311        assert!(!found_leaks, "detected leaked handles{}", hint);
5312    }
5313}
5314
5315#[derive(Default)]
5316struct RefCounts {
5317    entity_counts: HashMap<usize, usize>,
5318    element_state_counts: HashMap<ElementStateId, ElementStateRefCount>,
5319    dropped_models: HashSet<usize>,
5320    dropped_views: HashSet<(usize, usize)>,
5321    dropped_element_states: HashSet<ElementStateId>,
5322
5323    #[cfg(any(test, feature = "test-support"))]
5324    leak_detector: Arc<Mutex<LeakDetector>>,
5325}
5326
5327struct ElementStateRefCount {
5328    ref_count: usize,
5329    frame_id: usize,
5330}
5331
5332impl RefCounts {
5333    fn inc_model(&mut self, model_id: usize) {
5334        match self.entity_counts.entry(model_id) {
5335            Entry::Occupied(mut entry) => {
5336                *entry.get_mut() += 1;
5337            }
5338            Entry::Vacant(entry) => {
5339                entry.insert(1);
5340                self.dropped_models.remove(&model_id);
5341            }
5342        }
5343    }
5344
5345    fn inc_view(&mut self, window_id: usize, view_id: usize) {
5346        match self.entity_counts.entry(view_id) {
5347            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
5348            Entry::Vacant(entry) => {
5349                entry.insert(1);
5350                self.dropped_views.remove(&(window_id, view_id));
5351            }
5352        }
5353    }
5354
5355    fn inc_element_state(&mut self, id: ElementStateId, frame_id: usize) {
5356        match self.element_state_counts.entry(id) {
5357            Entry::Occupied(mut entry) => {
5358                let entry = entry.get_mut();
5359                if entry.frame_id == frame_id || entry.ref_count >= 2 {
5360                    panic!("used the same element state more than once in the same frame");
5361                }
5362                entry.ref_count += 1;
5363                entry.frame_id = frame_id;
5364            }
5365            Entry::Vacant(entry) => {
5366                entry.insert(ElementStateRefCount {
5367                    ref_count: 1,
5368                    frame_id,
5369                });
5370                self.dropped_element_states.remove(&id);
5371            }
5372        }
5373    }
5374
5375    fn dec_model(&mut self, model_id: usize) {
5376        let count = self.entity_counts.get_mut(&model_id).unwrap();
5377        *count -= 1;
5378        if *count == 0 {
5379            self.entity_counts.remove(&model_id);
5380            self.dropped_models.insert(model_id);
5381        }
5382    }
5383
5384    fn dec_view(&mut self, window_id: usize, view_id: usize) {
5385        let count = self.entity_counts.get_mut(&view_id).unwrap();
5386        *count -= 1;
5387        if *count == 0 {
5388            self.entity_counts.remove(&view_id);
5389            self.dropped_views.insert((window_id, view_id));
5390        }
5391    }
5392
5393    fn dec_element_state(&mut self, id: ElementStateId) {
5394        let entry = self.element_state_counts.get_mut(&id).unwrap();
5395        entry.ref_count -= 1;
5396        if entry.ref_count == 0 {
5397            self.element_state_counts.remove(&id);
5398            self.dropped_element_states.insert(id);
5399        }
5400    }
5401
5402    fn is_entity_alive(&self, entity_id: usize) -> bool {
5403        self.entity_counts.contains_key(&entity_id)
5404    }
5405
5406    fn take_dropped(
5407        &mut self,
5408    ) -> (
5409        HashSet<usize>,
5410        HashSet<(usize, usize)>,
5411        HashSet<ElementStateId>,
5412    ) {
5413        (
5414            std::mem::take(&mut self.dropped_models),
5415            std::mem::take(&mut self.dropped_views),
5416            std::mem::take(&mut self.dropped_element_states),
5417        )
5418    }
5419}
5420
5421#[cfg(test)]
5422mod tests {
5423    use super::*;
5424    use crate::{actions, elements::*, impl_actions, MouseButton, MouseButtonEvent};
5425    use serde::Deserialize;
5426    use smol::future::poll_once;
5427    use std::{
5428        cell::Cell,
5429        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
5430    };
5431
5432    #[crate::test(self)]
5433    fn test_model_handles(cx: &mut MutableAppContext) {
5434        struct Model {
5435            other: Option<ModelHandle<Model>>,
5436            events: Vec<String>,
5437        }
5438
5439        impl Entity for Model {
5440            type Event = usize;
5441        }
5442
5443        impl Model {
5444            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
5445                if let Some(other) = other.as_ref() {
5446                    cx.observe(other, |me, _, _| {
5447                        me.events.push("notified".into());
5448                    })
5449                    .detach();
5450                    cx.subscribe(other, |me, _, event, _| {
5451                        me.events.push(format!("observed event {}", event));
5452                    })
5453                    .detach();
5454                }
5455
5456                Self {
5457                    other,
5458                    events: Vec::new(),
5459                }
5460            }
5461        }
5462
5463        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
5464        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
5465        assert_eq!(cx.cx.models.len(), 2);
5466
5467        handle_1.update(cx, |model, cx| {
5468            model.events.push("updated".into());
5469            cx.emit(1);
5470            cx.notify();
5471            cx.emit(2);
5472        });
5473        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5474        assert_eq!(
5475            handle_2.read(cx).events,
5476            vec![
5477                "observed event 1".to_string(),
5478                "notified".to_string(),
5479                "observed event 2".to_string(),
5480            ]
5481        );
5482
5483        handle_2.update(cx, |model, _| {
5484            drop(handle_1);
5485            model.other.take();
5486        });
5487
5488        assert_eq!(cx.cx.models.len(), 1);
5489        assert!(cx.subscriptions.is_empty());
5490        assert!(cx.observations.is_empty());
5491    }
5492
5493    #[crate::test(self)]
5494    fn test_model_events(cx: &mut MutableAppContext) {
5495        #[derive(Default)]
5496        struct Model {
5497            events: Vec<usize>,
5498        }
5499
5500        impl Entity for Model {
5501            type Event = usize;
5502        }
5503
5504        let handle_1 = cx.add_model(|_| Model::default());
5505        let handle_2 = cx.add_model(|_| Model::default());
5506
5507        handle_1.update(cx, |_, cx| {
5508            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
5509                model.events.push(*event);
5510
5511                cx.subscribe(&emitter, |model, _, event, _| {
5512                    model.events.push(*event * 2);
5513                })
5514                .detach();
5515            })
5516            .detach();
5517        });
5518
5519        handle_2.update(cx, |_, c| c.emit(7));
5520        assert_eq!(handle_1.read(cx).events, vec![7]);
5521
5522        handle_2.update(cx, |_, c| c.emit(5));
5523        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
5524    }
5525
5526    #[crate::test(self)]
5527    fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
5528        #[derive(Default)]
5529        struct Model;
5530
5531        impl Entity for Model {
5532            type Event = ();
5533        }
5534
5535        let events = Rc::new(RefCell::new(Vec::new()));
5536        cx.add_model(|cx| {
5537            drop(cx.subscribe(&cx.handle(), {
5538                let events = events.clone();
5539                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
5540            }));
5541            cx.subscribe(&cx.handle(), {
5542                let events = events.clone();
5543                move |_, _, _, _| events.borrow_mut().push("before emit")
5544            })
5545            .detach();
5546            cx.emit(());
5547            cx.subscribe(&cx.handle(), {
5548                let events = events.clone();
5549                move |_, _, _, _| events.borrow_mut().push("after emit")
5550            })
5551            .detach();
5552            Model
5553        });
5554        assert_eq!(*events.borrow(), ["before emit"]);
5555    }
5556
5557    #[crate::test(self)]
5558    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
5559        #[derive(Default)]
5560        struct Model {
5561            count: usize,
5562            events: Vec<usize>,
5563        }
5564
5565        impl Entity for Model {
5566            type Event = ();
5567        }
5568
5569        let handle_1 = cx.add_model(|_| Model::default());
5570        let handle_2 = cx.add_model(|_| Model::default());
5571
5572        handle_1.update(cx, |_, c| {
5573            c.observe(&handle_2, move |model, observed, c| {
5574                model.events.push(observed.read(c).count);
5575                c.observe(&observed, |model, observed, c| {
5576                    model.events.push(observed.read(c).count * 2);
5577                })
5578                .detach();
5579            })
5580            .detach();
5581        });
5582
5583        handle_2.update(cx, |model, c| {
5584            model.count = 7;
5585            c.notify()
5586        });
5587        assert_eq!(handle_1.read(cx).events, vec![7]);
5588
5589        handle_2.update(cx, |model, c| {
5590            model.count = 5;
5591            c.notify()
5592        });
5593        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
5594    }
5595
5596    #[crate::test(self)]
5597    fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
5598        #[derive(Default)]
5599        struct Model;
5600
5601        impl Entity for Model {
5602            type Event = ();
5603        }
5604
5605        let events = Rc::new(RefCell::new(Vec::new()));
5606        cx.add_model(|cx| {
5607            drop(cx.observe(&cx.handle(), {
5608                let events = events.clone();
5609                move |_, _, _| events.borrow_mut().push("dropped before flush")
5610            }));
5611            cx.observe(&cx.handle(), {
5612                let events = events.clone();
5613                move |_, _, _| events.borrow_mut().push("before notify")
5614            })
5615            .detach();
5616            cx.notify();
5617            cx.observe(&cx.handle(), {
5618                let events = events.clone();
5619                move |_, _, _| events.borrow_mut().push("after notify")
5620            })
5621            .detach();
5622            Model
5623        });
5624        assert_eq!(*events.borrow(), ["before notify"]);
5625    }
5626
5627    #[crate::test(self)]
5628    fn test_defer_and_after_window_update(cx: &mut MutableAppContext) {
5629        struct View {
5630            render_count: usize,
5631        }
5632
5633        impl Entity for View {
5634            type Event = usize;
5635        }
5636
5637        impl super::View for View {
5638            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5639                post_inc(&mut self.render_count);
5640                Empty::new().boxed()
5641            }
5642
5643            fn ui_name() -> &'static str {
5644                "View"
5645            }
5646        }
5647
5648        let (_, view) = cx.add_window(Default::default(), |_| View { render_count: 0 });
5649        let called_defer = Rc::new(AtomicBool::new(false));
5650        let called_after_window_update = Rc::new(AtomicBool::new(false));
5651
5652        view.update(cx, |this, cx| {
5653            assert_eq!(this.render_count, 1);
5654            cx.defer({
5655                let called_defer = called_defer.clone();
5656                move |this, _| {
5657                    assert_eq!(this.render_count, 1);
5658                    called_defer.store(true, SeqCst);
5659                }
5660            });
5661            cx.after_window_update({
5662                let called_after_window_update = called_after_window_update.clone();
5663                move |this, cx| {
5664                    assert_eq!(this.render_count, 2);
5665                    called_after_window_update.store(true, SeqCst);
5666                    cx.notify();
5667                }
5668            });
5669            assert!(!called_defer.load(SeqCst));
5670            assert!(!called_after_window_update.load(SeqCst));
5671            cx.notify();
5672        });
5673
5674        assert!(called_defer.load(SeqCst));
5675        assert!(called_after_window_update.load(SeqCst));
5676        assert_eq!(view.read(cx).render_count, 3);
5677    }
5678
5679    #[crate::test(self)]
5680    fn test_view_handles(cx: &mut MutableAppContext) {
5681        struct View {
5682            other: Option<ViewHandle<View>>,
5683            events: Vec<String>,
5684        }
5685
5686        impl Entity for View {
5687            type Event = usize;
5688        }
5689
5690        impl super::View for View {
5691            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5692                Empty::new().boxed()
5693            }
5694
5695            fn ui_name() -> &'static str {
5696                "View"
5697            }
5698        }
5699
5700        impl View {
5701            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
5702                if let Some(other) = other.as_ref() {
5703                    cx.subscribe(other, |me, _, event, _| {
5704                        me.events.push(format!("observed event {}", event));
5705                    })
5706                    .detach();
5707                }
5708                Self {
5709                    other,
5710                    events: Vec::new(),
5711                }
5712            }
5713        }
5714
5715        let (_, root_view) = cx.add_window(Default::default(), |cx| View::new(None, cx));
5716        let handle_1 = cx.add_view(&root_view, |cx| View::new(None, cx));
5717        let handle_2 = cx.add_view(&root_view, |cx| View::new(Some(handle_1.clone()), cx));
5718        assert_eq!(cx.cx.views.len(), 3);
5719
5720        handle_1.update(cx, |view, cx| {
5721            view.events.push("updated".into());
5722            cx.emit(1);
5723            cx.emit(2);
5724        });
5725        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5726        assert_eq!(
5727            handle_2.read(cx).events,
5728            vec![
5729                "observed event 1".to_string(),
5730                "observed event 2".to_string(),
5731            ]
5732        );
5733
5734        handle_2.update(cx, |view, _| {
5735            drop(handle_1);
5736            view.other.take();
5737        });
5738
5739        assert_eq!(cx.cx.views.len(), 2);
5740        assert!(cx.subscriptions.is_empty());
5741        assert!(cx.observations.is_empty());
5742    }
5743
5744    #[crate::test(self)]
5745    fn test_add_window(cx: &mut MutableAppContext) {
5746        struct View {
5747            mouse_down_count: Arc<AtomicUsize>,
5748        }
5749
5750        impl Entity for View {
5751            type Event = ();
5752        }
5753
5754        impl super::View for View {
5755            fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
5756                enum Handler {}
5757                let mouse_down_count = self.mouse_down_count.clone();
5758                MouseEventHandler::<Handler>::new(0, cx, |_, _| Empty::new().boxed())
5759                    .on_down(MouseButton::Left, move |_, _| {
5760                        mouse_down_count.fetch_add(1, SeqCst);
5761                    })
5762                    .boxed()
5763            }
5764
5765            fn ui_name() -> &'static str {
5766                "View"
5767            }
5768        }
5769
5770        let mouse_down_count = Arc::new(AtomicUsize::new(0));
5771        let (window_id, _) = cx.add_window(Default::default(), |_| View {
5772            mouse_down_count: mouse_down_count.clone(),
5773        });
5774        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
5775        // Ensure window's root element is in a valid lifecycle state.
5776        presenter.borrow_mut().dispatch_event(
5777            Event::MouseDown(MouseButtonEvent {
5778                position: Default::default(),
5779                button: MouseButton::Left,
5780                modifiers: Default::default(),
5781                click_count: 1,
5782            }),
5783            false,
5784            cx,
5785        );
5786        assert_eq!(mouse_down_count.load(SeqCst), 1);
5787    }
5788
5789    #[crate::test(self)]
5790    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
5791        struct Model {
5792            released: Rc<Cell<bool>>,
5793        }
5794
5795        struct View {
5796            released: Rc<Cell<bool>>,
5797        }
5798
5799        impl Entity for Model {
5800            type Event = ();
5801
5802            fn release(&mut self, _: &mut MutableAppContext) {
5803                self.released.set(true);
5804            }
5805        }
5806
5807        impl Entity for View {
5808            type Event = ();
5809
5810            fn release(&mut self, _: &mut MutableAppContext) {
5811                self.released.set(true);
5812            }
5813        }
5814
5815        impl super::View for View {
5816            fn ui_name() -> &'static str {
5817                "View"
5818            }
5819
5820            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5821                Empty::new().boxed()
5822            }
5823        }
5824
5825        let model_released = Rc::new(Cell::new(false));
5826        let model_release_observed = Rc::new(Cell::new(false));
5827        let view_released = Rc::new(Cell::new(false));
5828        let view_release_observed = Rc::new(Cell::new(false));
5829
5830        let model = cx.add_model(|_| Model {
5831            released: model_released.clone(),
5832        });
5833        let (window_id, view) = cx.add_window(Default::default(), |_| View {
5834            released: view_released.clone(),
5835        });
5836        assert!(!model_released.get());
5837        assert!(!view_released.get());
5838
5839        cx.observe_release(&model, {
5840            let model_release_observed = model_release_observed.clone();
5841            move |_, _| model_release_observed.set(true)
5842        })
5843        .detach();
5844        cx.observe_release(&view, {
5845            let view_release_observed = view_release_observed.clone();
5846            move |_, _| view_release_observed.set(true)
5847        })
5848        .detach();
5849
5850        cx.update(move |_| {
5851            drop(model);
5852        });
5853        assert!(model_released.get());
5854        assert!(model_release_observed.get());
5855
5856        drop(view);
5857        cx.remove_window(window_id);
5858        assert!(view_released.get());
5859        assert!(view_release_observed.get());
5860    }
5861
5862    #[crate::test(self)]
5863    fn test_view_events(cx: &mut MutableAppContext) {
5864        #[derive(Default)]
5865        struct View {
5866            events: Vec<usize>,
5867        }
5868
5869        impl Entity for View {
5870            type Event = usize;
5871        }
5872
5873        impl super::View for View {
5874            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5875                Empty::new().boxed()
5876            }
5877
5878            fn ui_name() -> &'static str {
5879                "View"
5880            }
5881        }
5882
5883        struct Model;
5884
5885        impl Entity for Model {
5886            type Event = usize;
5887        }
5888
5889        let (_, handle_1) = cx.add_window(Default::default(), |_| View::default());
5890        let handle_2 = cx.add_view(&handle_1, |_| View::default());
5891        let handle_3 = cx.add_model(|_| Model);
5892
5893        handle_1.update(cx, |_, cx| {
5894            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
5895                me.events.push(*event);
5896
5897                cx.subscribe(&emitter, |me, _, event, _| {
5898                    me.events.push(*event * 2);
5899                })
5900                .detach();
5901            })
5902            .detach();
5903
5904            cx.subscribe(&handle_3, |me, _, event, _| {
5905                me.events.push(*event);
5906            })
5907            .detach();
5908        });
5909
5910        handle_2.update(cx, |_, c| c.emit(7));
5911        assert_eq!(handle_1.read(cx).events, vec![7]);
5912
5913        handle_2.update(cx, |_, c| c.emit(5));
5914        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
5915
5916        handle_3.update(cx, |_, c| c.emit(9));
5917        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
5918    }
5919
5920    #[crate::test(self)]
5921    fn test_global_events(cx: &mut MutableAppContext) {
5922        #[derive(Clone, Debug, Eq, PartialEq)]
5923        struct GlobalEvent(u64);
5924
5925        let events = Rc::new(RefCell::new(Vec::new()));
5926        let first_subscription;
5927        let second_subscription;
5928
5929        {
5930            let events = events.clone();
5931            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5932                events.borrow_mut().push(("First", e.clone()));
5933            });
5934        }
5935
5936        {
5937            let events = events.clone();
5938            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
5939                events.borrow_mut().push(("Second", e.clone()));
5940            });
5941        }
5942
5943        cx.update(|cx| {
5944            cx.emit_global(GlobalEvent(1));
5945            cx.emit_global(GlobalEvent(2));
5946        });
5947
5948        drop(first_subscription);
5949
5950        cx.update(|cx| {
5951            cx.emit_global(GlobalEvent(3));
5952        });
5953
5954        drop(second_subscription);
5955
5956        cx.update(|cx| {
5957            cx.emit_global(GlobalEvent(4));
5958        });
5959
5960        assert_eq!(
5961            &*events.borrow(),
5962            &[
5963                ("First", GlobalEvent(1)),
5964                ("Second", GlobalEvent(1)),
5965                ("First", GlobalEvent(2)),
5966                ("Second", GlobalEvent(2)),
5967                ("Second", GlobalEvent(3)),
5968            ]
5969        );
5970    }
5971
5972    #[crate::test(self)]
5973    fn test_global_events_emitted_before_subscription_in_same_update_cycle(
5974        cx: &mut MutableAppContext,
5975    ) {
5976        let events = Rc::new(RefCell::new(Vec::new()));
5977        cx.update(|cx| {
5978            {
5979                let events = events.clone();
5980                drop(cx.subscribe_global(move |_: &(), _| {
5981                    events.borrow_mut().push("dropped before emit");
5982                }));
5983            }
5984
5985            {
5986                let events = events.clone();
5987                cx.subscribe_global(move |_: &(), _| {
5988                    events.borrow_mut().push("before emit");
5989                })
5990                .detach();
5991            }
5992
5993            cx.emit_global(());
5994
5995            {
5996                let events = events.clone();
5997                cx.subscribe_global(move |_: &(), _| {
5998                    events.borrow_mut().push("after emit");
5999                })
6000                .detach();
6001            }
6002        });
6003
6004        assert_eq!(*events.borrow(), ["before emit"]);
6005    }
6006
6007    #[crate::test(self)]
6008    fn test_global_nested_events(cx: &mut MutableAppContext) {
6009        #[derive(Clone, Debug, Eq, PartialEq)]
6010        struct GlobalEvent(u64);
6011
6012        let events = Rc::new(RefCell::new(Vec::new()));
6013
6014        {
6015            let events = events.clone();
6016            cx.subscribe_global(move |e: &GlobalEvent, cx| {
6017                events.borrow_mut().push(("Outer", e.clone()));
6018
6019                if e.0 == 1 {
6020                    let events = events.clone();
6021                    cx.subscribe_global(move |e: &GlobalEvent, _| {
6022                        events.borrow_mut().push(("Inner", e.clone()));
6023                    })
6024                    .detach();
6025                }
6026            })
6027            .detach();
6028        }
6029
6030        cx.update(|cx| {
6031            cx.emit_global(GlobalEvent(1));
6032            cx.emit_global(GlobalEvent(2));
6033            cx.emit_global(GlobalEvent(3));
6034        });
6035        cx.update(|cx| {
6036            cx.emit_global(GlobalEvent(4));
6037        });
6038
6039        assert_eq!(
6040            &*events.borrow(),
6041            &[
6042                ("Outer", GlobalEvent(1)),
6043                ("Outer", GlobalEvent(2)),
6044                ("Outer", GlobalEvent(3)),
6045                ("Outer", GlobalEvent(4)),
6046                ("Inner", GlobalEvent(4)),
6047            ]
6048        );
6049    }
6050
6051    #[crate::test(self)]
6052    fn test_global(cx: &mut MutableAppContext) {
6053        type Global = usize;
6054
6055        let observation_count = Rc::new(RefCell::new(0));
6056        let subscription = cx.observe_global::<Global, _>({
6057            let observation_count = observation_count.clone();
6058            move |_| {
6059                *observation_count.borrow_mut() += 1;
6060            }
6061        });
6062
6063        assert!(!cx.has_global::<Global>());
6064        assert_eq!(cx.default_global::<Global>(), &0);
6065        assert_eq!(*observation_count.borrow(), 1);
6066        assert!(cx.has_global::<Global>());
6067        assert_eq!(
6068            cx.update_global::<Global, _, _>(|global, _| {
6069                *global = 1;
6070                "Update Result"
6071            }),
6072            "Update Result"
6073        );
6074        assert_eq!(*observation_count.borrow(), 2);
6075        assert_eq!(cx.global::<Global>(), &1);
6076
6077        drop(subscription);
6078        cx.update_global::<Global, _, _>(|global, _| {
6079            *global = 2;
6080        });
6081        assert_eq!(*observation_count.borrow(), 2);
6082
6083        type OtherGlobal = f32;
6084
6085        let observation_count = Rc::new(RefCell::new(0));
6086        cx.observe_global::<OtherGlobal, _>({
6087            let observation_count = observation_count.clone();
6088            move |_| {
6089                *observation_count.borrow_mut() += 1;
6090            }
6091        })
6092        .detach();
6093
6094        assert_eq!(
6095            cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
6096                assert_eq!(global, &0.0);
6097                *global = 2.0;
6098                "Default update result"
6099            }),
6100            "Default update result"
6101        );
6102        assert_eq!(cx.global::<OtherGlobal>(), &2.0);
6103        assert_eq!(*observation_count.borrow(), 1);
6104    }
6105
6106    #[crate::test(self)]
6107    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
6108        struct View;
6109
6110        impl Entity for View {
6111            type Event = ();
6112        }
6113
6114        impl super::View for View {
6115            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6116                Empty::new().boxed()
6117            }
6118
6119            fn ui_name() -> &'static str {
6120                "View"
6121            }
6122        }
6123
6124        struct Model;
6125
6126        impl Entity for Model {
6127            type Event = ();
6128        }
6129
6130        let (_, root_view) = cx.add_window(Default::default(), |_| View);
6131        let observing_view = cx.add_view(&root_view, |_| View);
6132        let emitting_view = cx.add_view(&root_view, |_| View);
6133        let observing_model = cx.add_model(|_| Model);
6134        let observed_model = cx.add_model(|_| Model);
6135
6136        observing_view.update(cx, |_, cx| {
6137            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
6138            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
6139        });
6140        observing_model.update(cx, |_, cx| {
6141            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
6142        });
6143
6144        cx.update(|_| {
6145            drop(observing_view);
6146            drop(observing_model);
6147        });
6148
6149        emitting_view.update(cx, |_, cx| cx.emit(()));
6150        observed_model.update(cx, |_, cx| cx.emit(()));
6151    }
6152
6153    #[crate::test(self)]
6154    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
6155        #[derive(Default)]
6156        struct TestView;
6157
6158        impl Entity for TestView {
6159            type Event = ();
6160        }
6161
6162        impl View for TestView {
6163            fn ui_name() -> &'static str {
6164                "TestView"
6165            }
6166
6167            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6168                Empty::new().boxed()
6169            }
6170        }
6171
6172        let events = Rc::new(RefCell::new(Vec::new()));
6173        cx.add_window(Default::default(), |cx| {
6174            drop(cx.subscribe(&cx.handle(), {
6175                let events = events.clone();
6176                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
6177            }));
6178            cx.subscribe(&cx.handle(), {
6179                let events = events.clone();
6180                move |_, _, _, _| events.borrow_mut().push("before emit")
6181            })
6182            .detach();
6183            cx.emit(());
6184            cx.subscribe(&cx.handle(), {
6185                let events = events.clone();
6186                move |_, _, _, _| events.borrow_mut().push("after emit")
6187            })
6188            .detach();
6189            TestView
6190        });
6191        assert_eq!(*events.borrow(), ["before emit"]);
6192    }
6193
6194    #[crate::test(self)]
6195    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
6196        #[derive(Default)]
6197        struct View {
6198            events: Vec<usize>,
6199        }
6200
6201        impl Entity for View {
6202            type Event = usize;
6203        }
6204
6205        impl super::View for View {
6206            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6207                Empty::new().boxed()
6208            }
6209
6210            fn ui_name() -> &'static str {
6211                "View"
6212            }
6213        }
6214
6215        #[derive(Default)]
6216        struct Model {
6217            count: usize,
6218        }
6219
6220        impl Entity for Model {
6221            type Event = ();
6222        }
6223
6224        let (_, view) = cx.add_window(Default::default(), |_| View::default());
6225        let model = cx.add_model(|_| Model::default());
6226
6227        view.update(cx, |_, c| {
6228            c.observe(&model, |me, observed, c| {
6229                me.events.push(observed.read(c).count)
6230            })
6231            .detach();
6232        });
6233
6234        model.update(cx, |model, c| {
6235            model.count = 11;
6236            c.notify();
6237        });
6238        assert_eq!(view.read(cx).events, vec![11]);
6239    }
6240
6241    #[crate::test(self)]
6242    fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
6243        #[derive(Default)]
6244        struct TestView;
6245
6246        impl Entity for TestView {
6247            type Event = ();
6248        }
6249
6250        impl View for TestView {
6251            fn ui_name() -> &'static str {
6252                "TestView"
6253            }
6254
6255            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6256                Empty::new().boxed()
6257            }
6258        }
6259
6260        let events = Rc::new(RefCell::new(Vec::new()));
6261        cx.add_window(Default::default(), |cx| {
6262            drop(cx.observe(&cx.handle(), {
6263                let events = events.clone();
6264                move |_, _, _| events.borrow_mut().push("dropped before flush")
6265            }));
6266            cx.observe(&cx.handle(), {
6267                let events = events.clone();
6268                move |_, _, _| events.borrow_mut().push("before notify")
6269            })
6270            .detach();
6271            cx.notify();
6272            cx.observe(&cx.handle(), {
6273                let events = events.clone();
6274                move |_, _, _| events.borrow_mut().push("after notify")
6275            })
6276            .detach();
6277            TestView
6278        });
6279        assert_eq!(*events.borrow(), ["before notify"]);
6280    }
6281
6282    #[crate::test(self)]
6283    fn test_dropping_observers(cx: &mut MutableAppContext) {
6284        struct View;
6285
6286        impl Entity for View {
6287            type Event = ();
6288        }
6289
6290        impl super::View for View {
6291            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6292                Empty::new().boxed()
6293            }
6294
6295            fn ui_name() -> &'static str {
6296                "View"
6297            }
6298        }
6299
6300        struct Model;
6301
6302        impl Entity for Model {
6303            type Event = ();
6304        }
6305
6306        let (_, root_view) = cx.add_window(Default::default(), |_| View);
6307        let observing_view = cx.add_view(root_view, |_| View);
6308        let observing_model = cx.add_model(|_| Model);
6309        let observed_model = cx.add_model(|_| Model);
6310
6311        observing_view.update(cx, |_, cx| {
6312            cx.observe(&observed_model, |_, _, _| {}).detach();
6313        });
6314        observing_model.update(cx, |_, cx| {
6315            cx.observe(&observed_model, |_, _, _| {}).detach();
6316        });
6317
6318        cx.update(|_| {
6319            drop(observing_view);
6320            drop(observing_model);
6321        });
6322
6323        observed_model.update(cx, |_, cx| cx.notify());
6324    }
6325
6326    #[crate::test(self)]
6327    fn test_dropping_subscriptions_during_callback(cx: &mut MutableAppContext) {
6328        struct Model;
6329
6330        impl Entity for Model {
6331            type Event = u64;
6332        }
6333
6334        // Events
6335        let observing_model = cx.add_model(|_| Model);
6336        let observed_model = cx.add_model(|_| Model);
6337
6338        let events = Rc::new(RefCell::new(Vec::new()));
6339
6340        observing_model.update(cx, |_, cx| {
6341            let events = events.clone();
6342            let subscription = Rc::new(RefCell::new(None));
6343            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
6344                let subscription = subscription.clone();
6345                move |_, _, e, _| {
6346                    subscription.borrow_mut().take();
6347                    events.borrow_mut().push(*e);
6348                }
6349            }));
6350        });
6351
6352        observed_model.update(cx, |_, cx| {
6353            cx.emit(1);
6354            cx.emit(2);
6355        });
6356
6357        assert_eq!(*events.borrow(), [1]);
6358
6359        // Global Events
6360        #[derive(Clone, Debug, Eq, PartialEq)]
6361        struct GlobalEvent(u64);
6362
6363        let events = Rc::new(RefCell::new(Vec::new()));
6364
6365        {
6366            let events = events.clone();
6367            let subscription = Rc::new(RefCell::new(None));
6368            *subscription.borrow_mut() = Some(cx.subscribe_global({
6369                let subscription = subscription.clone();
6370                move |e: &GlobalEvent, _| {
6371                    subscription.borrow_mut().take();
6372                    events.borrow_mut().push(e.clone());
6373                }
6374            }));
6375        }
6376
6377        cx.update(|cx| {
6378            cx.emit_global(GlobalEvent(1));
6379            cx.emit_global(GlobalEvent(2));
6380        });
6381
6382        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
6383
6384        // Model Observation
6385        let observing_model = cx.add_model(|_| Model);
6386        let observed_model = cx.add_model(|_| Model);
6387
6388        let observation_count = Rc::new(RefCell::new(0));
6389
6390        observing_model.update(cx, |_, cx| {
6391            let observation_count = observation_count.clone();
6392            let subscription = Rc::new(RefCell::new(None));
6393            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
6394                let subscription = subscription.clone();
6395                move |_, _, _| {
6396                    subscription.borrow_mut().take();
6397                    *observation_count.borrow_mut() += 1;
6398                }
6399            }));
6400        });
6401
6402        observed_model.update(cx, |_, cx| {
6403            cx.notify();
6404        });
6405
6406        observed_model.update(cx, |_, cx| {
6407            cx.notify();
6408        });
6409
6410        assert_eq!(*observation_count.borrow(), 1);
6411
6412        // View Observation
6413        struct View;
6414
6415        impl Entity for View {
6416            type Event = ();
6417        }
6418
6419        impl super::View for View {
6420            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6421                Empty::new().boxed()
6422            }
6423
6424            fn ui_name() -> &'static str {
6425                "View"
6426            }
6427        }
6428
6429        let (_, root_view) = cx.add_window(Default::default(), |_| View);
6430        let observing_view = cx.add_view(&root_view, |_| View);
6431        let observed_view = cx.add_view(&root_view, |_| View);
6432
6433        let observation_count = Rc::new(RefCell::new(0));
6434        observing_view.update(cx, |_, cx| {
6435            let observation_count = observation_count.clone();
6436            let subscription = Rc::new(RefCell::new(None));
6437            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
6438                let subscription = subscription.clone();
6439                move |_, _, _| {
6440                    subscription.borrow_mut().take();
6441                    *observation_count.borrow_mut() += 1;
6442                }
6443            }));
6444        });
6445
6446        observed_view.update(cx, |_, cx| {
6447            cx.notify();
6448        });
6449
6450        observed_view.update(cx, |_, cx| {
6451            cx.notify();
6452        });
6453
6454        assert_eq!(*observation_count.borrow(), 1);
6455
6456        // Global Observation
6457        let observation_count = Rc::new(RefCell::new(0));
6458        let subscription = Rc::new(RefCell::new(None));
6459        *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
6460            let observation_count = observation_count.clone();
6461            let subscription = subscription.clone();
6462            move |_| {
6463                subscription.borrow_mut().take();
6464                *observation_count.borrow_mut() += 1;
6465            }
6466        }));
6467
6468        cx.default_global::<()>();
6469        cx.set_global(());
6470        assert_eq!(*observation_count.borrow(), 1);
6471    }
6472
6473    #[crate::test(self)]
6474    fn test_focus(cx: &mut MutableAppContext) {
6475        struct View {
6476            name: String,
6477            events: Arc<Mutex<Vec<String>>>,
6478        }
6479
6480        impl Entity for View {
6481            type Event = ();
6482        }
6483
6484        impl super::View for View {
6485            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6486                Empty::new().boxed()
6487            }
6488
6489            fn ui_name() -> &'static str {
6490                "View"
6491            }
6492
6493            fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
6494                if cx.handle().id() == focused.id() {
6495                    self.events.lock().push(format!("{} focused", &self.name));
6496                }
6497            }
6498
6499            fn focus_out(&mut self, blurred: AnyViewHandle, cx: &mut ViewContext<Self>) {
6500                if cx.handle().id() == blurred.id() {
6501                    self.events.lock().push(format!("{} blurred", &self.name));
6502                }
6503            }
6504        }
6505
6506        let view_events: Arc<Mutex<Vec<String>>> = Default::default();
6507        let (_, view_1) = cx.add_window(Default::default(), |_| View {
6508            events: view_events.clone(),
6509            name: "view 1".to_string(),
6510        });
6511        let view_2 = cx.add_view(&view_1, |_| View {
6512            events: view_events.clone(),
6513            name: "view 2".to_string(),
6514        });
6515
6516        let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
6517        view_1.update(cx, |_, cx| {
6518            cx.observe_focus(&view_2, {
6519                let observed_events = observed_events.clone();
6520                move |this, view, focused, cx| {
6521                    let label = if focused { "focus" } else { "blur" };
6522                    observed_events.lock().push(format!(
6523                        "{} observed {}'s {}",
6524                        this.name,
6525                        view.read(cx).name,
6526                        label
6527                    ))
6528                }
6529            })
6530            .detach();
6531        });
6532        view_2.update(cx, |_, cx| {
6533            cx.observe_focus(&view_1, {
6534                let observed_events = observed_events.clone();
6535                move |this, view, focused, cx| {
6536                    let label = if focused { "focus" } else { "blur" };
6537                    observed_events.lock().push(format!(
6538                        "{} observed {}'s {}",
6539                        this.name,
6540                        view.read(cx).name,
6541                        label
6542                    ))
6543                }
6544            })
6545            .detach();
6546        });
6547        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6548        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6549
6550        view_1.update(cx, |_, cx| {
6551            // Ensure focus events are sent for all intermediate focuses
6552            cx.focus(&view_2);
6553            cx.focus(&view_1);
6554            cx.focus(&view_2);
6555        });
6556        assert_eq!(
6557            mem::take(&mut *view_events.lock()),
6558            [
6559                "view 1 blurred",
6560                "view 2 focused",
6561                "view 2 blurred",
6562                "view 1 focused",
6563                "view 1 blurred",
6564                "view 2 focused"
6565            ],
6566        );
6567        assert_eq!(
6568            mem::take(&mut *observed_events.lock()),
6569            [
6570                "view 2 observed view 1's blur",
6571                "view 1 observed view 2's focus",
6572                "view 1 observed view 2's blur",
6573                "view 2 observed view 1's focus",
6574                "view 2 observed view 1's blur",
6575                "view 1 observed view 2's focus"
6576            ]
6577        );
6578
6579        view_1.update(cx, |_, cx| cx.focus(&view_1));
6580        assert_eq!(
6581            mem::take(&mut *view_events.lock()),
6582            ["view 2 blurred", "view 1 focused"],
6583        );
6584        assert_eq!(
6585            mem::take(&mut *observed_events.lock()),
6586            [
6587                "view 1 observed view 2's blur",
6588                "view 2 observed view 1's focus"
6589            ]
6590        );
6591
6592        view_1.update(cx, |_, cx| cx.focus(&view_2));
6593        assert_eq!(
6594            mem::take(&mut *view_events.lock()),
6595            ["view 1 blurred", "view 2 focused"],
6596        );
6597        assert_eq!(
6598            mem::take(&mut *observed_events.lock()),
6599            [
6600                "view 2 observed view 1's blur",
6601                "view 1 observed view 2's focus"
6602            ]
6603        );
6604
6605        view_1.update(cx, |_, _| drop(view_2));
6606        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6607        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6608    }
6609
6610    #[crate::test(self)]
6611    fn test_deserialize_actions(cx: &mut MutableAppContext) {
6612        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6613        pub struct ComplexAction {
6614            arg: String,
6615            count: usize,
6616        }
6617
6618        actions!(test::something, [SimpleAction]);
6619        impl_actions!(test::something, [ComplexAction]);
6620
6621        cx.add_global_action(move |_: &SimpleAction, _: &mut MutableAppContext| {});
6622        cx.add_global_action(move |_: &ComplexAction, _: &mut MutableAppContext| {});
6623
6624        let action1 = cx
6625            .deserialize_action(
6626                "test::something::ComplexAction",
6627                Some(r#"{"arg": "a", "count": 5}"#),
6628            )
6629            .unwrap();
6630        let action2 = cx
6631            .deserialize_action("test::something::SimpleAction", None)
6632            .unwrap();
6633        assert_eq!(
6634            action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
6635            &ComplexAction {
6636                arg: "a".to_string(),
6637                count: 5,
6638            }
6639        );
6640        assert_eq!(
6641            action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
6642            &SimpleAction
6643        );
6644    }
6645
6646    #[crate::test(self)]
6647    fn test_dispatch_action(cx: &mut MutableAppContext) {
6648        struct ViewA {
6649            id: usize,
6650        }
6651
6652        impl Entity for ViewA {
6653            type Event = ();
6654        }
6655
6656        impl View for ViewA {
6657            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6658                Empty::new().boxed()
6659            }
6660
6661            fn ui_name() -> &'static str {
6662                "View"
6663            }
6664        }
6665
6666        struct ViewB {
6667            id: usize,
6668        }
6669
6670        impl Entity for ViewB {
6671            type Event = ();
6672        }
6673
6674        impl View for ViewB {
6675            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6676                Empty::new().boxed()
6677            }
6678
6679            fn ui_name() -> &'static str {
6680                "View"
6681            }
6682        }
6683
6684        #[derive(Clone, Default, Deserialize, PartialEq)]
6685        pub struct Action(pub String);
6686
6687        impl_actions!(test, [Action]);
6688
6689        let actions = Rc::new(RefCell::new(Vec::new()));
6690
6691        cx.add_global_action({
6692            let actions = actions.clone();
6693            move |_: &Action, _: &mut MutableAppContext| {
6694                actions.borrow_mut().push("global".to_string());
6695            }
6696        });
6697
6698        cx.add_action({
6699            let actions = actions.clone();
6700            move |view: &mut ViewA, action: &Action, cx| {
6701                assert_eq!(action.0, "bar");
6702                cx.propagate_action();
6703                actions.borrow_mut().push(format!("{} a", view.id));
6704            }
6705        });
6706
6707        cx.add_action({
6708            let actions = actions.clone();
6709            move |view: &mut ViewA, _: &Action, cx| {
6710                if view.id != 1 {
6711                    cx.add_view(|cx| {
6712                        cx.propagate_action(); // Still works on a nested ViewContext
6713                        ViewB { id: 5 }
6714                    });
6715                }
6716                actions.borrow_mut().push(format!("{} b", view.id));
6717            }
6718        });
6719
6720        cx.add_action({
6721            let actions = actions.clone();
6722            move |view: &mut ViewB, _: &Action, cx| {
6723                cx.propagate_action();
6724                actions.borrow_mut().push(format!("{} c", view.id));
6725            }
6726        });
6727
6728        cx.add_action({
6729            let actions = actions.clone();
6730            move |view: &mut ViewB, _: &Action, cx| {
6731                cx.propagate_action();
6732                actions.borrow_mut().push(format!("{} d", view.id));
6733            }
6734        });
6735
6736        cx.capture_action({
6737            let actions = actions.clone();
6738            move |view: &mut ViewA, _: &Action, cx| {
6739                cx.propagate_action();
6740                actions.borrow_mut().push(format!("{} capture", view.id));
6741            }
6742        });
6743
6744        let observed_actions = Rc::new(RefCell::new(Vec::new()));
6745        cx.observe_actions({
6746            let observed_actions = observed_actions.clone();
6747            move |action_id, _| observed_actions.borrow_mut().push(action_id)
6748        })
6749        .detach();
6750
6751        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
6752        let view_2 = cx.add_view(&view_1, |_| ViewB { id: 2 });
6753        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
6754        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
6755
6756        cx.handle_dispatch_action_from_effect(
6757            window_id,
6758            Some(view_4.id()),
6759            &Action("bar".to_string()),
6760        );
6761
6762        assert_eq!(
6763            *actions.borrow(),
6764            vec![
6765                "1 capture",
6766                "3 capture",
6767                "4 d",
6768                "4 c",
6769                "3 b",
6770                "3 a",
6771                "2 d",
6772                "2 c",
6773                "1 b"
6774            ]
6775        );
6776        assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
6777
6778        // Remove view_1, which doesn't propagate the action
6779
6780        let (window_id, view_2) = cx.add_window(Default::default(), |_| ViewB { id: 2 });
6781        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
6782        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
6783
6784        actions.borrow_mut().clear();
6785        cx.handle_dispatch_action_from_effect(
6786            window_id,
6787            Some(view_4.id()),
6788            &Action("bar".to_string()),
6789        );
6790
6791        assert_eq!(
6792            *actions.borrow(),
6793            vec![
6794                "3 capture",
6795                "4 d",
6796                "4 c",
6797                "3 b",
6798                "3 a",
6799                "2 d",
6800                "2 c",
6801                "global"
6802            ]
6803        );
6804        assert_eq!(
6805            *observed_actions.borrow(),
6806            [Action::default().id(), Action::default().id()]
6807        );
6808    }
6809
6810    #[crate::test(self)]
6811    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
6812        #[derive(Clone, Deserialize, PartialEq)]
6813        pub struct Action(String);
6814
6815        impl_actions!(test, [Action]);
6816
6817        struct View {
6818            id: usize,
6819            keymap_context: keymap::Context,
6820        }
6821
6822        impl Entity for View {
6823            type Event = ();
6824        }
6825
6826        impl super::View for View {
6827            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6828                Empty::new().boxed()
6829            }
6830
6831            fn ui_name() -> &'static str {
6832                "View"
6833            }
6834
6835            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
6836                self.keymap_context.clone()
6837            }
6838        }
6839
6840        impl View {
6841            fn new(id: usize) -> Self {
6842                View {
6843                    id,
6844                    keymap_context: keymap::Context::default(),
6845                }
6846            }
6847        }
6848
6849        let mut view_1 = View::new(1);
6850        let mut view_2 = View::new(2);
6851        let mut view_3 = View::new(3);
6852        view_1.keymap_context.set.insert("a".into());
6853        view_2.keymap_context.set.insert("a".into());
6854        view_2.keymap_context.set.insert("b".into());
6855        view_3.keymap_context.set.insert("a".into());
6856        view_3.keymap_context.set.insert("b".into());
6857        view_3.keymap_context.set.insert("c".into());
6858
6859        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
6860        let view_2 = cx.add_view(&view_1, |_| view_2);
6861        let _view_3 = cx.add_view(&view_2, |cx| {
6862            cx.focus_self();
6863            view_3
6864        });
6865
6866        // This keymap's only binding dispatches an action on view 2 because that view will have
6867        // "a" and "b" in its context, but not "c".
6868        cx.add_bindings(vec![keymap::Binding::new(
6869            "a",
6870            Action("a".to_string()),
6871            Some("a && b && !c"),
6872        )]);
6873
6874        cx.add_bindings(vec![keymap::Binding::new(
6875            "b",
6876            Action("b".to_string()),
6877            None,
6878        )]);
6879
6880        let actions = Rc::new(RefCell::new(Vec::new()));
6881        cx.add_action({
6882            let actions = actions.clone();
6883            move |view: &mut View, action: &Action, cx| {
6884                if action.0 == "a" {
6885                    actions.borrow_mut().push(format!("{} a", view.id));
6886                } else {
6887                    actions
6888                        .borrow_mut()
6889                        .push(format!("{} {}", view.id, action.0));
6890                    cx.propagate_action();
6891                }
6892            }
6893        });
6894
6895        cx.add_global_action({
6896            let actions = actions.clone();
6897            move |action: &Action, _| {
6898                actions.borrow_mut().push(format!("global {}", action.0));
6899            }
6900        });
6901
6902        cx.dispatch_keystroke(window_id, &Keystroke::parse("a").unwrap());
6903
6904        assert_eq!(&*actions.borrow(), &["2 a"]);
6905
6906        actions.borrow_mut().clear();
6907
6908        cx.dispatch_keystroke(window_id, &Keystroke::parse("b").unwrap());
6909
6910        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
6911    }
6912
6913    #[crate::test(self)]
6914    async fn test_model_condition(cx: &mut TestAppContext) {
6915        struct Counter(usize);
6916
6917        impl super::Entity for Counter {
6918            type Event = ();
6919        }
6920
6921        impl Counter {
6922            fn inc(&mut self, cx: &mut ModelContext<Self>) {
6923                self.0 += 1;
6924                cx.notify();
6925            }
6926        }
6927
6928        let model = cx.add_model(|_| Counter(0));
6929
6930        let condition1 = model.condition(cx, |model, _| model.0 == 2);
6931        let condition2 = model.condition(cx, |model, _| model.0 == 3);
6932        smol::pin!(condition1, condition2);
6933
6934        model.update(cx, |model, cx| model.inc(cx));
6935        assert_eq!(poll_once(&mut condition1).await, None);
6936        assert_eq!(poll_once(&mut condition2).await, None);
6937
6938        model.update(cx, |model, cx| model.inc(cx));
6939        assert_eq!(poll_once(&mut condition1).await, Some(()));
6940        assert_eq!(poll_once(&mut condition2).await, None);
6941
6942        model.update(cx, |model, cx| model.inc(cx));
6943        assert_eq!(poll_once(&mut condition2).await, Some(()));
6944
6945        model.update(cx, |_, cx| cx.notify());
6946    }
6947
6948    #[crate::test(self)]
6949    #[should_panic]
6950    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
6951        struct Model;
6952
6953        impl super::Entity for Model {
6954            type Event = ();
6955        }
6956
6957        let model = cx.add_model(|_| Model);
6958        model.condition(cx, |_, _| false).await;
6959    }
6960
6961    #[crate::test(self)]
6962    #[should_panic(expected = "model dropped with pending condition")]
6963    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
6964        struct Model;
6965
6966        impl super::Entity for Model {
6967            type Event = ();
6968        }
6969
6970        let model = cx.add_model(|_| Model);
6971        let condition = model.condition(cx, |_, _| false);
6972        cx.update(|_| drop(model));
6973        condition.await;
6974    }
6975
6976    #[crate::test(self)]
6977    async fn test_view_condition(cx: &mut TestAppContext) {
6978        struct Counter(usize);
6979
6980        impl super::Entity for Counter {
6981            type Event = ();
6982        }
6983
6984        impl super::View for Counter {
6985            fn ui_name() -> &'static str {
6986                "test view"
6987            }
6988
6989            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6990                Empty::new().boxed()
6991            }
6992        }
6993
6994        impl Counter {
6995            fn inc(&mut self, cx: &mut ViewContext<Self>) {
6996                self.0 += 1;
6997                cx.notify();
6998            }
6999        }
7000
7001        let (_, view) = cx.add_window(|_| Counter(0));
7002
7003        let condition1 = view.condition(cx, |view, _| view.0 == 2);
7004        let condition2 = view.condition(cx, |view, _| view.0 == 3);
7005        smol::pin!(condition1, condition2);
7006
7007        view.update(cx, |view, cx| view.inc(cx));
7008        assert_eq!(poll_once(&mut condition1).await, None);
7009        assert_eq!(poll_once(&mut condition2).await, None);
7010
7011        view.update(cx, |view, cx| view.inc(cx));
7012        assert_eq!(poll_once(&mut condition1).await, Some(()));
7013        assert_eq!(poll_once(&mut condition2).await, None);
7014
7015        view.update(cx, |view, cx| view.inc(cx));
7016        assert_eq!(poll_once(&mut condition2).await, Some(()));
7017        view.update(cx, |_, cx| cx.notify());
7018    }
7019
7020    #[crate::test(self)]
7021    #[should_panic]
7022    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
7023        struct View;
7024
7025        impl super::Entity for View {
7026            type Event = ();
7027        }
7028
7029        impl super::View for View {
7030            fn ui_name() -> &'static str {
7031                "test view"
7032            }
7033
7034            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7035                Empty::new().boxed()
7036            }
7037        }
7038
7039        let (_, view) = cx.add_window(|_| View);
7040        view.condition(cx, |_, _| false).await;
7041    }
7042
7043    #[crate::test(self)]
7044    #[should_panic(expected = "view dropped with pending condition")]
7045    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
7046        struct View;
7047
7048        impl super::Entity for View {
7049            type Event = ();
7050        }
7051
7052        impl super::View for View {
7053            fn ui_name() -> &'static str {
7054                "test view"
7055            }
7056
7057            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7058                Empty::new().boxed()
7059            }
7060        }
7061
7062        let (_, root_view) = cx.add_window(|_| View);
7063        let view = cx.add_view(&root_view, |_| View);
7064
7065        let condition = view.condition(cx, |_, _| false);
7066        cx.update(|_| drop(view));
7067        condition.await;
7068    }
7069
7070    #[crate::test(self)]
7071    fn test_refresh_windows(cx: &mut MutableAppContext) {
7072        struct View(usize);
7073
7074        impl super::Entity for View {
7075            type Event = ();
7076        }
7077
7078        impl super::View for View {
7079            fn ui_name() -> &'static str {
7080                "test view"
7081            }
7082
7083            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7084                Empty::new().named(format!("render count: {}", post_inc(&mut self.0)))
7085            }
7086        }
7087
7088        let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
7089        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
7090
7091        assert_eq!(
7092            presenter.borrow().rendered_views[&root_view.id()].name(),
7093            Some("render count: 0")
7094        );
7095
7096        let view = cx.add_view(&root_view, |cx| {
7097            cx.refresh_windows();
7098            View(0)
7099        });
7100
7101        assert_eq!(
7102            presenter.borrow().rendered_views[&root_view.id()].name(),
7103            Some("render count: 1")
7104        );
7105        assert_eq!(
7106            presenter.borrow().rendered_views[&view.id()].name(),
7107            Some("render count: 0")
7108        );
7109
7110        cx.update(|cx| cx.refresh_windows());
7111        assert_eq!(
7112            presenter.borrow().rendered_views[&root_view.id()].name(),
7113            Some("render count: 2")
7114        );
7115        assert_eq!(
7116            presenter.borrow().rendered_views[&view.id()].name(),
7117            Some("render count: 1")
7118        );
7119
7120        cx.update(|cx| {
7121            cx.refresh_windows();
7122            drop(view);
7123        });
7124        assert_eq!(
7125            presenter.borrow().rendered_views[&root_view.id()].name(),
7126            Some("render count: 3")
7127        );
7128        assert_eq!(presenter.borrow().rendered_views.len(), 1);
7129    }
7130
7131    #[crate::test(self)]
7132    async fn test_window_activation(cx: &mut TestAppContext) {
7133        struct View(&'static str);
7134
7135        impl super::Entity for View {
7136            type Event = ();
7137        }
7138
7139        impl super::View for View {
7140            fn ui_name() -> &'static str {
7141                "test view"
7142            }
7143
7144            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7145                Empty::new().boxed()
7146            }
7147        }
7148
7149        let events = Rc::new(RefCell::new(Vec::new()));
7150        let (window_1, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7151            cx.observe_window_activation({
7152                let events = events.clone();
7153                move |this, active, _| events.borrow_mut().push((this.0, active))
7154            })
7155            .detach();
7156            View("window 1")
7157        });
7158        assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
7159
7160        let (window_2, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7161            cx.observe_window_activation({
7162                let events = events.clone();
7163                move |this, active, _| events.borrow_mut().push((this.0, active))
7164            })
7165            .detach();
7166            View("window 2")
7167        });
7168        assert_eq!(
7169            mem::take(&mut *events.borrow_mut()),
7170            [("window 1", false), ("window 2", true)]
7171        );
7172
7173        let (window_3, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7174            cx.observe_window_activation({
7175                let events = events.clone();
7176                move |this, active, _| events.borrow_mut().push((this.0, active))
7177            })
7178            .detach();
7179            View("window 3")
7180        });
7181        assert_eq!(
7182            mem::take(&mut *events.borrow_mut()),
7183            [("window 2", false), ("window 3", true)]
7184        );
7185
7186        cx.simulate_window_activation(Some(window_2));
7187        assert_eq!(
7188            mem::take(&mut *events.borrow_mut()),
7189            [("window 3", false), ("window 2", true)]
7190        );
7191
7192        cx.simulate_window_activation(Some(window_1));
7193        assert_eq!(
7194            mem::take(&mut *events.borrow_mut()),
7195            [("window 2", false), ("window 1", true)]
7196        );
7197
7198        cx.simulate_window_activation(Some(window_3));
7199        assert_eq!(
7200            mem::take(&mut *events.borrow_mut()),
7201            [("window 1", false), ("window 3", true)]
7202        );
7203
7204        cx.simulate_window_activation(Some(window_3));
7205        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
7206    }
7207
7208    #[crate::test(self)]
7209    fn test_child_view(cx: &mut MutableAppContext) {
7210        struct Child {
7211            rendered: Rc<Cell<bool>>,
7212            dropped: Rc<Cell<bool>>,
7213        }
7214
7215        impl super::Entity for Child {
7216            type Event = ();
7217        }
7218
7219        impl super::View for Child {
7220            fn ui_name() -> &'static str {
7221                "child view"
7222            }
7223
7224            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7225                self.rendered.set(true);
7226                Empty::new().boxed()
7227            }
7228        }
7229
7230        impl Drop for Child {
7231            fn drop(&mut self) {
7232                self.dropped.set(true);
7233            }
7234        }
7235
7236        struct Parent {
7237            child: Option<ViewHandle<Child>>,
7238        }
7239
7240        impl super::Entity for Parent {
7241            type Event = ();
7242        }
7243
7244        impl super::View for Parent {
7245            fn ui_name() -> &'static str {
7246                "parent view"
7247            }
7248
7249            fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
7250                if let Some(child) = self.child.as_ref() {
7251                    ChildView::new(child, cx).boxed()
7252                } else {
7253                    Empty::new().boxed()
7254                }
7255            }
7256        }
7257
7258        let child_rendered = Rc::new(Cell::new(false));
7259        let child_dropped = Rc::new(Cell::new(false));
7260        let (_, root_view) = cx.add_window(Default::default(), |cx| Parent {
7261            child: Some(cx.add_view(|_| Child {
7262                rendered: child_rendered.clone(),
7263                dropped: child_dropped.clone(),
7264            })),
7265        });
7266        assert!(child_rendered.take());
7267        assert!(!child_dropped.take());
7268
7269        root_view.update(cx, |view, cx| {
7270            view.child.take();
7271            cx.notify();
7272        });
7273        assert!(!child_rendered.take());
7274        assert!(child_dropped.take());
7275    }
7276}