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