app.rs

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