app.rs

   1use crate::{
   2    elements::ElementBox,
   3    executor::{self, Task},
   4    keymap::{self, Keystroke},
   5    platform::{self, CursorStyle, Platform, PromptLevel, WindowOptions},
   6    presenter::Presenter,
   7    util::post_inc,
   8    AssetCache, AssetSource, ClipboardItem, FontCache, PathPromptOptions, TextLayoutCache,
   9};
  10use anyhow::{anyhow, Result};
  11use keymap::MatchResult;
  12use lazy_static::lazy_static;
  13use parking_lot::Mutex;
  14use platform::Event;
  15use postage::oneshot;
  16use smol::prelude::*;
  17use std::{
  18    any::{self, type_name, Any, TypeId},
  19    cell::RefCell,
  20    collections::{hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque},
  21    fmt::{self, Debug},
  22    hash::{Hash, Hasher},
  23    marker::PhantomData,
  24    mem,
  25    ops::{Deref, DerefMut},
  26    path::{Path, PathBuf},
  27    pin::Pin,
  28    rc::{self, Rc},
  29    sync::{
  30        atomic::{AtomicUsize, Ordering::SeqCst},
  31        Arc, Weak,
  32    },
  33    time::Duration,
  34};
  35
  36pub trait Entity: 'static {
  37    type Event;
  38
  39    fn release(&mut self, _: &mut MutableAppContext) {}
  40    fn app_will_quit(
  41        &mut self,
  42        _: &mut MutableAppContext,
  43    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
  44        None
  45    }
  46}
  47
  48pub trait View: Entity + Sized {
  49    fn ui_name() -> &'static str;
  50    fn render(&mut self, cx: &mut RenderContext<'_, Self>) -> ElementBox;
  51    fn on_focus(&mut self, _: &mut ViewContext<Self>) {}
  52    fn on_blur(&mut self, _: &mut ViewContext<Self>) {}
  53    fn keymap_context(&self, _: &AppContext) -> keymap::Context {
  54        Self::default_keymap_context()
  55    }
  56    fn default_keymap_context() -> keymap::Context {
  57        let mut cx = keymap::Context::default();
  58        cx.set.insert(Self::ui_name().into());
  59        cx
  60    }
  61}
  62
  63pub trait ReadModel {
  64    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T;
  65}
  66
  67pub trait ReadModelWith {
  68    fn read_model_with<E: Entity, T>(
  69        &self,
  70        handle: &ModelHandle<E>,
  71        read: &mut dyn FnMut(&E, &AppContext) -> T,
  72    ) -> T;
  73}
  74
  75pub trait UpdateModel {
  76    fn update_model<T: Entity, O>(
  77        &mut self,
  78        handle: &ModelHandle<T>,
  79        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
  80    ) -> O;
  81}
  82
  83pub trait UpgradeModelHandle {
  84    fn upgrade_model_handle<T: Entity>(
  85        &self,
  86        handle: &WeakModelHandle<T>,
  87    ) -> Option<ModelHandle<T>>;
  88
  89    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool;
  90
  91    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle>;
  92}
  93
  94pub trait UpgradeViewHandle {
  95    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>>;
  96}
  97
  98pub trait ReadView {
  99    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T;
 100}
 101
 102pub trait ReadViewWith {
 103    fn read_view_with<V, T>(
 104        &self,
 105        handle: &ViewHandle<V>,
 106        read: &mut dyn FnMut(&V, &AppContext) -> T,
 107    ) -> T
 108    where
 109        V: View;
 110}
 111
 112pub trait UpdateView {
 113    fn update_view<T, S>(
 114        &mut self,
 115        handle: &ViewHandle<T>,
 116        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 117    ) -> S
 118    where
 119        T: View;
 120}
 121
 122pub trait ElementStateContext: DerefMut<Target = MutableAppContext> {
 123    fn current_view_id(&self) -> usize;
 124
 125    fn element_state<Tag: 'static, T: 'static + Default>(
 126        &mut self,
 127        element_id: usize,
 128    ) -> ElementStateHandle<T> {
 129        let id = ElementStateId {
 130            view_id: self.current_view_id(),
 131            element_id,
 132            tag: TypeId::of::<Tag>(),
 133        };
 134        self.cx
 135            .element_states
 136            .entry(id)
 137            .or_insert_with(|| Box::new(T::default()));
 138        ElementStateHandle::new(id, self.frame_count, &self.cx.ref_counts)
 139    }
 140}
 141
 142pub trait Action: 'static + AnyAction {
 143    type Argument: 'static + Clone;
 144}
 145
 146pub trait AnyAction {
 147    fn id(&self) -> TypeId;
 148    fn name(&self) -> &'static str;
 149    fn as_any(&self) -> &dyn Any;
 150    fn boxed_clone(&self) -> Box<dyn AnyAction>;
 151    fn boxed_clone_as_any(&self) -> Box<dyn Any>;
 152}
 153
 154#[macro_export]
 155macro_rules! action {
 156    ($name:ident, $arg:ty) => {
 157        #[derive(Clone)]
 158        pub struct $name(pub $arg);
 159
 160        impl $crate::Action for $name {
 161            type Argument = $arg;
 162        }
 163
 164        impl $crate::AnyAction for $name {
 165            fn id(&self) -> std::any::TypeId {
 166                std::any::TypeId::of::<$name>()
 167            }
 168
 169            fn name(&self) -> &'static str {
 170                stringify!($name)
 171            }
 172
 173            fn as_any(&self) -> &dyn std::any::Any {
 174                self
 175            }
 176
 177            fn boxed_clone(&self) -> Box<dyn $crate::AnyAction> {
 178                Box::new(self.clone())
 179            }
 180
 181            fn boxed_clone_as_any(&self) -> Box<dyn std::any::Any> {
 182                Box::new(self.clone())
 183            }
 184        }
 185    };
 186
 187    ($name:ident) => {
 188        #[derive(Clone, Debug, Eq, PartialEq)]
 189        pub struct $name;
 190
 191        impl $crate::Action for $name {
 192            type Argument = ();
 193        }
 194
 195        impl $crate::AnyAction for $name {
 196            fn id(&self) -> std::any::TypeId {
 197                std::any::TypeId::of::<$name>()
 198            }
 199
 200            fn name(&self) -> &'static str {
 201                stringify!($name)
 202            }
 203
 204            fn as_any(&self) -> &dyn std::any::Any {
 205                self
 206            }
 207
 208            fn boxed_clone(&self) -> Box<dyn $crate::AnyAction> {
 209                Box::new(self.clone())
 210            }
 211
 212            fn boxed_clone_as_any(&self) -> Box<dyn std::any::Any> {
 213                Box::new(self.clone())
 214            }
 215        }
 216    };
 217}
 218
 219pub struct Menu<'a> {
 220    pub name: &'a str,
 221    pub items: Vec<MenuItem<'a>>,
 222}
 223
 224pub enum MenuItem<'a> {
 225    Action {
 226        name: &'a str,
 227        keystroke: Option<&'a str>,
 228        action: Box<dyn AnyAction>,
 229    },
 230    Separator,
 231}
 232
 233#[derive(Clone)]
 234pub struct App(Rc<RefCell<MutableAppContext>>);
 235
 236#[derive(Clone)]
 237pub struct AsyncAppContext(Rc<RefCell<MutableAppContext>>);
 238
 239#[cfg(any(test, feature = "test-support"))]
 240pub struct TestAppContext {
 241    cx: Rc<RefCell<MutableAppContext>>,
 242    foreground_platform: Rc<platform::test::ForegroundPlatform>,
 243}
 244
 245impl App {
 246    pub fn new(asset_source: impl AssetSource) -> Result<Self> {
 247        let platform = platform::current::platform();
 248        let foreground_platform = platform::current::foreground_platform();
 249        let foreground = Rc::new(executor::Foreground::platform(platform.dispatcher())?);
 250        let app = Self(Rc::new(RefCell::new(MutableAppContext::new(
 251            foreground,
 252            Arc::new(executor::Background::new()),
 253            platform.clone(),
 254            foreground_platform.clone(),
 255            Arc::new(FontCache::new(platform.fonts())),
 256            Default::default(),
 257            asset_source,
 258        ))));
 259
 260        foreground_platform.on_quit(Box::new({
 261            let cx = app.0.clone();
 262            move || {
 263                cx.borrow_mut().quit();
 264            }
 265        }));
 266        foreground_platform.on_menu_command(Box::new({
 267            let cx = app.0.clone();
 268            move |action| {
 269                let mut cx = cx.borrow_mut();
 270                if let Some(key_window_id) = cx.cx.platform.key_window_id() {
 271                    if let Some((presenter, _)) =
 272                        cx.presenters_and_platform_windows.get(&key_window_id)
 273                    {
 274                        let presenter = presenter.clone();
 275                        let path = presenter.borrow().dispatch_path(cx.as_ref());
 276                        cx.dispatch_action_any(key_window_id, &path, action);
 277                    } else {
 278                        cx.dispatch_global_action_any(action);
 279                    }
 280                } else {
 281                    cx.dispatch_global_action_any(action);
 282                }
 283            }
 284        }));
 285
 286        app.0.borrow_mut().weak_self = Some(Rc::downgrade(&app.0));
 287        Ok(app)
 288    }
 289
 290    pub fn background(&self) -> Arc<executor::Background> {
 291        self.0.borrow().background().clone()
 292    }
 293
 294    pub fn on_become_active<F>(self, mut callback: F) -> Self
 295    where
 296        F: 'static + FnMut(&mut MutableAppContext),
 297    {
 298        let cx = self.0.clone();
 299        self.0
 300            .borrow_mut()
 301            .foreground_platform
 302            .on_become_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 303        self
 304    }
 305
 306    pub fn on_resign_active<F>(self, mut callback: F) -> Self
 307    where
 308        F: 'static + FnMut(&mut MutableAppContext),
 309    {
 310        let cx = self.0.clone();
 311        self.0
 312            .borrow_mut()
 313            .foreground_platform
 314            .on_resign_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 315        self
 316    }
 317
 318    pub fn on_quit<F>(self, mut callback: F) -> Self
 319    where
 320        F: 'static + FnMut(&mut MutableAppContext),
 321    {
 322        let cx = self.0.clone();
 323        self.0
 324            .borrow_mut()
 325            .foreground_platform
 326            .on_quit(Box::new(move || callback(&mut *cx.borrow_mut())));
 327        self
 328    }
 329
 330    pub fn on_event<F>(self, mut callback: F) -> Self
 331    where
 332        F: 'static + FnMut(Event, &mut MutableAppContext) -> bool,
 333    {
 334        let cx = self.0.clone();
 335        self.0
 336            .borrow_mut()
 337            .foreground_platform
 338            .on_event(Box::new(move |event| {
 339                callback(event, &mut *cx.borrow_mut())
 340            }));
 341        self
 342    }
 343
 344    pub fn on_open_files<F>(self, mut callback: F) -> Self
 345    where
 346        F: 'static + FnMut(Vec<PathBuf>, &mut MutableAppContext),
 347    {
 348        let cx = self.0.clone();
 349        self.0
 350            .borrow_mut()
 351            .foreground_platform
 352            .on_open_files(Box::new(move |paths| {
 353                callback(paths, &mut *cx.borrow_mut())
 354            }));
 355        self
 356    }
 357
 358    pub fn run<F>(self, on_finish_launching: F)
 359    where
 360        F: 'static + FnOnce(&mut MutableAppContext),
 361    {
 362        let platform = self.0.borrow().foreground_platform.clone();
 363        platform.run(Box::new(move || {
 364            let mut cx = self.0.borrow_mut();
 365            let cx = &mut *cx;
 366            crate::views::init(cx);
 367            on_finish_launching(cx);
 368        }))
 369    }
 370
 371    pub fn platform(&self) -> Arc<dyn Platform> {
 372        self.0.borrow().platform()
 373    }
 374
 375    pub fn font_cache(&self) -> Arc<FontCache> {
 376        self.0.borrow().cx.font_cache.clone()
 377    }
 378
 379    fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 380        let mut state = self.0.borrow_mut();
 381        let result = state.update(callback);
 382        state.pending_notifications.clear();
 383        result
 384    }
 385}
 386
 387#[cfg(any(test, feature = "test-support"))]
 388impl TestAppContext {
 389    pub fn new(
 390        foreground_platform: Rc<platform::test::ForegroundPlatform>,
 391        platform: Arc<dyn Platform>,
 392        foreground: Rc<executor::Foreground>,
 393        background: Arc<executor::Background>,
 394        font_cache: Arc<FontCache>,
 395        leak_detector: Arc<Mutex<LeakDetector>>,
 396        first_entity_id: usize,
 397    ) -> Self {
 398        let mut cx = MutableAppContext::new(
 399            foreground.clone(),
 400            background,
 401            platform,
 402            foreground_platform.clone(),
 403            font_cache,
 404            RefCounts {
 405                #[cfg(any(test, feature = "test-support"))]
 406                leak_detector,
 407                ..Default::default()
 408            },
 409            (),
 410        );
 411        cx.next_entity_id = first_entity_id;
 412        let cx = TestAppContext {
 413            cx: Rc::new(RefCell::new(cx)),
 414            foreground_platform,
 415        };
 416        cx.cx.borrow_mut().weak_self = Some(Rc::downgrade(&cx.cx));
 417        cx
 418    }
 419
 420    pub fn dispatch_action<A: Action>(
 421        &self,
 422        window_id: usize,
 423        responder_chain: Vec<usize>,
 424        action: A,
 425    ) {
 426        self.cx
 427            .borrow_mut()
 428            .dispatch_action_any(window_id, &responder_chain, &action);
 429    }
 430
 431    pub fn dispatch_global_action<A: Action>(&self, action: A) {
 432        self.cx.borrow_mut().dispatch_global_action(action);
 433    }
 434
 435    pub fn dispatch_keystroke(
 436        &self,
 437        window_id: usize,
 438        responder_chain: Vec<usize>,
 439        keystroke: &Keystroke,
 440    ) -> Result<bool> {
 441        let mut state = self.cx.borrow_mut();
 442        state.dispatch_keystroke(window_id, responder_chain, keystroke)
 443    }
 444
 445    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 446    where
 447        T: Entity,
 448        F: FnOnce(&mut ModelContext<T>) -> T,
 449    {
 450        self.cx.borrow_mut().add_model(build_model)
 451    }
 452
 453    pub fn add_window<T, F>(&mut self, build_root_view: F) -> (usize, ViewHandle<T>)
 454    where
 455        T: View,
 456        F: FnOnce(&mut ViewContext<T>) -> T,
 457    {
 458        self.cx
 459            .borrow_mut()
 460            .add_window(Default::default(), build_root_view)
 461    }
 462
 463    pub fn window_ids(&self) -> Vec<usize> {
 464        self.cx.borrow().window_ids().collect()
 465    }
 466
 467    pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
 468        self.cx.borrow().root_view(window_id)
 469    }
 470
 471    pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
 472    where
 473        T: View,
 474        F: FnOnce(&mut ViewContext<T>) -> T,
 475    {
 476        self.cx.borrow_mut().add_view(window_id, build_view)
 477    }
 478
 479    pub fn add_option_view<T, F>(
 480        &mut self,
 481        window_id: usize,
 482        build_view: F,
 483    ) -> Option<ViewHandle<T>>
 484    where
 485        T: View,
 486        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
 487    {
 488        self.cx.borrow_mut().add_option_view(window_id, build_view)
 489    }
 490
 491    pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
 492        callback(self.cx.borrow().as_ref())
 493    }
 494
 495    pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 496        let mut state = self.cx.borrow_mut();
 497        // Don't increment pending flushes in order to effects to be flushed before the callback
 498        // completes, which is helpful in tests.
 499        let result = callback(&mut *state);
 500        // Flush effects after the callback just in case there are any. This can happen in edge
 501        // cases such as the closure dropping handles.
 502        state.flush_effects();
 503        result
 504    }
 505
 506    pub fn to_async(&self) -> AsyncAppContext {
 507        AsyncAppContext(self.cx.clone())
 508    }
 509
 510    pub fn font_cache(&self) -> Arc<FontCache> {
 511        self.cx.borrow().cx.font_cache.clone()
 512    }
 513
 514    pub fn foreground_platform(&self) -> Rc<platform::test::ForegroundPlatform> {
 515        self.foreground_platform.clone()
 516    }
 517
 518    pub fn platform(&self) -> Arc<dyn platform::Platform> {
 519        self.cx.borrow().cx.platform.clone()
 520    }
 521
 522    pub fn foreground(&self) -> Rc<executor::Foreground> {
 523        self.cx.borrow().foreground().clone()
 524    }
 525
 526    pub fn background(&self) -> Arc<executor::Background> {
 527        self.cx.borrow().background().clone()
 528    }
 529
 530    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
 531    where
 532        F: FnOnce(AsyncAppContext) -> Fut,
 533        Fut: 'static + Future<Output = T>,
 534        T: 'static,
 535    {
 536        self.cx.borrow_mut().spawn(f)
 537    }
 538
 539    pub fn simulate_new_path_selection(&self, result: impl FnOnce(PathBuf) -> Option<PathBuf>) {
 540        self.foreground_platform.simulate_new_path_selection(result);
 541    }
 542
 543    pub fn did_prompt_for_new_path(&self) -> bool {
 544        self.foreground_platform.as_ref().did_prompt_for_new_path()
 545    }
 546
 547    pub fn simulate_prompt_answer(&self, window_id: usize, answer: usize) {
 548        use postage::prelude::Sink as _;
 549
 550        let mut state = self.cx.borrow_mut();
 551        let (_, window) = state
 552            .presenters_and_platform_windows
 553            .get_mut(&window_id)
 554            .unwrap();
 555        let test_window = window
 556            .as_any_mut()
 557            .downcast_mut::<platform::test::Window>()
 558            .unwrap();
 559        let mut done_tx = test_window
 560            .last_prompt
 561            .take()
 562            .expect("prompt was not called");
 563        let _ = done_tx.try_send(answer);
 564    }
 565
 566    #[cfg(any(test, feature = "test-support"))]
 567    pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
 568        self.cx.borrow().leak_detector()
 569    }
 570}
 571
 572impl AsyncAppContext {
 573    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
 574    where
 575        F: FnOnce(AsyncAppContext) -> Fut,
 576        Fut: 'static + Future<Output = T>,
 577        T: 'static,
 578    {
 579        self.0.borrow().foreground.spawn(f(self.clone()))
 580    }
 581
 582    pub fn read<T, F: FnOnce(&AppContext) -> T>(&mut self, callback: F) -> T {
 583        callback(self.0.borrow().as_ref())
 584    }
 585
 586    pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 587        self.0.borrow_mut().update(callback)
 588    }
 589
 590    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 591    where
 592        T: Entity,
 593        F: FnOnce(&mut ModelContext<T>) -> T,
 594    {
 595        self.update(|cx| cx.add_model(build_model))
 596    }
 597
 598    pub fn platform(&self) -> Arc<dyn Platform> {
 599        self.0.borrow().platform()
 600    }
 601
 602    pub fn foreground(&self) -> Rc<executor::Foreground> {
 603        self.0.borrow().foreground.clone()
 604    }
 605
 606    pub fn background(&self) -> Arc<executor::Background> {
 607        self.0.borrow().cx.background.clone()
 608    }
 609}
 610
 611impl UpdateModel for AsyncAppContext {
 612    fn update_model<E: Entity, O>(
 613        &mut self,
 614        handle: &ModelHandle<E>,
 615        update: &mut dyn FnMut(&mut E, &mut ModelContext<E>) -> O,
 616    ) -> O {
 617        self.0.borrow_mut().update_model(handle, update)
 618    }
 619}
 620
 621impl UpgradeModelHandle for AsyncAppContext {
 622    fn upgrade_model_handle<T: Entity>(
 623        &self,
 624        handle: &WeakModelHandle<T>,
 625    ) -> Option<ModelHandle<T>> {
 626        self.0.borrow().upgrade_model_handle(handle)
 627    }
 628
 629    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
 630        self.0.borrow().model_handle_is_upgradable(handle)
 631    }
 632
 633    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
 634        self.0.borrow().upgrade_any_model_handle(handle)
 635    }
 636}
 637
 638impl UpgradeViewHandle for AsyncAppContext {
 639    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
 640        self.0.borrow_mut().upgrade_view_handle(handle)
 641    }
 642}
 643
 644impl ReadModelWith for AsyncAppContext {
 645    fn read_model_with<E: Entity, T>(
 646        &self,
 647        handle: &ModelHandle<E>,
 648        read: &mut dyn FnMut(&E, &AppContext) -> T,
 649    ) -> T {
 650        let cx = self.0.borrow();
 651        let cx = cx.as_ref();
 652        read(handle.read(cx), cx)
 653    }
 654}
 655
 656impl UpdateView for AsyncAppContext {
 657    fn update_view<T, S>(
 658        &mut self,
 659        handle: &ViewHandle<T>,
 660        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 661    ) -> S
 662    where
 663        T: View,
 664    {
 665        self.0.borrow_mut().update_view(handle, update)
 666    }
 667}
 668
 669impl ReadViewWith for AsyncAppContext {
 670    fn read_view_with<V, T>(
 671        &self,
 672        handle: &ViewHandle<V>,
 673        read: &mut dyn FnMut(&V, &AppContext) -> T,
 674    ) -> T
 675    where
 676        V: View,
 677    {
 678        let cx = self.0.borrow();
 679        let cx = cx.as_ref();
 680        read(handle.read(cx), cx)
 681    }
 682}
 683
 684#[cfg(any(test, feature = "test-support"))]
 685impl UpdateModel for TestAppContext {
 686    fn update_model<T: Entity, O>(
 687        &mut self,
 688        handle: &ModelHandle<T>,
 689        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
 690    ) -> O {
 691        self.cx.borrow_mut().update_model(handle, update)
 692    }
 693}
 694
 695#[cfg(any(test, feature = "test-support"))]
 696impl ReadModelWith for TestAppContext {
 697    fn read_model_with<E: Entity, T>(
 698        &self,
 699        handle: &ModelHandle<E>,
 700        read: &mut dyn FnMut(&E, &AppContext) -> T,
 701    ) -> T {
 702        let cx = self.cx.borrow();
 703        let cx = cx.as_ref();
 704        read(handle.read(cx), cx)
 705    }
 706}
 707
 708#[cfg(any(test, feature = "test-support"))]
 709impl UpdateView for TestAppContext {
 710    fn update_view<T, S>(
 711        &mut self,
 712        handle: &ViewHandle<T>,
 713        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 714    ) -> S
 715    where
 716        T: View,
 717    {
 718        self.cx.borrow_mut().update_view(handle, update)
 719    }
 720}
 721
 722#[cfg(any(test, feature = "test-support"))]
 723impl ReadViewWith for TestAppContext {
 724    fn read_view_with<V, T>(
 725        &self,
 726        handle: &ViewHandle<V>,
 727        read: &mut dyn FnMut(&V, &AppContext) -> T,
 728    ) -> T
 729    where
 730        V: View,
 731    {
 732        let cx = self.cx.borrow();
 733        let cx = cx.as_ref();
 734        read(handle.read(cx), cx)
 735    }
 736}
 737
 738type ActionCallback =
 739    dyn FnMut(&mut dyn AnyView, &dyn AnyAction, &mut MutableAppContext, usize, usize);
 740type GlobalActionCallback = dyn FnMut(&dyn AnyAction, &mut MutableAppContext);
 741
 742type SubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut MutableAppContext) -> bool>;
 743type ObservationCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>;
 744type ReleaseObservationCallback = Box<dyn FnMut(&mut MutableAppContext)>;
 745
 746pub struct MutableAppContext {
 747    weak_self: Option<rc::Weak<RefCell<Self>>>,
 748    foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 749    assets: Arc<AssetCache>,
 750    cx: AppContext,
 751    capture_actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 752    actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 753    global_actions: HashMap<TypeId, Box<GlobalActionCallback>>,
 754    keystroke_matcher: keymap::Matcher,
 755    next_entity_id: usize,
 756    next_window_id: usize,
 757    next_subscription_id: usize,
 758    frame_count: usize,
 759    subscriptions: Arc<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>,
 760    observations: Arc<Mutex<HashMap<usize, BTreeMap<usize, ObservationCallback>>>>,
 761    release_observations: Arc<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>,
 762    presenters_and_platform_windows:
 763        HashMap<usize, (Rc<RefCell<Presenter>>, Box<dyn platform::Window>)>,
 764    foreground: Rc<executor::Foreground>,
 765    pending_effects: VecDeque<Effect>,
 766    pending_notifications: HashSet<usize>,
 767    pending_flushes: usize,
 768    flushing_effects: bool,
 769    next_cursor_style_handle_id: Arc<AtomicUsize>,
 770    halt_action_dispatch: bool,
 771}
 772
 773impl MutableAppContext {
 774    fn new(
 775        foreground: Rc<executor::Foreground>,
 776        background: Arc<executor::Background>,
 777        platform: Arc<dyn platform::Platform>,
 778        foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 779        font_cache: Arc<FontCache>,
 780        ref_counts: RefCounts,
 781        asset_source: impl AssetSource,
 782    ) -> Self {
 783        Self {
 784            weak_self: None,
 785            foreground_platform,
 786            assets: Arc::new(AssetCache::new(asset_source)),
 787            cx: AppContext {
 788                models: Default::default(),
 789                views: Default::default(),
 790                windows: Default::default(),
 791                app_states: Default::default(),
 792                element_states: Default::default(),
 793                ref_counts: Arc::new(Mutex::new(ref_counts)),
 794                background,
 795                font_cache,
 796                platform,
 797            },
 798            capture_actions: HashMap::new(),
 799            actions: HashMap::new(),
 800            global_actions: HashMap::new(),
 801            keystroke_matcher: keymap::Matcher::default(),
 802            next_entity_id: 0,
 803            next_window_id: 0,
 804            next_subscription_id: 0,
 805            frame_count: 0,
 806            subscriptions: Default::default(),
 807            observations: Default::default(),
 808            release_observations: Default::default(),
 809            presenters_and_platform_windows: HashMap::new(),
 810            foreground,
 811            pending_effects: VecDeque::new(),
 812            pending_notifications: HashSet::new(),
 813            pending_flushes: 0,
 814            flushing_effects: false,
 815            next_cursor_style_handle_id: Default::default(),
 816            halt_action_dispatch: false,
 817        }
 818    }
 819
 820    pub fn upgrade(&self) -> App {
 821        App(self.weak_self.as_ref().unwrap().upgrade().unwrap())
 822    }
 823
 824    pub fn quit(&mut self) {
 825        let mut futures = Vec::new();
 826        for model_id in self.cx.models.keys().copied().collect::<Vec<_>>() {
 827            let mut model = self.cx.models.remove(&model_id).unwrap();
 828            futures.extend(model.app_will_quit(self));
 829            self.cx.models.insert(model_id, model);
 830        }
 831
 832        for view_id in self.cx.views.keys().copied().collect::<Vec<_>>() {
 833            let mut view = self.cx.views.remove(&view_id).unwrap();
 834            futures.extend(view.app_will_quit(self));
 835            self.cx.views.insert(view_id, view);
 836        }
 837
 838        self.remove_all_windows();
 839
 840        let futures = futures::future::join_all(futures);
 841        if self
 842            .background
 843            .block_with_timeout(Duration::from_millis(100), futures)
 844            .is_err()
 845        {
 846            log::error!("timed out waiting on app_will_quit");
 847        }
 848    }
 849
 850    pub fn remove_all_windows(&mut self) {
 851        for (window_id, _) in self.cx.windows.drain() {
 852            self.presenters_and_platform_windows.remove(&window_id);
 853        }
 854        self.flush_effects();
 855    }
 856
 857    pub fn platform(&self) -> Arc<dyn platform::Platform> {
 858        self.cx.platform.clone()
 859    }
 860
 861    pub fn font_cache(&self) -> &Arc<FontCache> {
 862        &self.cx.font_cache
 863    }
 864
 865    pub fn foreground(&self) -> &Rc<executor::Foreground> {
 866        &self.foreground
 867    }
 868
 869    pub fn background(&self) -> &Arc<executor::Background> {
 870        &self.cx.background
 871    }
 872
 873    pub fn debug_elements(&self, window_id: usize) -> Option<crate::json::Value> {
 874        self.presenters_and_platform_windows
 875            .get(&window_id)
 876            .and_then(|(presenter, _)| presenter.borrow().debug_elements(self))
 877    }
 878
 879    pub fn add_action<A, V, F>(&mut self, handler: F)
 880    where
 881        A: Action,
 882        V: View,
 883        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
 884    {
 885        self.add_action_internal(handler, false)
 886    }
 887
 888    pub fn capture_action<A, V, F>(&mut self, handler: F)
 889    where
 890        A: Action,
 891        V: View,
 892        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
 893    {
 894        self.add_action_internal(handler, true)
 895    }
 896
 897    fn add_action_internal<A, V, F>(&mut self, mut handler: F, capture: bool)
 898    where
 899        A: Action,
 900        V: View,
 901        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
 902    {
 903        let handler = Box::new(
 904            move |view: &mut dyn AnyView,
 905                  action: &dyn AnyAction,
 906                  cx: &mut MutableAppContext,
 907                  window_id: usize,
 908                  view_id: usize| {
 909                let action = action.as_any().downcast_ref().unwrap();
 910                let mut cx = ViewContext::new(cx, window_id, view_id);
 911                handler(
 912                    view.as_any_mut()
 913                        .downcast_mut()
 914                        .expect("downcast is type safe"),
 915                    action,
 916                    &mut cx,
 917                );
 918            },
 919        );
 920
 921        let actions = if capture {
 922            &mut self.capture_actions
 923        } else {
 924            &mut self.actions
 925        };
 926
 927        actions
 928            .entry(TypeId::of::<V>())
 929            .or_default()
 930            .entry(TypeId::of::<A>())
 931            .or_default()
 932            .push(handler);
 933    }
 934
 935    pub fn add_async_action<A, V, F>(&mut self, mut handler: F)
 936    where
 937        A: Action,
 938        V: View,
 939        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> Option<Task<Result<()>>>,
 940    {
 941        self.add_action(move |view, action, cx| {
 942            handler(view, action, cx).map(|task| task.detach_and_log_err(cx));
 943        })
 944    }
 945
 946    pub fn add_global_action<A, F>(&mut self, mut handler: F)
 947    where
 948        A: Action,
 949        F: 'static + FnMut(&A, &mut MutableAppContext),
 950    {
 951        let handler = Box::new(move |action: &dyn AnyAction, cx: &mut MutableAppContext| {
 952            let action = action.as_any().downcast_ref().unwrap();
 953            handler(action, cx);
 954        });
 955
 956        if self
 957            .global_actions
 958            .insert(TypeId::of::<A>(), handler)
 959            .is_some()
 960        {
 961            panic!("registered multiple global handlers for the same action type");
 962        }
 963    }
 964
 965    pub fn window_ids(&self) -> impl Iterator<Item = usize> + '_ {
 966        self.cx.windows.keys().cloned()
 967    }
 968
 969    pub fn activate_window(&self, window_id: usize) {
 970        if let Some((_, window)) = self.presenters_and_platform_windows.get(&window_id) {
 971            window.activate()
 972        }
 973    }
 974
 975    pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
 976        self.cx
 977            .windows
 978            .get(&window_id)
 979            .and_then(|window| window.root_view.clone().downcast::<T>())
 980    }
 981
 982    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
 983        self.cx.root_view_id(window_id)
 984    }
 985
 986    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
 987        self.cx.focused_view_id(window_id)
 988    }
 989
 990    pub fn render_view(
 991        &mut self,
 992        window_id: usize,
 993        view_id: usize,
 994        titlebar_height: f32,
 995        refreshing: bool,
 996    ) -> Result<ElementBox> {
 997        let mut view = self
 998            .cx
 999            .views
1000            .remove(&(window_id, view_id))
1001            .ok_or(anyhow!("view not found"))?;
1002        let element = view.render(window_id, view_id, titlebar_height, refreshing, self);
1003        self.cx.views.insert((window_id, view_id), view);
1004        Ok(element)
1005    }
1006
1007    pub fn render_views(
1008        &mut self,
1009        window_id: usize,
1010        titlebar_height: f32,
1011    ) -> HashMap<usize, ElementBox> {
1012        self.start_frame();
1013        let view_ids = self
1014            .views
1015            .keys()
1016            .filter_map(|(win_id, view_id)| {
1017                if *win_id == window_id {
1018                    Some(*view_id)
1019                } else {
1020                    None
1021                }
1022            })
1023            .collect::<Vec<_>>();
1024        view_ids
1025            .into_iter()
1026            .map(|view_id| {
1027                (
1028                    view_id,
1029                    self.render_view(window_id, view_id, titlebar_height, false)
1030                        .unwrap(),
1031                )
1032            })
1033            .collect()
1034    }
1035
1036    pub(crate) fn start_frame(&mut self) {
1037        self.frame_count += 1;
1038    }
1039
1040    pub fn update<T, F: FnOnce(&mut Self) -> T>(&mut self, callback: F) -> T {
1041        self.pending_flushes += 1;
1042        let result = callback(self);
1043        self.flush_effects();
1044        result
1045    }
1046
1047    pub fn set_menus(&mut self, menus: Vec<Menu>) {
1048        self.foreground_platform.set_menus(menus);
1049    }
1050
1051    fn prompt(
1052        &self,
1053        window_id: usize,
1054        level: PromptLevel,
1055        msg: &str,
1056        answers: &[&str],
1057    ) -> oneshot::Receiver<usize> {
1058        let (_, window) = &self.presenters_and_platform_windows[&window_id];
1059        window.prompt(level, msg, answers)
1060    }
1061
1062    pub fn prompt_for_paths(
1063        &self,
1064        options: PathPromptOptions,
1065    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
1066        self.foreground_platform.prompt_for_paths(options)
1067    }
1068
1069    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
1070        self.foreground_platform.prompt_for_new_path(directory)
1071    }
1072
1073    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1074    where
1075        E: Entity,
1076        E::Event: 'static,
1077        H: Handle<E>,
1078        F: 'static + FnMut(H, &E::Event, &mut Self),
1079    {
1080        self.subscribe_internal(handle, move |handle, event, cx| {
1081            callback(handle, event, cx);
1082            true
1083        })
1084    }
1085
1086    pub fn observe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1087    where
1088        E: Entity,
1089        E::Event: 'static,
1090        H: Handle<E>,
1091        F: 'static + FnMut(H, &mut Self),
1092    {
1093        self.observe_internal(handle, move |handle, cx| {
1094            callback(handle, cx);
1095            true
1096        })
1097    }
1098
1099    pub fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1100    where
1101        E: Entity,
1102        E::Event: 'static,
1103        H: Handle<E>,
1104        F: 'static + FnMut(H, &E::Event, &mut Self) -> bool,
1105    {
1106        let id = post_inc(&mut self.next_subscription_id);
1107        let emitter = handle.downgrade();
1108        self.subscriptions
1109            .lock()
1110            .entry(handle.id())
1111            .or_default()
1112            .insert(
1113                id,
1114                Box::new(move |payload, cx| {
1115                    if let Some(emitter) = H::upgrade_from(&emitter, cx.as_ref()) {
1116                        let payload = payload.downcast_ref().expect("downcast is type safe");
1117                        callback(emitter, payload, cx)
1118                    } else {
1119                        false
1120                    }
1121                }),
1122            );
1123        Subscription::Subscription {
1124            id,
1125            entity_id: handle.id(),
1126            subscriptions: Some(Arc::downgrade(&self.subscriptions)),
1127        }
1128    }
1129
1130    fn observe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1131    where
1132        E: Entity,
1133        E::Event: 'static,
1134        H: Handle<E>,
1135        F: 'static + FnMut(H, &mut Self) -> bool,
1136    {
1137        let id = post_inc(&mut self.next_subscription_id);
1138        let observed = handle.downgrade();
1139        self.observations
1140            .lock()
1141            .entry(handle.id())
1142            .or_default()
1143            .insert(
1144                id,
1145                Box::new(move |cx| {
1146                    if let Some(observed) = H::upgrade_from(&observed, cx) {
1147                        callback(observed, cx)
1148                    } else {
1149                        false
1150                    }
1151                }),
1152            );
1153        Subscription::Observation {
1154            id,
1155            entity_id: handle.id(),
1156            observations: Some(Arc::downgrade(&self.observations)),
1157        }
1158    }
1159
1160    pub fn observe_release<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1161    where
1162        E: Entity,
1163        E::Event: 'static,
1164        H: Handle<E>,
1165        F: 'static + FnMut(&mut Self),
1166    {
1167        let id = post_inc(&mut self.next_subscription_id);
1168        self.release_observations
1169            .lock()
1170            .entry(handle.id())
1171            .or_default()
1172            .insert(id, Box::new(move |cx| callback(cx)));
1173        Subscription::ReleaseObservation {
1174            id,
1175            entity_id: handle.id(),
1176            observations: Some(Arc::downgrade(&self.release_observations)),
1177        }
1178    }
1179
1180    fn defer(&mut self, callback: Box<dyn FnOnce(&mut MutableAppContext)>) {
1181        self.pending_effects.push_back(Effect::Deferred(callback))
1182    }
1183
1184    pub(crate) fn notify_model(&mut self, model_id: usize) {
1185        if self.pending_notifications.insert(model_id) {
1186            self.pending_effects
1187                .push_back(Effect::ModelNotification { model_id });
1188        }
1189    }
1190
1191    pub(crate) fn notify_view(&mut self, window_id: usize, view_id: usize) {
1192        if self.pending_notifications.insert(view_id) {
1193            self.pending_effects
1194                .push_back(Effect::ViewNotification { window_id, view_id });
1195        }
1196    }
1197
1198    pub fn dispatch_action<A: Action>(
1199        &mut self,
1200        window_id: usize,
1201        responder_chain: Vec<usize>,
1202        action: &A,
1203    ) {
1204        self.dispatch_action_any(window_id, &responder_chain, action);
1205    }
1206
1207    pub(crate) fn dispatch_action_any(
1208        &mut self,
1209        window_id: usize,
1210        path: &[usize],
1211        action: &dyn AnyAction,
1212    ) -> bool {
1213        self.update(|this| {
1214            this.halt_action_dispatch = false;
1215            for (capture_phase, view_id) in path
1216                .iter()
1217                .map(|view_id| (true, *view_id))
1218                .chain(path.iter().rev().map(|view_id| (false, *view_id)))
1219            {
1220                if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
1221                    let type_id = view.as_any().type_id();
1222
1223                    if let Some((name, mut handlers)) = this
1224                        .actions_mut(capture_phase)
1225                        .get_mut(&type_id)
1226                        .and_then(|h| h.remove_entry(&action.id()))
1227                    {
1228                        for handler in handlers.iter_mut().rev() {
1229                            this.halt_action_dispatch = true;
1230                            handler(view.as_mut(), action, this, window_id, view_id);
1231                            if this.halt_action_dispatch {
1232                                break;
1233                            }
1234                        }
1235                        this.actions_mut(capture_phase)
1236                            .get_mut(&type_id)
1237                            .unwrap()
1238                            .insert(name, handlers);
1239                    }
1240
1241                    this.cx.views.insert((window_id, view_id), view);
1242
1243                    if this.halt_action_dispatch {
1244                        break;
1245                    }
1246                }
1247            }
1248
1249            if !this.halt_action_dispatch {
1250                this.dispatch_global_action_any(action);
1251            }
1252            this.halt_action_dispatch
1253        })
1254    }
1255
1256    fn actions_mut(
1257        &mut self,
1258        capture_phase: bool,
1259    ) -> &mut HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>> {
1260        if capture_phase {
1261            &mut self.capture_actions
1262        } else {
1263            &mut self.actions
1264        }
1265    }
1266
1267    pub fn dispatch_global_action<A: Action>(&mut self, action: A) {
1268        self.dispatch_global_action_any(&action);
1269    }
1270
1271    fn dispatch_global_action_any(&mut self, action: &dyn AnyAction) -> bool {
1272        self.update(|this| {
1273            if let Some((name, mut handler)) = this.global_actions.remove_entry(&action.id()) {
1274                handler(action, this);
1275                this.global_actions.insert(name, handler);
1276                true
1277            } else {
1278                false
1279            }
1280        })
1281    }
1282
1283    pub fn add_bindings<T: IntoIterator<Item = keymap::Binding>>(&mut self, bindings: T) {
1284        self.keystroke_matcher.add_bindings(bindings);
1285    }
1286
1287    pub fn dispatch_keystroke(
1288        &mut self,
1289        window_id: usize,
1290        responder_chain: Vec<usize>,
1291        keystroke: &Keystroke,
1292    ) -> Result<bool> {
1293        let mut context_chain = Vec::new();
1294        for view_id in &responder_chain {
1295            if let Some(view) = self.cx.views.get(&(window_id, *view_id)) {
1296                context_chain.push(view.keymap_context(self.as_ref()));
1297            } else {
1298                return Err(anyhow!(
1299                    "View {} in responder chain does not exist",
1300                    view_id
1301                ));
1302            }
1303        }
1304
1305        let mut pending = false;
1306        for (i, cx) in context_chain.iter().enumerate().rev() {
1307            match self
1308                .keystroke_matcher
1309                .push_keystroke(keystroke.clone(), responder_chain[i], cx)
1310            {
1311                MatchResult::None => {}
1312                MatchResult::Pending => pending = true,
1313                MatchResult::Action(action) => {
1314                    if self.dispatch_action_any(window_id, &responder_chain[0..=i], action.as_ref())
1315                    {
1316                        self.keystroke_matcher.clear_pending();
1317                        return Ok(true);
1318                    }
1319                }
1320            }
1321        }
1322
1323        Ok(pending)
1324    }
1325
1326    pub fn add_app_state<T: 'static>(&mut self, state: T) {
1327        self.cx
1328            .app_states
1329            .insert(TypeId::of::<T>(), Box::new(state));
1330    }
1331
1332    pub fn update_app_state<T: 'static, F, U>(&mut self, update: F) -> U
1333    where
1334        F: FnOnce(&mut T, &mut MutableAppContext) -> U,
1335    {
1336        let type_id = TypeId::of::<T>();
1337        let mut state = self
1338            .cx
1339            .app_states
1340            .remove(&type_id)
1341            .expect("no app state has been added for this type");
1342        let result = update(state.downcast_mut().unwrap(), self);
1343        self.cx.app_states.insert(type_id, state);
1344        result
1345    }
1346
1347    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
1348    where
1349        T: Entity,
1350        F: FnOnce(&mut ModelContext<T>) -> T,
1351    {
1352        self.update(|this| {
1353            let model_id = post_inc(&mut this.next_entity_id);
1354            let handle = ModelHandle::new(model_id, &this.cx.ref_counts);
1355            let mut cx = ModelContext::new(this, model_id);
1356            let model = build_model(&mut cx);
1357            this.cx.models.insert(model_id, Box::new(model));
1358            handle
1359        })
1360    }
1361
1362    pub fn add_window<T, F>(
1363        &mut self,
1364        window_options: WindowOptions,
1365        build_root_view: F,
1366    ) -> (usize, ViewHandle<T>)
1367    where
1368        T: View,
1369        F: FnOnce(&mut ViewContext<T>) -> T,
1370    {
1371        self.update(|this| {
1372            let window_id = post_inc(&mut this.next_window_id);
1373            let root_view = this.add_view(window_id, build_root_view);
1374
1375            this.cx.windows.insert(
1376                window_id,
1377                Window {
1378                    root_view: root_view.clone().into(),
1379                    focused_view_id: root_view.id(),
1380                    invalidation: None,
1381                },
1382            );
1383            this.open_platform_window(window_id, window_options);
1384            root_view.update(this, |view, cx| {
1385                view.on_focus(cx);
1386                cx.notify();
1387            });
1388
1389            (window_id, root_view)
1390        })
1391    }
1392
1393    pub fn remove_window(&mut self, window_id: usize) {
1394        self.cx.windows.remove(&window_id);
1395        self.presenters_and_platform_windows.remove(&window_id);
1396        self.flush_effects();
1397    }
1398
1399    fn open_platform_window(&mut self, window_id: usize, window_options: WindowOptions) {
1400        let mut window =
1401            self.cx
1402                .platform
1403                .open_window(window_id, window_options, self.foreground.clone());
1404        let presenter = Rc::new(RefCell::new(
1405            self.build_presenter(window_id, window.titlebar_height()),
1406        ));
1407
1408        {
1409            let mut app = self.upgrade();
1410            let presenter = presenter.clone();
1411            window.on_event(Box::new(move |event| {
1412                app.update(|cx| {
1413                    if let Event::KeyDown { keystroke, .. } = &event {
1414                        if cx
1415                            .dispatch_keystroke(
1416                                window_id,
1417                                presenter.borrow().dispatch_path(cx.as_ref()),
1418                                keystroke,
1419                            )
1420                            .unwrap()
1421                        {
1422                            return;
1423                        }
1424                    }
1425
1426                    presenter.borrow_mut().dispatch_event(event, cx);
1427                })
1428            }));
1429        }
1430
1431        {
1432            let mut app = self.upgrade();
1433            window.on_resize(Box::new(move || {
1434                app.update(|cx| cx.resize_window(window_id))
1435            }));
1436        }
1437
1438        {
1439            let mut app = self.upgrade();
1440            window.on_close(Box::new(move || {
1441                app.update(|cx| cx.remove_window(window_id));
1442            }));
1443        }
1444
1445        self.presenters_and_platform_windows
1446            .insert(window_id, (presenter.clone(), window));
1447    }
1448
1449    pub fn build_presenter(&mut self, window_id: usize, titlebar_height: f32) -> Presenter {
1450        Presenter::new(
1451            window_id,
1452            titlebar_height,
1453            self.cx.font_cache.clone(),
1454            TextLayoutCache::new(self.cx.platform.fonts()),
1455            self.assets.clone(),
1456            self,
1457        )
1458    }
1459
1460    pub fn build_render_context<V: View>(
1461        &mut self,
1462        window_id: usize,
1463        view_id: usize,
1464        titlebar_height: f32,
1465        refreshing: bool,
1466    ) -> RenderContext<V> {
1467        RenderContext {
1468            app: self,
1469            titlebar_height,
1470            refreshing,
1471            window_id,
1472            view_id,
1473            view_type: PhantomData,
1474        }
1475    }
1476
1477    pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
1478    where
1479        T: View,
1480        F: FnOnce(&mut ViewContext<T>) -> T,
1481    {
1482        self.add_option_view(window_id, |cx| Some(build_view(cx)))
1483            .unwrap()
1484    }
1485
1486    pub fn add_option_view<T, F>(
1487        &mut self,
1488        window_id: usize,
1489        build_view: F,
1490    ) -> Option<ViewHandle<T>>
1491    where
1492        T: View,
1493        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1494    {
1495        self.update(|this| {
1496            let view_id = post_inc(&mut this.next_entity_id);
1497            let mut cx = ViewContext::new(this, window_id, view_id);
1498            let handle = if let Some(view) = build_view(&mut cx) {
1499                this.cx.views.insert((window_id, view_id), Box::new(view));
1500                if let Some(window) = this.cx.windows.get_mut(&window_id) {
1501                    window
1502                        .invalidation
1503                        .get_or_insert_with(Default::default)
1504                        .updated
1505                        .insert(view_id);
1506                }
1507                Some(ViewHandle::new(window_id, view_id, &this.cx.ref_counts))
1508            } else {
1509                None
1510            };
1511            handle
1512        })
1513    }
1514
1515    fn remove_dropped_entities(&mut self) {
1516        loop {
1517            let (dropped_models, dropped_views, dropped_element_states) =
1518                self.cx.ref_counts.lock().take_dropped();
1519            if dropped_models.is_empty()
1520                && dropped_views.is_empty()
1521                && dropped_element_states.is_empty()
1522            {
1523                break;
1524            }
1525
1526            for model_id in dropped_models {
1527                self.subscriptions.lock().remove(&model_id);
1528                self.observations.lock().remove(&model_id);
1529                let mut model = self.cx.models.remove(&model_id).unwrap();
1530                model.release(self);
1531                self.pending_effects.push_back(Effect::Release {
1532                    entity_id: model_id,
1533                });
1534            }
1535
1536            for (window_id, view_id) in dropped_views {
1537                self.subscriptions.lock().remove(&view_id);
1538                self.observations.lock().remove(&view_id);
1539                let mut view = self.cx.views.remove(&(window_id, view_id)).unwrap();
1540                view.release(self);
1541                let change_focus_to = self.cx.windows.get_mut(&window_id).and_then(|window| {
1542                    window
1543                        .invalidation
1544                        .get_or_insert_with(Default::default)
1545                        .removed
1546                        .push(view_id);
1547                    if window.focused_view_id == view_id {
1548                        Some(window.root_view.id())
1549                    } else {
1550                        None
1551                    }
1552                });
1553
1554                if let Some(view_id) = change_focus_to {
1555                    self.focus(window_id, view_id);
1556                }
1557
1558                self.pending_effects
1559                    .push_back(Effect::Release { entity_id: view_id });
1560            }
1561
1562            for key in dropped_element_states {
1563                self.cx.element_states.remove(&key);
1564            }
1565        }
1566    }
1567
1568    fn flush_effects(&mut self) {
1569        self.pending_flushes = self.pending_flushes.saturating_sub(1);
1570
1571        if !self.flushing_effects && self.pending_flushes == 0 {
1572            self.flushing_effects = true;
1573
1574            let mut refreshing = false;
1575            loop {
1576                if let Some(effect) = self.pending_effects.pop_front() {
1577                    match effect {
1578                        Effect::Event { entity_id, payload } => self.emit_event(entity_id, payload),
1579                        Effect::ModelNotification { model_id } => {
1580                            self.notify_model_observers(model_id)
1581                        }
1582                        Effect::ViewNotification { window_id, view_id } => {
1583                            self.notify_view_observers(window_id, view_id)
1584                        }
1585                        Effect::Deferred(callback) => callback(self),
1586                        Effect::Release { entity_id } => self.notify_release_observers(entity_id),
1587                        Effect::Focus { window_id, view_id } => {
1588                            self.focus(window_id, view_id);
1589                        }
1590                        Effect::ResizeWindow { window_id } => {
1591                            if let Some(window) = self.cx.windows.get_mut(&window_id) {
1592                                window
1593                                    .invalidation
1594                                    .get_or_insert(WindowInvalidation::default());
1595                            }
1596                        }
1597                        Effect::RefreshWindows => {
1598                            refreshing = true;
1599                        }
1600                    }
1601                    self.pending_notifications.clear();
1602                    self.remove_dropped_entities();
1603                } else {
1604                    self.remove_dropped_entities();
1605                    if refreshing {
1606                        self.perform_window_refresh();
1607                    } else {
1608                        self.update_windows();
1609                    }
1610
1611                    if self.pending_effects.is_empty() {
1612                        self.flushing_effects = false;
1613                        self.pending_notifications.clear();
1614                        break;
1615                    } else {
1616                        refreshing = false;
1617                    }
1618                }
1619            }
1620        }
1621    }
1622
1623    fn update_windows(&mut self) {
1624        let mut invalidations = HashMap::new();
1625        for (window_id, window) in &mut self.cx.windows {
1626            if let Some(invalidation) = window.invalidation.take() {
1627                invalidations.insert(*window_id, invalidation);
1628            }
1629        }
1630
1631        for (window_id, invalidation) in invalidations {
1632            if let Some((presenter, mut window)) =
1633                self.presenters_and_platform_windows.remove(&window_id)
1634            {
1635                {
1636                    let mut presenter = presenter.borrow_mut();
1637                    presenter.invalidate(invalidation, self);
1638                    let scene =
1639                        presenter.build_scene(window.size(), window.scale_factor(), false, self);
1640                    window.present_scene(scene);
1641                }
1642                self.presenters_and_platform_windows
1643                    .insert(window_id, (presenter, window));
1644            }
1645        }
1646    }
1647
1648    fn resize_window(&mut self, window_id: usize) {
1649        self.pending_effects
1650            .push_back(Effect::ResizeWindow { window_id });
1651    }
1652
1653    pub fn refresh_windows(&mut self) {
1654        self.pending_effects.push_back(Effect::RefreshWindows);
1655    }
1656
1657    fn perform_window_refresh(&mut self) {
1658        let mut presenters = mem::take(&mut self.presenters_and_platform_windows);
1659        for (window_id, (presenter, window)) in &mut presenters {
1660            let invalidation = self
1661                .cx
1662                .windows
1663                .get_mut(&window_id)
1664                .unwrap()
1665                .invalidation
1666                .take();
1667            let mut presenter = presenter.borrow_mut();
1668            presenter.refresh(invalidation, self);
1669            let scene = presenter.build_scene(window.size(), window.scale_factor(), true, self);
1670            window.present_scene(scene);
1671        }
1672        self.presenters_and_platform_windows = presenters;
1673    }
1674
1675    pub fn set_cursor_style(&mut self, style: CursorStyle) -> CursorStyleHandle {
1676        self.platform.set_cursor_style(style);
1677        let id = self.next_cursor_style_handle_id.fetch_add(1, SeqCst);
1678        CursorStyleHandle {
1679            id,
1680            next_cursor_style_handle_id: self.next_cursor_style_handle_id.clone(),
1681            platform: self.platform(),
1682        }
1683    }
1684
1685    fn emit_event(&mut self, entity_id: usize, payload: Box<dyn Any>) {
1686        let callbacks = self.subscriptions.lock().remove(&entity_id);
1687        if let Some(callbacks) = callbacks {
1688            for (id, mut callback) in callbacks {
1689                let alive = callback(payload.as_ref(), self);
1690                if alive {
1691                    self.subscriptions
1692                        .lock()
1693                        .entry(entity_id)
1694                        .or_default()
1695                        .insert(id, callback);
1696                }
1697            }
1698        }
1699    }
1700
1701    fn notify_model_observers(&mut self, observed_id: usize) {
1702        let callbacks = self.observations.lock().remove(&observed_id);
1703        if let Some(callbacks) = callbacks {
1704            if self.cx.models.contains_key(&observed_id) {
1705                for (id, mut callback) in callbacks {
1706                    let alive = callback(self);
1707                    if alive {
1708                        self.observations
1709                            .lock()
1710                            .entry(observed_id)
1711                            .or_default()
1712                            .insert(id, callback);
1713                    }
1714                }
1715            }
1716        }
1717    }
1718
1719    fn notify_view_observers(&mut self, observed_window_id: usize, observed_view_id: usize) {
1720        if let Some(window) = self.cx.windows.get_mut(&observed_window_id) {
1721            window
1722                .invalidation
1723                .get_or_insert_with(Default::default)
1724                .updated
1725                .insert(observed_view_id);
1726        }
1727
1728        let callbacks = self.observations.lock().remove(&observed_view_id);
1729        if let Some(callbacks) = callbacks {
1730            if self
1731                .cx
1732                .views
1733                .contains_key(&(observed_window_id, observed_view_id))
1734            {
1735                for (id, mut callback) in callbacks {
1736                    let alive = callback(self);
1737                    if alive {
1738                        self.observations
1739                            .lock()
1740                            .entry(observed_view_id)
1741                            .or_default()
1742                            .insert(id, callback);
1743                    }
1744                }
1745            }
1746        }
1747    }
1748
1749    fn notify_release_observers(&mut self, entity_id: usize) {
1750        let callbacks = self.release_observations.lock().remove(&entity_id);
1751        if let Some(callbacks) = callbacks {
1752            for (_, mut callback) in callbacks {
1753                callback(self);
1754            }
1755        }
1756    }
1757
1758    fn focus(&mut self, window_id: usize, focused_id: usize) {
1759        if self
1760            .cx
1761            .windows
1762            .get(&window_id)
1763            .map(|w| w.focused_view_id)
1764            .map_or(false, |cur_focused| cur_focused == focused_id)
1765        {
1766            return;
1767        }
1768
1769        self.update(|this| {
1770            let blurred_id = this.cx.windows.get_mut(&window_id).map(|window| {
1771                let blurred_id = window.focused_view_id;
1772                window.focused_view_id = focused_id;
1773                blurred_id
1774            });
1775
1776            if let Some(blurred_id) = blurred_id {
1777                if let Some(mut blurred_view) = this.cx.views.remove(&(window_id, blurred_id)) {
1778                    blurred_view.on_blur(this, window_id, blurred_id);
1779                    this.cx.views.insert((window_id, blurred_id), blurred_view);
1780                }
1781            }
1782
1783            if let Some(mut focused_view) = this.cx.views.remove(&(window_id, focused_id)) {
1784                focused_view.on_focus(this, window_id, focused_id);
1785                this.cx.views.insert((window_id, focused_id), focused_view);
1786            }
1787        })
1788    }
1789
1790    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
1791    where
1792        F: FnOnce(AsyncAppContext) -> Fut,
1793        Fut: 'static + Future<Output = T>,
1794        T: 'static,
1795    {
1796        let future = f(self.to_async());
1797        let cx = self.to_async();
1798        self.foreground.spawn(async move {
1799            let result = future.await;
1800            cx.0.borrow_mut().flush_effects();
1801            result
1802        })
1803    }
1804
1805    pub fn to_async(&self) -> AsyncAppContext {
1806        AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
1807    }
1808
1809    pub fn write_to_clipboard(&self, item: ClipboardItem) {
1810        self.cx.platform.write_to_clipboard(item);
1811    }
1812
1813    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1814        self.cx.platform.read_from_clipboard()
1815    }
1816
1817    #[cfg(any(test, feature = "test-support"))]
1818    pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
1819        self.cx.ref_counts.lock().leak_detector.clone()
1820    }
1821}
1822
1823impl ReadModel for MutableAppContext {
1824    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1825        if let Some(model) = self.cx.models.get(&handle.model_id) {
1826            model
1827                .as_any()
1828                .downcast_ref()
1829                .expect("downcast is type safe")
1830        } else {
1831            panic!("circular model reference");
1832        }
1833    }
1834}
1835
1836impl UpdateModel for MutableAppContext {
1837    fn update_model<T: Entity, V>(
1838        &mut self,
1839        handle: &ModelHandle<T>,
1840        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
1841    ) -> V {
1842        if let Some(mut model) = self.cx.models.remove(&handle.model_id) {
1843            self.update(|this| {
1844                let mut cx = ModelContext::new(this, handle.model_id);
1845                let result = update(
1846                    model
1847                        .as_any_mut()
1848                        .downcast_mut()
1849                        .expect("downcast is type safe"),
1850                    &mut cx,
1851                );
1852                this.cx.models.insert(handle.model_id, model);
1853                result
1854            })
1855        } else {
1856            panic!("circular model update");
1857        }
1858    }
1859}
1860
1861impl UpgradeModelHandle for MutableAppContext {
1862    fn upgrade_model_handle<T: Entity>(
1863        &self,
1864        handle: &WeakModelHandle<T>,
1865    ) -> Option<ModelHandle<T>> {
1866        self.cx.upgrade_model_handle(handle)
1867    }
1868
1869    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
1870        self.cx.model_handle_is_upgradable(handle)
1871    }
1872
1873    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
1874        self.cx.upgrade_any_model_handle(handle)
1875    }
1876}
1877
1878impl UpgradeViewHandle for MutableAppContext {
1879    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
1880        self.cx.upgrade_view_handle(handle)
1881    }
1882}
1883
1884impl ReadView for MutableAppContext {
1885    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1886        if let Some(view) = self.cx.views.get(&(handle.window_id, handle.view_id)) {
1887            view.as_any().downcast_ref().expect("downcast is type safe")
1888        } else {
1889            panic!("circular view reference");
1890        }
1891    }
1892}
1893
1894impl UpdateView for MutableAppContext {
1895    fn update_view<T, S>(
1896        &mut self,
1897        handle: &ViewHandle<T>,
1898        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
1899    ) -> S
1900    where
1901        T: View,
1902    {
1903        self.update(|this| {
1904            let mut view = this
1905                .cx
1906                .views
1907                .remove(&(handle.window_id, handle.view_id))
1908                .expect("circular view update");
1909
1910            let mut cx = ViewContext::new(this, handle.window_id, handle.view_id);
1911            let result = update(
1912                view.as_any_mut()
1913                    .downcast_mut()
1914                    .expect("downcast is type safe"),
1915                &mut cx,
1916            );
1917            this.cx
1918                .views
1919                .insert((handle.window_id, handle.view_id), view);
1920            result
1921        })
1922    }
1923}
1924
1925impl AsRef<AppContext> for MutableAppContext {
1926    fn as_ref(&self) -> &AppContext {
1927        &self.cx
1928    }
1929}
1930
1931impl Deref for MutableAppContext {
1932    type Target = AppContext;
1933
1934    fn deref(&self) -> &Self::Target {
1935        &self.cx
1936    }
1937}
1938
1939pub struct AppContext {
1940    models: HashMap<usize, Box<dyn AnyModel>>,
1941    views: HashMap<(usize, usize), Box<dyn AnyView>>,
1942    windows: HashMap<usize, Window>,
1943    app_states: HashMap<TypeId, Box<dyn Any>>,
1944    element_states: HashMap<ElementStateId, Box<dyn Any>>,
1945    background: Arc<executor::Background>,
1946    ref_counts: Arc<Mutex<RefCounts>>,
1947    font_cache: Arc<FontCache>,
1948    platform: Arc<dyn Platform>,
1949}
1950
1951impl AppContext {
1952    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
1953        self.windows
1954            .get(&window_id)
1955            .map(|window| window.root_view.id())
1956    }
1957
1958    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
1959        self.windows
1960            .get(&window_id)
1961            .map(|window| window.focused_view_id)
1962    }
1963
1964    pub fn background(&self) -> &Arc<executor::Background> {
1965        &self.background
1966    }
1967
1968    pub fn font_cache(&self) -> &Arc<FontCache> {
1969        &self.font_cache
1970    }
1971
1972    pub fn platform(&self) -> &Arc<dyn Platform> {
1973        &self.platform
1974    }
1975
1976    pub fn app_state<T: 'static>(&self) -> &T {
1977        self.app_states
1978            .get(&TypeId::of::<T>())
1979            .expect("no app state has been added for this type")
1980            .downcast_ref()
1981            .unwrap()
1982    }
1983}
1984
1985impl ReadModel for AppContext {
1986    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1987        if let Some(model) = self.models.get(&handle.model_id) {
1988            model
1989                .as_any()
1990                .downcast_ref()
1991                .expect("downcast should be type safe")
1992        } else {
1993            panic!("circular model reference");
1994        }
1995    }
1996}
1997
1998impl UpgradeModelHandle for AppContext {
1999    fn upgrade_model_handle<T: Entity>(
2000        &self,
2001        handle: &WeakModelHandle<T>,
2002    ) -> Option<ModelHandle<T>> {
2003        if self.models.contains_key(&handle.model_id) {
2004            Some(ModelHandle::new(handle.model_id, &self.ref_counts))
2005        } else {
2006            None
2007        }
2008    }
2009
2010    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2011        self.models.contains_key(&handle.model_id)
2012    }
2013
2014    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2015        if self.models.contains_key(&handle.model_id) {
2016            Some(AnyModelHandle::new(
2017                handle.model_id,
2018                handle.model_type,
2019                self.ref_counts.clone(),
2020            ))
2021        } else {
2022            None
2023        }
2024    }
2025}
2026
2027impl UpgradeViewHandle for AppContext {
2028    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2029        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2030            Some(ViewHandle::new(
2031                handle.window_id,
2032                handle.view_id,
2033                &self.ref_counts,
2034            ))
2035        } else {
2036            None
2037        }
2038    }
2039}
2040
2041impl ReadView for AppContext {
2042    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2043        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
2044            view.as_any()
2045                .downcast_ref()
2046                .expect("downcast should be type safe")
2047        } else {
2048            panic!("circular view reference");
2049        }
2050    }
2051}
2052
2053struct Window {
2054    root_view: AnyViewHandle,
2055    focused_view_id: usize,
2056    invalidation: Option<WindowInvalidation>,
2057}
2058
2059#[derive(Default, Clone)]
2060pub struct WindowInvalidation {
2061    pub updated: HashSet<usize>,
2062    pub removed: Vec<usize>,
2063}
2064
2065pub enum Effect {
2066    Event {
2067        entity_id: usize,
2068        payload: Box<dyn Any>,
2069    },
2070    ModelNotification {
2071        model_id: usize,
2072    },
2073    ViewNotification {
2074        window_id: usize,
2075        view_id: usize,
2076    },
2077    Deferred(Box<dyn FnOnce(&mut MutableAppContext)>),
2078    Release {
2079        entity_id: usize,
2080    },
2081    Focus {
2082        window_id: usize,
2083        view_id: usize,
2084    },
2085    ResizeWindow {
2086        window_id: usize,
2087    },
2088    RefreshWindows,
2089}
2090
2091impl Debug for Effect {
2092    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2093        match self {
2094            Effect::Event { entity_id, .. } => f
2095                .debug_struct("Effect::Event")
2096                .field("entity_id", entity_id)
2097                .finish(),
2098            Effect::ModelNotification { model_id } => f
2099                .debug_struct("Effect::ModelNotification")
2100                .field("model_id", model_id)
2101                .finish(),
2102            Effect::ViewNotification { window_id, view_id } => f
2103                .debug_struct("Effect::ViewNotification")
2104                .field("window_id", window_id)
2105                .field("view_id", view_id)
2106                .finish(),
2107            Effect::Deferred(_) => f.debug_struct("Effect::Deferred").finish(),
2108            Effect::Release { entity_id } => f
2109                .debug_struct("Effect::Release")
2110                .field("entity_id", entity_id)
2111                .finish(),
2112            Effect::Focus { window_id, view_id } => f
2113                .debug_struct("Effect::Focus")
2114                .field("window_id", window_id)
2115                .field("view_id", view_id)
2116                .finish(),
2117            Effect::ResizeWindow { window_id } => f
2118                .debug_struct("Effect::RefreshWindow")
2119                .field("window_id", window_id)
2120                .finish(),
2121            Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
2122        }
2123    }
2124}
2125
2126pub trait AnyModel {
2127    fn as_any(&self) -> &dyn Any;
2128    fn as_any_mut(&mut self) -> &mut dyn Any;
2129    fn release(&mut self, cx: &mut MutableAppContext);
2130    fn app_will_quit(
2131        &mut self,
2132        cx: &mut MutableAppContext,
2133    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2134}
2135
2136impl<T> AnyModel for T
2137where
2138    T: Entity,
2139{
2140    fn as_any(&self) -> &dyn Any {
2141        self
2142    }
2143
2144    fn as_any_mut(&mut self) -> &mut dyn Any {
2145        self
2146    }
2147
2148    fn release(&mut self, cx: &mut MutableAppContext) {
2149        self.release(cx);
2150    }
2151
2152    fn app_will_quit(
2153        &mut self,
2154        cx: &mut MutableAppContext,
2155    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2156        self.app_will_quit(cx)
2157    }
2158}
2159
2160pub trait AnyView {
2161    fn as_any(&self) -> &dyn Any;
2162    fn as_any_mut(&mut self) -> &mut dyn Any;
2163    fn release(&mut self, cx: &mut MutableAppContext);
2164    fn app_will_quit(
2165        &mut self,
2166        cx: &mut MutableAppContext,
2167    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2168    fn ui_name(&self) -> &'static str;
2169    fn render<'a>(
2170        &mut self,
2171        window_id: usize,
2172        view_id: usize,
2173        titlebar_height: f32,
2174        refreshing: bool,
2175        cx: &mut MutableAppContext,
2176    ) -> ElementBox;
2177    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
2178    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
2179    fn keymap_context(&self, cx: &AppContext) -> keymap::Context;
2180}
2181
2182impl<T> AnyView for T
2183where
2184    T: View,
2185{
2186    fn as_any(&self) -> &dyn Any {
2187        self
2188    }
2189
2190    fn as_any_mut(&mut self) -> &mut dyn Any {
2191        self
2192    }
2193
2194    fn release(&mut self, cx: &mut MutableAppContext) {
2195        self.release(cx);
2196    }
2197
2198    fn app_will_quit(
2199        &mut self,
2200        cx: &mut MutableAppContext,
2201    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2202        self.app_will_quit(cx)
2203    }
2204
2205    fn ui_name(&self) -> &'static str {
2206        T::ui_name()
2207    }
2208
2209    fn render<'a>(
2210        &mut self,
2211        window_id: usize,
2212        view_id: usize,
2213        titlebar_height: f32,
2214        refreshing: bool,
2215        cx: &mut MutableAppContext,
2216    ) -> ElementBox {
2217        View::render(
2218            self,
2219            &mut RenderContext {
2220                window_id,
2221                view_id,
2222                app: cx,
2223                view_type: PhantomData::<T>,
2224                titlebar_height,
2225                refreshing,
2226            },
2227        )
2228    }
2229
2230    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
2231        let mut cx = ViewContext::new(cx, window_id, view_id);
2232        View::on_focus(self, &mut cx);
2233    }
2234
2235    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
2236        let mut cx = ViewContext::new(cx, window_id, view_id);
2237        View::on_blur(self, &mut cx);
2238    }
2239
2240    fn keymap_context(&self, cx: &AppContext) -> keymap::Context {
2241        View::keymap_context(self, cx)
2242    }
2243}
2244
2245pub struct ModelContext<'a, T: ?Sized> {
2246    app: &'a mut MutableAppContext,
2247    model_id: usize,
2248    model_type: PhantomData<T>,
2249    halt_stream: bool,
2250}
2251
2252impl<'a, T: Entity> ModelContext<'a, T> {
2253    fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
2254        Self {
2255            app,
2256            model_id,
2257            model_type: PhantomData,
2258            halt_stream: false,
2259        }
2260    }
2261
2262    pub fn background(&self) -> &Arc<executor::Background> {
2263        &self.app.cx.background
2264    }
2265
2266    pub fn halt_stream(&mut self) {
2267        self.halt_stream = true;
2268    }
2269
2270    pub fn model_id(&self) -> usize {
2271        self.model_id
2272    }
2273
2274    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2275    where
2276        S: Entity,
2277        F: FnOnce(&mut ModelContext<S>) -> S,
2278    {
2279        self.app.add_model(build_model)
2280    }
2281
2282    pub fn emit(&mut self, payload: T::Event) {
2283        self.app.pending_effects.push_back(Effect::Event {
2284            entity_id: self.model_id,
2285            payload: Box::new(payload),
2286        });
2287    }
2288
2289    pub fn notify(&mut self) {
2290        self.app.notify_model(self.model_id);
2291    }
2292
2293    pub fn subscribe<S: Entity, F>(
2294        &mut self,
2295        handle: &ModelHandle<S>,
2296        mut callback: F,
2297    ) -> Subscription
2298    where
2299        S::Event: 'static,
2300        F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
2301    {
2302        let subscriber = self.weak_handle();
2303        self.app
2304            .subscribe_internal(handle, move |emitter, event, cx| {
2305                if let Some(subscriber) = subscriber.upgrade(cx) {
2306                    subscriber.update(cx, |subscriber, cx| {
2307                        callback(subscriber, emitter, event, cx);
2308                    });
2309                    true
2310                } else {
2311                    false
2312                }
2313            })
2314    }
2315
2316    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
2317    where
2318        S: Entity,
2319        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
2320    {
2321        let observer = self.weak_handle();
2322        self.app.observe_internal(handle, move |observed, cx| {
2323            if let Some(observer) = observer.upgrade(cx) {
2324                observer.update(cx, |observer, cx| {
2325                    callback(observer, observed, cx);
2326                });
2327                true
2328            } else {
2329                false
2330            }
2331        })
2332    }
2333
2334    pub fn observe_release<S, F>(
2335        &mut self,
2336        handle: &ModelHandle<S>,
2337        mut callback: F,
2338    ) -> Subscription
2339    where
2340        S: Entity,
2341        F: 'static + FnMut(&mut T, &mut ModelContext<T>),
2342    {
2343        let observer = self.weak_handle();
2344        self.app.observe_release(handle, move |cx| {
2345            if let Some(observer) = observer.upgrade(cx) {
2346                observer.update(cx, |observer, cx| {
2347                    callback(observer, cx);
2348                });
2349            }
2350        })
2351    }
2352
2353    pub fn handle(&self) -> ModelHandle<T> {
2354        ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
2355    }
2356
2357    pub fn weak_handle(&self) -> WeakModelHandle<T> {
2358        WeakModelHandle::new(self.model_id)
2359    }
2360
2361    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2362    where
2363        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
2364        Fut: 'static + Future<Output = S>,
2365        S: 'static,
2366    {
2367        let handle = self.handle();
2368        self.app.spawn(|cx| f(handle, cx))
2369    }
2370
2371    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
2372    where
2373        F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
2374        Fut: 'static + Future<Output = S>,
2375        S: 'static,
2376    {
2377        let handle = self.weak_handle();
2378        self.app.spawn(|cx| f(handle, cx))
2379    }
2380}
2381
2382impl<M> AsRef<AppContext> for ModelContext<'_, M> {
2383    fn as_ref(&self) -> &AppContext {
2384        &self.app.cx
2385    }
2386}
2387
2388impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
2389    fn as_mut(&mut self) -> &mut MutableAppContext {
2390        self.app
2391    }
2392}
2393
2394impl<M> ReadModel for ModelContext<'_, M> {
2395    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2396        self.app.read_model(handle)
2397    }
2398}
2399
2400impl<M> UpdateModel for ModelContext<'_, M> {
2401    fn update_model<T: Entity, V>(
2402        &mut self,
2403        handle: &ModelHandle<T>,
2404        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
2405    ) -> V {
2406        self.app.update_model(handle, update)
2407    }
2408}
2409
2410impl<M> UpgradeModelHandle for ModelContext<'_, M> {
2411    fn upgrade_model_handle<T: Entity>(
2412        &self,
2413        handle: &WeakModelHandle<T>,
2414    ) -> Option<ModelHandle<T>> {
2415        self.cx.upgrade_model_handle(handle)
2416    }
2417
2418    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2419        self.cx.model_handle_is_upgradable(handle)
2420    }
2421
2422    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2423        self.cx.upgrade_any_model_handle(handle)
2424    }
2425}
2426
2427impl<M> Deref for ModelContext<'_, M> {
2428    type Target = MutableAppContext;
2429
2430    fn deref(&self) -> &Self::Target {
2431        &self.app
2432    }
2433}
2434
2435impl<M> DerefMut for ModelContext<'_, M> {
2436    fn deref_mut(&mut self) -> &mut Self::Target {
2437        &mut self.app
2438    }
2439}
2440
2441pub struct ViewContext<'a, T: ?Sized> {
2442    app: &'a mut MutableAppContext,
2443    window_id: usize,
2444    view_id: usize,
2445    view_type: PhantomData<T>,
2446}
2447
2448impl<'a, T: View> ViewContext<'a, T> {
2449    fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
2450        Self {
2451            app,
2452            window_id,
2453            view_id,
2454            view_type: PhantomData,
2455        }
2456    }
2457
2458    pub fn handle(&self) -> ViewHandle<T> {
2459        ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
2460    }
2461
2462    pub fn weak_handle(&self) -> WeakViewHandle<T> {
2463        WeakViewHandle::new(self.window_id, self.view_id)
2464    }
2465
2466    pub fn window_id(&self) -> usize {
2467        self.window_id
2468    }
2469
2470    pub fn view_id(&self) -> usize {
2471        self.view_id
2472    }
2473
2474    pub fn foreground(&self) -> &Rc<executor::Foreground> {
2475        self.app.foreground()
2476    }
2477
2478    pub fn background_executor(&self) -> &Arc<executor::Background> {
2479        &self.app.cx.background
2480    }
2481
2482    pub fn platform(&self) -> Arc<dyn Platform> {
2483        self.app.platform()
2484    }
2485
2486    pub fn prompt(
2487        &self,
2488        level: PromptLevel,
2489        msg: &str,
2490        answers: &[&str],
2491    ) -> oneshot::Receiver<usize> {
2492        self.app.prompt(self.window_id, level, msg, answers)
2493    }
2494
2495    pub fn prompt_for_paths(
2496        &self,
2497        options: PathPromptOptions,
2498    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2499        self.app.prompt_for_paths(options)
2500    }
2501
2502    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
2503        self.app.prompt_for_new_path(directory)
2504    }
2505
2506    pub fn debug_elements(&self) -> crate::json::Value {
2507        self.app.debug_elements(self.window_id).unwrap()
2508    }
2509
2510    pub fn focus<S>(&mut self, handle: S)
2511    where
2512        S: Into<AnyViewHandle>,
2513    {
2514        let handle = handle.into();
2515        self.app.pending_effects.push_back(Effect::Focus {
2516            window_id: handle.window_id,
2517            view_id: handle.view_id,
2518        });
2519    }
2520
2521    pub fn focus_self(&mut self) {
2522        self.app.pending_effects.push_back(Effect::Focus {
2523            window_id: self.window_id,
2524            view_id: self.view_id,
2525        });
2526    }
2527
2528    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2529    where
2530        S: Entity,
2531        F: FnOnce(&mut ModelContext<S>) -> S,
2532    {
2533        self.app.add_model(build_model)
2534    }
2535
2536    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
2537    where
2538        S: View,
2539        F: FnOnce(&mut ViewContext<S>) -> S,
2540    {
2541        self.app.add_view(self.window_id, build_view)
2542    }
2543
2544    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
2545    where
2546        S: View,
2547        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
2548    {
2549        self.app.add_option_view(self.window_id, build_view)
2550    }
2551
2552    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
2553    where
2554        E: Entity,
2555        E::Event: 'static,
2556        H: Handle<E>,
2557        F: 'static + FnMut(&mut T, H, &E::Event, &mut ViewContext<T>),
2558    {
2559        let subscriber = self.weak_handle();
2560        self.app
2561            .subscribe_internal(handle, move |emitter, event, cx| {
2562                if let Some(subscriber) = subscriber.upgrade(cx) {
2563                    subscriber.update(cx, |subscriber, cx| {
2564                        callback(subscriber, emitter, event, cx);
2565                    });
2566                    true
2567                } else {
2568                    false
2569                }
2570            })
2571    }
2572
2573    pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2574    where
2575        E: Entity,
2576        H: Handle<E>,
2577        F: 'static + FnMut(&mut T, H, &mut ViewContext<T>),
2578    {
2579        let observer = self.weak_handle();
2580        self.app.observe_internal(handle, move |observed, cx| {
2581            if let Some(observer) = observer.upgrade(cx) {
2582                observer.update(cx, |observer, cx| {
2583                    callback(observer, observed, cx);
2584                });
2585                true
2586            } else {
2587                false
2588            }
2589        })
2590    }
2591
2592    pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2593    where
2594        E: Entity,
2595        H: Handle<E>,
2596        F: 'static + FnMut(&mut T, &mut ViewContext<T>),
2597    {
2598        let observer = self.weak_handle();
2599        self.app.observe_release(handle, move |cx| {
2600            if let Some(observer) = observer.upgrade(cx) {
2601                observer.update(cx, |observer, cx| {
2602                    callback(observer, cx);
2603                });
2604            }
2605        })
2606    }
2607
2608    pub fn emit(&mut self, payload: T::Event) {
2609        self.app.pending_effects.push_back(Effect::Event {
2610            entity_id: self.view_id,
2611            payload: Box::new(payload),
2612        });
2613    }
2614
2615    pub fn notify(&mut self) {
2616        self.app.notify_view(self.window_id, self.view_id);
2617    }
2618
2619    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>)) {
2620        let handle = self.handle();
2621        self.app.defer(Box::new(move |cx| {
2622            handle.update(cx, |view, cx| {
2623                callback(view, cx);
2624            })
2625        }))
2626    }
2627
2628    pub fn propagate_action(&mut self) {
2629        self.app.halt_action_dispatch = false;
2630    }
2631
2632    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2633    where
2634        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
2635        Fut: 'static + Future<Output = S>,
2636        S: 'static,
2637    {
2638        let handle = self.handle();
2639        self.app.spawn(|cx| f(handle, cx))
2640    }
2641
2642    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
2643    where
2644        F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut,
2645        Fut: 'static + Future<Output = S>,
2646        S: 'static,
2647    {
2648        let handle = self.weak_handle();
2649        self.app.spawn(|cx| f(handle, cx))
2650    }
2651}
2652
2653pub struct RenderContext<'a, T: View> {
2654    pub app: &'a mut MutableAppContext,
2655    pub titlebar_height: f32,
2656    pub refreshing: bool,
2657    window_id: usize,
2658    view_id: usize,
2659    view_type: PhantomData<T>,
2660}
2661
2662impl<'a, T: View> RenderContext<'a, T> {
2663    pub fn handle(&self) -> WeakViewHandle<T> {
2664        WeakViewHandle::new(self.window_id, self.view_id)
2665    }
2666
2667    pub fn view_id(&self) -> usize {
2668        self.view_id
2669    }
2670}
2671
2672impl AsRef<AppContext> for &AppContext {
2673    fn as_ref(&self) -> &AppContext {
2674        self
2675    }
2676}
2677
2678impl<V: View> Deref for RenderContext<'_, V> {
2679    type Target = MutableAppContext;
2680
2681    fn deref(&self) -> &Self::Target {
2682        self.app
2683    }
2684}
2685
2686impl<V: View> DerefMut for RenderContext<'_, V> {
2687    fn deref_mut(&mut self) -> &mut Self::Target {
2688        self.app
2689    }
2690}
2691
2692impl<V: View> ReadModel for RenderContext<'_, V> {
2693    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2694        self.app.read_model(handle)
2695    }
2696}
2697
2698impl<V: View> UpdateModel for RenderContext<'_, V> {
2699    fn update_model<T: Entity, O>(
2700        &mut self,
2701        handle: &ModelHandle<T>,
2702        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
2703    ) -> O {
2704        self.app.update_model(handle, update)
2705    }
2706}
2707
2708impl<V: View> ReadView for RenderContext<'_, V> {
2709    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2710        self.app.read_view(handle)
2711    }
2712}
2713
2714impl<V: View> ElementStateContext for RenderContext<'_, V> {
2715    fn current_view_id(&self) -> usize {
2716        self.view_id
2717    }
2718}
2719
2720impl<M> AsRef<AppContext> for ViewContext<'_, M> {
2721    fn as_ref(&self) -> &AppContext {
2722        &self.app.cx
2723    }
2724}
2725
2726impl<M> Deref for ViewContext<'_, M> {
2727    type Target = MutableAppContext;
2728
2729    fn deref(&self) -> &Self::Target {
2730        &self.app
2731    }
2732}
2733
2734impl<M> DerefMut for ViewContext<'_, M> {
2735    fn deref_mut(&mut self) -> &mut Self::Target {
2736        &mut self.app
2737    }
2738}
2739
2740impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
2741    fn as_mut(&mut self) -> &mut MutableAppContext {
2742        self.app
2743    }
2744}
2745
2746impl<V> ReadModel for ViewContext<'_, V> {
2747    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2748        self.app.read_model(handle)
2749    }
2750}
2751
2752impl<V> UpgradeModelHandle for ViewContext<'_, V> {
2753    fn upgrade_model_handle<T: Entity>(
2754        &self,
2755        handle: &WeakModelHandle<T>,
2756    ) -> Option<ModelHandle<T>> {
2757        self.cx.upgrade_model_handle(handle)
2758    }
2759
2760    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2761        self.cx.model_handle_is_upgradable(handle)
2762    }
2763
2764    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2765        self.cx.upgrade_any_model_handle(handle)
2766    }
2767}
2768
2769impl<V> UpgradeViewHandle for ViewContext<'_, V> {
2770    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2771        self.cx.upgrade_view_handle(handle)
2772    }
2773}
2774
2775impl<V: View> UpdateModel for ViewContext<'_, V> {
2776    fn update_model<T: Entity, O>(
2777        &mut self,
2778        handle: &ModelHandle<T>,
2779        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
2780    ) -> O {
2781        self.app.update_model(handle, update)
2782    }
2783}
2784
2785impl<V: View> ReadView for ViewContext<'_, V> {
2786    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2787        self.app.read_view(handle)
2788    }
2789}
2790
2791impl<V: View> UpdateView for ViewContext<'_, V> {
2792    fn update_view<T, S>(
2793        &mut self,
2794        handle: &ViewHandle<T>,
2795        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
2796    ) -> S
2797    where
2798        T: View,
2799    {
2800        self.app.update_view(handle, update)
2801    }
2802}
2803
2804impl<V: View> ElementStateContext for ViewContext<'_, V> {
2805    fn current_view_id(&self) -> usize {
2806        self.view_id
2807    }
2808}
2809
2810pub trait Handle<T> {
2811    type Weak: 'static;
2812    fn id(&self) -> usize;
2813    fn location(&self) -> EntityLocation;
2814    fn downgrade(&self) -> Self::Weak;
2815    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2816    where
2817        Self: Sized;
2818}
2819
2820#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
2821pub enum EntityLocation {
2822    Model(usize),
2823    View(usize, usize),
2824}
2825
2826pub struct ModelHandle<T: Entity> {
2827    model_id: usize,
2828    model_type: PhantomData<T>,
2829    ref_counts: Arc<Mutex<RefCounts>>,
2830
2831    #[cfg(any(test, feature = "test-support"))]
2832    handle_id: usize,
2833}
2834
2835impl<T: Entity> ModelHandle<T> {
2836    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2837        ref_counts.lock().inc_model(model_id);
2838
2839        #[cfg(any(test, feature = "test-support"))]
2840        let handle_id = ref_counts
2841            .lock()
2842            .leak_detector
2843            .lock()
2844            .handle_created(Some(type_name::<T>()), model_id);
2845
2846        Self {
2847            model_id,
2848            model_type: PhantomData,
2849            ref_counts: ref_counts.clone(),
2850
2851            #[cfg(any(test, feature = "test-support"))]
2852            handle_id,
2853        }
2854    }
2855
2856    pub fn downgrade(&self) -> WeakModelHandle<T> {
2857        WeakModelHandle::new(self.model_id)
2858    }
2859
2860    pub fn id(&self) -> usize {
2861        self.model_id
2862    }
2863
2864    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
2865        cx.read_model(self)
2866    }
2867
2868    pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
2869    where
2870        C: ReadModelWith,
2871        F: FnOnce(&T, &AppContext) -> S,
2872    {
2873        let mut read = Some(read);
2874        cx.read_model_with(self, &mut |model, cx| {
2875            let read = read.take().unwrap();
2876            read(model, cx)
2877        })
2878    }
2879
2880    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2881    where
2882        C: UpdateModel,
2883        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2884    {
2885        let mut update = Some(update);
2886        cx.update_model(self, &mut |model, cx| {
2887            let update = update.take().unwrap();
2888            update(model, cx)
2889        })
2890    }
2891
2892    #[cfg(any(test, feature = "test-support"))]
2893    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
2894        use postage::prelude::{Sink as _, Stream as _};
2895
2896        let (mut tx, mut rx) = postage::mpsc::channel(1);
2897        let mut cx = cx.cx.borrow_mut();
2898        let subscription = cx.observe(self, move |_, _| {
2899            tx.try_send(()).ok();
2900        });
2901
2902        let duration = if std::env::var("CI").is_ok() {
2903            Duration::from_secs(5)
2904        } else {
2905            Duration::from_secs(1)
2906        };
2907
2908        async move {
2909            let notification = crate::util::timeout(duration, rx.recv())
2910                .await
2911                .expect("next notification timed out");
2912            drop(subscription);
2913            notification.expect("model dropped while test was waiting for its next notification")
2914        }
2915    }
2916
2917    #[cfg(any(test, feature = "test-support"))]
2918    pub fn next_event(&self, cx: &TestAppContext) -> impl Future<Output = T::Event>
2919    where
2920        T::Event: Clone,
2921    {
2922        use postage::prelude::{Sink as _, Stream as _};
2923
2924        let (mut tx, mut rx) = postage::mpsc::channel(1);
2925        let mut cx = cx.cx.borrow_mut();
2926        let subscription = cx.subscribe(self, move |_, event, _| {
2927            tx.blocking_send(event.clone()).ok();
2928        });
2929
2930        let duration = if std::env::var("CI").is_ok() {
2931            Duration::from_secs(5)
2932        } else {
2933            Duration::from_secs(1)
2934        };
2935
2936        async move {
2937            let event = crate::util::timeout(duration, rx.recv())
2938                .await
2939                .expect("next event timed out");
2940            drop(subscription);
2941            event.expect("model dropped while test was waiting for its next event")
2942        }
2943    }
2944
2945    #[cfg(any(test, feature = "test-support"))]
2946    pub fn condition(
2947        &self,
2948        cx: &TestAppContext,
2949        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2950    ) -> impl Future<Output = ()> {
2951        use postage::prelude::{Sink as _, Stream as _};
2952
2953        let (tx, mut rx) = postage::mpsc::channel(1024);
2954
2955        let mut cx = cx.cx.borrow_mut();
2956        let subscriptions = (
2957            cx.observe(self, {
2958                let mut tx = tx.clone();
2959                move |_, _| {
2960                    tx.blocking_send(()).ok();
2961                }
2962            }),
2963            cx.subscribe(self, {
2964                let mut tx = tx.clone();
2965                move |_, _, _| {
2966                    tx.blocking_send(()).ok();
2967                }
2968            }),
2969        );
2970
2971        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2972        let handle = self.downgrade();
2973        let duration = if std::env::var("CI").is_ok() {
2974            Duration::from_secs(5)
2975        } else {
2976            Duration::from_secs(1)
2977        };
2978
2979        async move {
2980            crate::util::timeout(duration, async move {
2981                loop {
2982                    {
2983                        let cx = cx.borrow();
2984                        let cx = cx.as_ref();
2985                        if predicate(
2986                            handle
2987                                .upgrade(cx)
2988                                .expect("model dropped with pending condition")
2989                                .read(cx),
2990                            cx,
2991                        ) {
2992                            break;
2993                        }
2994                    }
2995
2996                    cx.borrow().foreground().start_waiting();
2997                    rx.recv()
2998                        .await
2999                        .expect("model dropped with pending condition");
3000                    cx.borrow().foreground().finish_waiting();
3001                }
3002            })
3003            .await
3004            .expect("condition timed out");
3005            drop(subscriptions);
3006        }
3007    }
3008}
3009
3010impl<T: Entity> Clone for ModelHandle<T> {
3011    fn clone(&self) -> Self {
3012        Self::new(self.model_id, &self.ref_counts)
3013    }
3014}
3015
3016impl<T: Entity> PartialEq for ModelHandle<T> {
3017    fn eq(&self, other: &Self) -> bool {
3018        self.model_id == other.model_id
3019    }
3020}
3021
3022impl<T: Entity> Eq for ModelHandle<T> {}
3023
3024impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
3025    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
3026        self.model_id == other.model_id
3027    }
3028}
3029
3030impl<T: Entity> Hash for ModelHandle<T> {
3031    fn hash<H: Hasher>(&self, state: &mut H) {
3032        self.model_id.hash(state);
3033    }
3034}
3035
3036impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
3037    fn borrow(&self) -> &usize {
3038        &self.model_id
3039    }
3040}
3041
3042impl<T: Entity> Debug for ModelHandle<T> {
3043    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3044        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
3045            .field(&self.model_id)
3046            .finish()
3047    }
3048}
3049
3050unsafe impl<T: Entity> Send for ModelHandle<T> {}
3051unsafe impl<T: Entity> Sync for ModelHandle<T> {}
3052
3053impl<T: Entity> Drop for ModelHandle<T> {
3054    fn drop(&mut self) {
3055        let mut ref_counts = self.ref_counts.lock();
3056        ref_counts.dec_model(self.model_id);
3057
3058        #[cfg(any(test, feature = "test-support"))]
3059        ref_counts
3060            .leak_detector
3061            .lock()
3062            .handle_dropped(self.model_id, self.handle_id);
3063    }
3064}
3065
3066impl<T: Entity> Handle<T> for ModelHandle<T> {
3067    type Weak = WeakModelHandle<T>;
3068
3069    fn id(&self) -> usize {
3070        self.model_id
3071    }
3072
3073    fn location(&self) -> EntityLocation {
3074        EntityLocation::Model(self.model_id)
3075    }
3076
3077    fn downgrade(&self) -> Self::Weak {
3078        self.downgrade()
3079    }
3080
3081    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3082    where
3083        Self: Sized,
3084    {
3085        weak.upgrade(cx)
3086    }
3087}
3088
3089pub struct WeakModelHandle<T> {
3090    model_id: usize,
3091    model_type: PhantomData<T>,
3092}
3093
3094unsafe impl<T> Send for WeakModelHandle<T> {}
3095unsafe impl<T> Sync for WeakModelHandle<T> {}
3096
3097impl<T: Entity> WeakModelHandle<T> {
3098    fn new(model_id: usize) -> Self {
3099        Self {
3100            model_id,
3101            model_type: PhantomData,
3102        }
3103    }
3104
3105    pub fn id(&self) -> usize {
3106        self.model_id
3107    }
3108
3109    pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
3110        cx.model_handle_is_upgradable(self)
3111    }
3112
3113    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
3114        cx.upgrade_model_handle(self)
3115    }
3116}
3117
3118impl<T> Hash for WeakModelHandle<T> {
3119    fn hash<H: Hasher>(&self, state: &mut H) {
3120        self.model_id.hash(state)
3121    }
3122}
3123
3124impl<T> PartialEq for WeakModelHandle<T> {
3125    fn eq(&self, other: &Self) -> bool {
3126        self.model_id == other.model_id
3127    }
3128}
3129
3130impl<T> Eq for WeakModelHandle<T> {}
3131
3132impl<T> Clone for WeakModelHandle<T> {
3133    fn clone(&self) -> Self {
3134        Self {
3135            model_id: self.model_id,
3136            model_type: PhantomData,
3137        }
3138    }
3139}
3140
3141impl<T> Copy for WeakModelHandle<T> {}
3142
3143pub struct ViewHandle<T> {
3144    window_id: usize,
3145    view_id: usize,
3146    view_type: PhantomData<T>,
3147    ref_counts: Arc<Mutex<RefCounts>>,
3148    #[cfg(any(test, feature = "test-support"))]
3149    handle_id: usize,
3150}
3151
3152impl<T: View> ViewHandle<T> {
3153    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3154        ref_counts.lock().inc_view(window_id, view_id);
3155        #[cfg(any(test, feature = "test-support"))]
3156        let handle_id = ref_counts
3157            .lock()
3158            .leak_detector
3159            .lock()
3160            .handle_created(Some(type_name::<T>()), view_id);
3161
3162        Self {
3163            window_id,
3164            view_id,
3165            view_type: PhantomData,
3166            ref_counts: ref_counts.clone(),
3167
3168            #[cfg(any(test, feature = "test-support"))]
3169            handle_id,
3170        }
3171    }
3172
3173    pub fn downgrade(&self) -> WeakViewHandle<T> {
3174        WeakViewHandle::new(self.window_id, self.view_id)
3175    }
3176
3177    pub fn window_id(&self) -> usize {
3178        self.window_id
3179    }
3180
3181    pub fn id(&self) -> usize {
3182        self.view_id
3183    }
3184
3185    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
3186        cx.read_view(self)
3187    }
3188
3189    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3190    where
3191        C: ReadViewWith,
3192        F: FnOnce(&T, &AppContext) -> S,
3193    {
3194        let mut read = Some(read);
3195        cx.read_view_with(self, &mut |view, cx| {
3196            let read = read.take().unwrap();
3197            read(view, cx)
3198        })
3199    }
3200
3201    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3202    where
3203        C: UpdateView,
3204        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
3205    {
3206        let mut update = Some(update);
3207        cx.update_view(self, &mut |view, cx| {
3208            let update = update.take().unwrap();
3209            update(view, cx)
3210        })
3211    }
3212
3213    pub fn defer<C, F>(&self, cx: &mut C, update: F)
3214    where
3215        C: AsMut<MutableAppContext>,
3216        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
3217    {
3218        let this = self.clone();
3219        cx.as_mut().defer(Box::new(move |cx| {
3220            this.update(cx, |view, cx| update(view, cx));
3221        }));
3222    }
3223
3224    pub fn is_focused(&self, cx: &AppContext) -> bool {
3225        cx.focused_view_id(self.window_id)
3226            .map_or(false, |focused_id| focused_id == self.view_id)
3227    }
3228
3229    #[cfg(any(test, feature = "test-support"))]
3230    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
3231        use postage::prelude::{Sink as _, Stream as _};
3232
3233        let (mut tx, mut rx) = postage::mpsc::channel(1);
3234        let mut cx = cx.cx.borrow_mut();
3235        let subscription = cx.observe(self, move |_, _| {
3236            tx.try_send(()).ok();
3237        });
3238
3239        let duration = if std::env::var("CI").is_ok() {
3240            Duration::from_secs(5)
3241        } else {
3242            Duration::from_secs(1)
3243        };
3244
3245        async move {
3246            let notification = crate::util::timeout(duration, rx.recv())
3247                .await
3248                .expect("next notification timed out");
3249            drop(subscription);
3250            notification.expect("model dropped while test was waiting for its next notification")
3251        }
3252    }
3253
3254    #[cfg(any(test, feature = "test-support"))]
3255    pub fn condition(
3256        &self,
3257        cx: &TestAppContext,
3258        mut predicate: impl FnMut(&T, &AppContext) -> bool,
3259    ) -> impl Future<Output = ()> {
3260        use postage::prelude::{Sink as _, Stream as _};
3261
3262        let (tx, mut rx) = postage::mpsc::channel(1024);
3263
3264        let mut cx = cx.cx.borrow_mut();
3265        let subscriptions = self.update(&mut *cx, |_, cx| {
3266            (
3267                cx.observe(self, {
3268                    let mut tx = tx.clone();
3269                    move |_, _, _| {
3270                        tx.blocking_send(()).ok();
3271                    }
3272                }),
3273                cx.subscribe(self, {
3274                    let mut tx = tx.clone();
3275                    move |_, _, _, _| {
3276                        tx.blocking_send(()).ok();
3277                    }
3278                }),
3279            )
3280        });
3281
3282        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
3283        let handle = self.downgrade();
3284        let duration = if std::env::var("CI").is_ok() {
3285            Duration::from_secs(2)
3286        } else {
3287            Duration::from_millis(500)
3288        };
3289
3290        async move {
3291            crate::util::timeout(duration, async move {
3292                loop {
3293                    {
3294                        let cx = cx.borrow();
3295                        let cx = cx.as_ref();
3296                        if predicate(
3297                            handle
3298                                .upgrade(cx)
3299                                .expect("view dropped with pending condition")
3300                                .read(cx),
3301                            cx,
3302                        ) {
3303                            break;
3304                        }
3305                    }
3306
3307                    cx.borrow().foreground().start_waiting();
3308                    rx.recv()
3309                        .await
3310                        .expect("view dropped with pending condition");
3311                    cx.borrow().foreground().finish_waiting();
3312                }
3313            })
3314            .await
3315            .expect("condition timed out");
3316            drop(subscriptions);
3317        }
3318    }
3319}
3320
3321impl<T: View> Clone for ViewHandle<T> {
3322    fn clone(&self) -> Self {
3323        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
3324    }
3325}
3326
3327impl<T> PartialEq for ViewHandle<T> {
3328    fn eq(&self, other: &Self) -> bool {
3329        self.window_id == other.window_id && self.view_id == other.view_id
3330    }
3331}
3332
3333impl<T> Eq for ViewHandle<T> {}
3334
3335impl<T> Debug for ViewHandle<T> {
3336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3337        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
3338            .field("window_id", &self.window_id)
3339            .field("view_id", &self.view_id)
3340            .finish()
3341    }
3342}
3343
3344impl<T> Drop for ViewHandle<T> {
3345    fn drop(&mut self) {
3346        self.ref_counts
3347            .lock()
3348            .dec_view(self.window_id, self.view_id);
3349        #[cfg(any(test, feature = "test-support"))]
3350        self.ref_counts
3351            .lock()
3352            .leak_detector
3353            .lock()
3354            .handle_dropped(self.view_id, self.handle_id);
3355    }
3356}
3357
3358impl<T: View> Handle<T> for ViewHandle<T> {
3359    type Weak = WeakViewHandle<T>;
3360
3361    fn id(&self) -> usize {
3362        self.view_id
3363    }
3364
3365    fn location(&self) -> EntityLocation {
3366        EntityLocation::View(self.window_id, self.view_id)
3367    }
3368
3369    fn downgrade(&self) -> Self::Weak {
3370        self.downgrade()
3371    }
3372
3373    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3374    where
3375        Self: Sized,
3376    {
3377        weak.upgrade(cx)
3378    }
3379}
3380
3381pub struct AnyViewHandle {
3382    window_id: usize,
3383    view_id: usize,
3384    view_type: TypeId,
3385    type_name: &'static str,
3386    ref_counts: Arc<Mutex<RefCounts>>,
3387    #[cfg(any(test, feature = "test-support"))]
3388    handle_id: usize,
3389}
3390
3391impl AnyViewHandle {
3392    fn new(
3393        window_id: usize,
3394        view_id: usize,
3395        view_type: TypeId,
3396        type_name: &'static str,
3397        ref_counts: Arc<Mutex<RefCounts>>,
3398    ) -> Self {
3399        ref_counts.lock().inc_view(window_id, view_id);
3400
3401        #[cfg(any(test, feature = "test-support"))]
3402        let handle_id = ref_counts
3403            .lock()
3404            .leak_detector
3405            .lock()
3406            .handle_created(Some(type_name), view_id);
3407
3408        Self {
3409            window_id,
3410            view_id,
3411            view_type,
3412            type_name,
3413            ref_counts,
3414            #[cfg(any(test, feature = "test-support"))]
3415            handle_id,
3416        }
3417    }
3418
3419    pub fn id(&self) -> usize {
3420        self.view_id
3421    }
3422
3423    pub fn is<T: 'static>(&self) -> bool {
3424        TypeId::of::<T>() == self.view_type
3425    }
3426
3427    pub fn is_focused(&self, cx: &AppContext) -> bool {
3428        cx.focused_view_id(self.window_id)
3429            .map_or(false, |focused_id| focused_id == self.view_id)
3430    }
3431
3432    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
3433        if self.is::<T>() {
3434            let result = Some(ViewHandle {
3435                window_id: self.window_id,
3436                view_id: self.view_id,
3437                ref_counts: self.ref_counts.clone(),
3438                view_type: PhantomData,
3439                #[cfg(any(test, feature = "test-support"))]
3440                handle_id: self.handle_id,
3441            });
3442            unsafe {
3443                Arc::decrement_strong_count(&self.ref_counts);
3444            }
3445            std::mem::forget(self);
3446            result
3447        } else {
3448            None
3449        }
3450    }
3451}
3452
3453impl Clone for AnyViewHandle {
3454    fn clone(&self) -> Self {
3455        Self::new(
3456            self.window_id,
3457            self.view_id,
3458            self.view_type,
3459            self.type_name,
3460            self.ref_counts.clone(),
3461        )
3462    }
3463}
3464
3465impl From<&AnyViewHandle> for AnyViewHandle {
3466    fn from(handle: &AnyViewHandle) -> Self {
3467        handle.clone()
3468    }
3469}
3470
3471impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
3472    fn from(handle: &ViewHandle<T>) -> Self {
3473        Self::new(
3474            handle.window_id,
3475            handle.view_id,
3476            TypeId::of::<T>(),
3477            any::type_name::<T>(),
3478            handle.ref_counts.clone(),
3479        )
3480    }
3481}
3482
3483impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
3484    fn from(handle: ViewHandle<T>) -> Self {
3485        let any_handle = AnyViewHandle {
3486            window_id: handle.window_id,
3487            view_id: handle.view_id,
3488            view_type: TypeId::of::<T>(),
3489            type_name: any::type_name::<T>(),
3490            ref_counts: handle.ref_counts.clone(),
3491            #[cfg(any(test, feature = "test-support"))]
3492            handle_id: handle.handle_id,
3493        };
3494        unsafe {
3495            Arc::decrement_strong_count(&handle.ref_counts);
3496        }
3497        std::mem::forget(handle);
3498        any_handle
3499    }
3500}
3501
3502impl Drop for AnyViewHandle {
3503    fn drop(&mut self) {
3504        self.ref_counts
3505            .lock()
3506            .dec_view(self.window_id, self.view_id);
3507        #[cfg(any(test, feature = "test-support"))]
3508        self.ref_counts
3509            .lock()
3510            .leak_detector
3511            .lock()
3512            .handle_dropped(self.view_id, self.handle_id);
3513    }
3514}
3515
3516pub struct AnyModelHandle {
3517    model_id: usize,
3518    model_type: TypeId,
3519    ref_counts: Arc<Mutex<RefCounts>>,
3520
3521    #[cfg(any(test, feature = "test-support"))]
3522    handle_id: usize,
3523}
3524
3525impl AnyModelHandle {
3526    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
3527        ref_counts.lock().inc_model(model_id);
3528
3529        #[cfg(any(test, feature = "test-support"))]
3530        let handle_id = ref_counts
3531            .lock()
3532            .leak_detector
3533            .lock()
3534            .handle_created(None, model_id);
3535
3536        Self {
3537            model_id,
3538            model_type,
3539            ref_counts,
3540
3541            #[cfg(any(test, feature = "test-support"))]
3542            handle_id,
3543        }
3544    }
3545
3546    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
3547        if self.is::<T>() {
3548            let result = Some(ModelHandle {
3549                model_id: self.model_id,
3550                model_type: PhantomData,
3551                ref_counts: self.ref_counts.clone(),
3552
3553                #[cfg(any(test, feature = "test-support"))]
3554                handle_id: self.handle_id,
3555            });
3556            unsafe {
3557                Arc::decrement_strong_count(&self.ref_counts);
3558            }
3559            std::mem::forget(self);
3560            result
3561        } else {
3562            None
3563        }
3564    }
3565
3566    pub fn downgrade(&self) -> AnyWeakModelHandle {
3567        AnyWeakModelHandle {
3568            model_id: self.model_id,
3569            model_type: self.model_type,
3570        }
3571    }
3572
3573    pub fn is<T: Entity>(&self) -> bool {
3574        self.model_type == TypeId::of::<T>()
3575    }
3576}
3577
3578impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
3579    fn from(handle: ModelHandle<T>) -> Self {
3580        Self::new(
3581            handle.model_id,
3582            TypeId::of::<T>(),
3583            handle.ref_counts.clone(),
3584        )
3585    }
3586}
3587
3588impl Clone for AnyModelHandle {
3589    fn clone(&self) -> Self {
3590        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
3591    }
3592}
3593
3594impl Drop for AnyModelHandle {
3595    fn drop(&mut self) {
3596        let mut ref_counts = self.ref_counts.lock();
3597        ref_counts.dec_model(self.model_id);
3598
3599        #[cfg(any(test, feature = "test-support"))]
3600        ref_counts
3601            .leak_detector
3602            .lock()
3603            .handle_dropped(self.model_id, self.handle_id);
3604    }
3605}
3606
3607pub struct AnyWeakModelHandle {
3608    model_id: usize,
3609    model_type: TypeId,
3610}
3611
3612impl AnyWeakModelHandle {
3613    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
3614        cx.upgrade_any_model_handle(self)
3615    }
3616}
3617
3618impl<T: Entity> From<WeakModelHandle<T>> for AnyWeakModelHandle {
3619    fn from(handle: WeakModelHandle<T>) -> Self {
3620        AnyWeakModelHandle {
3621            model_id: handle.model_id,
3622            model_type: TypeId::of::<T>(),
3623        }
3624    }
3625}
3626
3627pub struct WeakViewHandle<T> {
3628    window_id: usize,
3629    view_id: usize,
3630    view_type: PhantomData<T>,
3631}
3632
3633impl<T: View> WeakViewHandle<T> {
3634    fn new(window_id: usize, view_id: usize) -> Self {
3635        Self {
3636            window_id,
3637            view_id,
3638            view_type: PhantomData,
3639        }
3640    }
3641
3642    pub fn id(&self) -> usize {
3643        self.view_id
3644    }
3645
3646    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
3647        cx.upgrade_view_handle(self)
3648    }
3649}
3650
3651impl<T> Clone for WeakViewHandle<T> {
3652    fn clone(&self) -> Self {
3653        Self {
3654            window_id: self.window_id,
3655            view_id: self.view_id,
3656            view_type: PhantomData,
3657        }
3658    }
3659}
3660
3661impl<T> PartialEq for WeakViewHandle<T> {
3662    fn eq(&self, other: &Self) -> bool {
3663        self.window_id == other.window_id && self.view_id == other.view_id
3664    }
3665}
3666
3667impl<T> Eq for WeakViewHandle<T> {}
3668
3669impl<T> Hash for WeakViewHandle<T> {
3670    fn hash<H: Hasher>(&self, state: &mut H) {
3671        self.window_id.hash(state);
3672        self.view_id.hash(state);
3673    }
3674}
3675
3676#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3677pub struct ElementStateId {
3678    view_id: usize,
3679    element_id: usize,
3680    tag: TypeId,
3681}
3682
3683pub struct ElementStateHandle<T> {
3684    value_type: PhantomData<T>,
3685    id: ElementStateId,
3686    ref_counts: Weak<Mutex<RefCounts>>,
3687}
3688
3689impl<T: 'static> ElementStateHandle<T> {
3690    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3691        ref_counts.lock().inc_element_state(id, frame_id);
3692        Self {
3693            value_type: PhantomData,
3694            id,
3695            ref_counts: Arc::downgrade(ref_counts),
3696        }
3697    }
3698
3699    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3700        cx.element_states
3701            .get(&self.id)
3702            .unwrap()
3703            .downcast_ref()
3704            .unwrap()
3705    }
3706
3707    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
3708    where
3709        C: DerefMut<Target = MutableAppContext>,
3710    {
3711        let mut element_state = cx.deref_mut().cx.element_states.remove(&self.id).unwrap();
3712        let result = f(element_state.downcast_mut().unwrap(), cx);
3713        cx.deref_mut()
3714            .cx
3715            .element_states
3716            .insert(self.id, element_state);
3717        result
3718    }
3719}
3720
3721impl<T> Drop for ElementStateHandle<T> {
3722    fn drop(&mut self) {
3723        if let Some(ref_counts) = self.ref_counts.upgrade() {
3724            ref_counts.lock().dec_element_state(self.id);
3725        }
3726    }
3727}
3728
3729pub struct CursorStyleHandle {
3730    id: usize,
3731    next_cursor_style_handle_id: Arc<AtomicUsize>,
3732    platform: Arc<dyn Platform>,
3733}
3734
3735impl Drop for CursorStyleHandle {
3736    fn drop(&mut self) {
3737        if self.id + 1 == self.next_cursor_style_handle_id.load(SeqCst) {
3738            self.platform.set_cursor_style(CursorStyle::Arrow);
3739        }
3740    }
3741}
3742
3743#[must_use]
3744pub enum Subscription {
3745    Subscription {
3746        id: usize,
3747        entity_id: usize,
3748        subscriptions: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>>,
3749    },
3750    Observation {
3751        id: usize,
3752        entity_id: usize,
3753        observations: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ObservationCallback>>>>>,
3754    },
3755    ReleaseObservation {
3756        id: usize,
3757        entity_id: usize,
3758        observations:
3759            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>>,
3760    },
3761}
3762
3763impl Subscription {
3764    pub fn detach(&mut self) {
3765        match self {
3766            Subscription::Subscription { subscriptions, .. } => {
3767                subscriptions.take();
3768            }
3769            Subscription::Observation { observations, .. } => {
3770                observations.take();
3771            }
3772            Subscription::ReleaseObservation { observations, .. } => {
3773                observations.take();
3774            }
3775        }
3776    }
3777}
3778
3779impl Drop for Subscription {
3780    fn drop(&mut self) {
3781        match self {
3782            Subscription::Observation {
3783                id,
3784                entity_id,
3785                observations,
3786            } => {
3787                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3788                    if let Some(observations) = observations.lock().get_mut(entity_id) {
3789                        observations.remove(id);
3790                    }
3791                }
3792            }
3793            Subscription::ReleaseObservation {
3794                id,
3795                entity_id,
3796                observations,
3797            } => {
3798                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3799                    if let Some(observations) = observations.lock().get_mut(entity_id) {
3800                        observations.remove(id);
3801                    }
3802                }
3803            }
3804            Subscription::Subscription {
3805                id,
3806                entity_id,
3807                subscriptions,
3808            } => {
3809                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
3810                    if let Some(subscriptions) = subscriptions.lock().get_mut(entity_id) {
3811                        subscriptions.remove(id);
3812                    }
3813                }
3814            }
3815        }
3816    }
3817}
3818
3819lazy_static! {
3820    static ref LEAK_BACKTRACE: bool =
3821        std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty());
3822}
3823
3824#[cfg(any(test, feature = "test-support"))]
3825#[derive(Default)]
3826pub struct LeakDetector {
3827    next_handle_id: usize,
3828    handle_backtraces: HashMap<
3829        usize,
3830        (
3831            Option<&'static str>,
3832            HashMap<usize, Option<backtrace::Backtrace>>,
3833        ),
3834    >,
3835}
3836
3837#[cfg(any(test, feature = "test-support"))]
3838impl LeakDetector {
3839    fn handle_created(&mut self, type_name: Option<&'static str>, entity_id: usize) -> usize {
3840        let handle_id = post_inc(&mut self.next_handle_id);
3841        let entry = self.handle_backtraces.entry(entity_id).or_default();
3842        let backtrace = if *LEAK_BACKTRACE {
3843            Some(backtrace::Backtrace::new_unresolved())
3844        } else {
3845            None
3846        };
3847        if let Some(type_name) = type_name {
3848            entry.0.get_or_insert(type_name);
3849        }
3850        entry.1.insert(handle_id, backtrace);
3851        handle_id
3852    }
3853
3854    fn handle_dropped(&mut self, entity_id: usize, handle_id: usize) {
3855        if let Some((_, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
3856            assert!(backtraces.remove(&handle_id).is_some());
3857            if backtraces.is_empty() {
3858                self.handle_backtraces.remove(&entity_id);
3859            }
3860        }
3861    }
3862
3863    pub fn detect(&mut self) {
3864        let mut found_leaks = false;
3865        for (id, (type_name, backtraces)) in self.handle_backtraces.iter_mut() {
3866            eprintln!(
3867                "leaked {} handles to {:?} {}",
3868                backtraces.len(),
3869                type_name.unwrap_or("entity"),
3870                id
3871            );
3872            for trace in backtraces.values_mut() {
3873                if let Some(trace) = trace {
3874                    trace.resolve();
3875                    eprintln!("{:?}", crate::util::CwdBacktrace(trace));
3876                }
3877            }
3878            found_leaks = true;
3879        }
3880
3881        let hint = if *LEAK_BACKTRACE {
3882            ""
3883        } else {
3884            " – set LEAK_BACKTRACE=1 for more information"
3885        };
3886        assert!(!found_leaks, "detected leaked handles{}", hint);
3887    }
3888}
3889
3890#[derive(Default)]
3891struct RefCounts {
3892    entity_counts: HashMap<usize, usize>,
3893    element_state_counts: HashMap<ElementStateId, ElementStateRefCount>,
3894    dropped_models: HashSet<usize>,
3895    dropped_views: HashSet<(usize, usize)>,
3896    dropped_element_states: HashSet<ElementStateId>,
3897
3898    #[cfg(any(test, feature = "test-support"))]
3899    leak_detector: Arc<Mutex<LeakDetector>>,
3900}
3901
3902struct ElementStateRefCount {
3903    ref_count: usize,
3904    frame_id: usize,
3905}
3906
3907impl RefCounts {
3908    fn inc_model(&mut self, model_id: usize) {
3909        match self.entity_counts.entry(model_id) {
3910            Entry::Occupied(mut entry) => {
3911                *entry.get_mut() += 1;
3912            }
3913            Entry::Vacant(entry) => {
3914                entry.insert(1);
3915                self.dropped_models.remove(&model_id);
3916            }
3917        }
3918    }
3919
3920    fn inc_view(&mut self, window_id: usize, view_id: usize) {
3921        match self.entity_counts.entry(view_id) {
3922            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3923            Entry::Vacant(entry) => {
3924                entry.insert(1);
3925                self.dropped_views.remove(&(window_id, view_id));
3926            }
3927        }
3928    }
3929
3930    fn inc_element_state(&mut self, id: ElementStateId, frame_id: usize) {
3931        match self.element_state_counts.entry(id) {
3932            Entry::Occupied(mut entry) => {
3933                let entry = entry.get_mut();
3934                if entry.frame_id == frame_id || entry.ref_count >= 2 {
3935                    panic!("used the same element state more than once in the same frame");
3936                }
3937                entry.ref_count += 1;
3938                entry.frame_id = frame_id;
3939            }
3940            Entry::Vacant(entry) => {
3941                entry.insert(ElementStateRefCount {
3942                    ref_count: 1,
3943                    frame_id,
3944                });
3945                self.dropped_element_states.remove(&id);
3946            }
3947        }
3948    }
3949
3950    fn dec_model(&mut self, model_id: usize) {
3951        let count = self.entity_counts.get_mut(&model_id).unwrap();
3952        *count -= 1;
3953        if *count == 0 {
3954            self.entity_counts.remove(&model_id);
3955            self.dropped_models.insert(model_id);
3956        }
3957    }
3958
3959    fn dec_view(&mut self, window_id: usize, view_id: usize) {
3960        let count = self.entity_counts.get_mut(&view_id).unwrap();
3961        *count -= 1;
3962        if *count == 0 {
3963            self.entity_counts.remove(&view_id);
3964            self.dropped_views.insert((window_id, view_id));
3965        }
3966    }
3967
3968    fn dec_element_state(&mut self, id: ElementStateId) {
3969        let entry = self.element_state_counts.get_mut(&id).unwrap();
3970        entry.ref_count -= 1;
3971        if entry.ref_count == 0 {
3972            self.element_state_counts.remove(&id);
3973            self.dropped_element_states.insert(id);
3974        }
3975    }
3976
3977    fn is_entity_alive(&self, entity_id: usize) -> bool {
3978        self.entity_counts.contains_key(&entity_id)
3979    }
3980
3981    fn take_dropped(
3982        &mut self,
3983    ) -> (
3984        HashSet<usize>,
3985        HashSet<(usize, usize)>,
3986        HashSet<ElementStateId>,
3987    ) {
3988        (
3989            std::mem::take(&mut self.dropped_models),
3990            std::mem::take(&mut self.dropped_views),
3991            std::mem::take(&mut self.dropped_element_states),
3992        )
3993    }
3994}
3995
3996#[cfg(test)]
3997mod tests {
3998    use super::*;
3999    use crate::elements::*;
4000    use smol::future::poll_once;
4001    use std::{
4002        cell::Cell,
4003        sync::atomic::{AtomicUsize, Ordering::SeqCst},
4004    };
4005
4006    #[crate::test(self)]
4007    fn test_model_handles(cx: &mut MutableAppContext) {
4008        struct Model {
4009            other: Option<ModelHandle<Model>>,
4010            events: Vec<String>,
4011        }
4012
4013        impl Entity for Model {
4014            type Event = usize;
4015        }
4016
4017        impl Model {
4018            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
4019                if let Some(other) = other.as_ref() {
4020                    cx.observe(other, |me, _, _| {
4021                        me.events.push("notified".into());
4022                    })
4023                    .detach();
4024                    cx.subscribe(other, |me, _, event, _| {
4025                        me.events.push(format!("observed event {}", event));
4026                    })
4027                    .detach();
4028                }
4029
4030                Self {
4031                    other,
4032                    events: Vec::new(),
4033                }
4034            }
4035        }
4036
4037        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
4038        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
4039        assert_eq!(cx.cx.models.len(), 2);
4040
4041        handle_1.update(cx, |model, cx| {
4042            model.events.push("updated".into());
4043            cx.emit(1);
4044            cx.notify();
4045            cx.emit(2);
4046        });
4047        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4048        assert_eq!(
4049            handle_2.read(cx).events,
4050            vec![
4051                "observed event 1".to_string(),
4052                "notified".to_string(),
4053                "observed event 2".to_string(),
4054            ]
4055        );
4056
4057        handle_2.update(cx, |model, _| {
4058            drop(handle_1);
4059            model.other.take();
4060        });
4061
4062        assert_eq!(cx.cx.models.len(), 1);
4063        assert!(cx.subscriptions.lock().is_empty());
4064        assert!(cx.observations.lock().is_empty());
4065    }
4066
4067    #[crate::test(self)]
4068    fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) {
4069        #[derive(Default)]
4070        struct Model {
4071            events: Vec<usize>,
4072        }
4073
4074        impl Entity for Model {
4075            type Event = usize;
4076        }
4077
4078        let handle_1 = cx.add_model(|_| Model::default());
4079        let handle_2 = cx.add_model(|_| Model::default());
4080        handle_1.update(cx, |_, c| {
4081            c.subscribe(&handle_2, move |model: &mut Model, emitter, event, c| {
4082                model.events.push(*event);
4083
4084                c.subscribe(&emitter, |model, _, event, _| {
4085                    model.events.push(*event * 2);
4086                })
4087                .detach();
4088            })
4089            .detach();
4090        });
4091
4092        handle_2.update(cx, |_, c| c.emit(7));
4093        assert_eq!(handle_1.read(cx).events, vec![7]);
4094
4095        handle_2.update(cx, |_, c| c.emit(5));
4096        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4097    }
4098
4099    #[crate::test(self)]
4100    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
4101        #[derive(Default)]
4102        struct Model {
4103            count: usize,
4104            events: Vec<usize>,
4105        }
4106
4107        impl Entity for Model {
4108            type Event = ();
4109        }
4110
4111        let handle_1 = cx.add_model(|_| Model::default());
4112        let handle_2 = cx.add_model(|_| Model::default());
4113
4114        handle_1.update(cx, |_, c| {
4115            c.observe(&handle_2, move |model, observed, c| {
4116                model.events.push(observed.read(c).count);
4117                c.observe(&observed, |model, observed, c| {
4118                    model.events.push(observed.read(c).count * 2);
4119                })
4120                .detach();
4121            })
4122            .detach();
4123        });
4124
4125        handle_2.update(cx, |model, c| {
4126            model.count = 7;
4127            c.notify()
4128        });
4129        assert_eq!(handle_1.read(cx).events, vec![7]);
4130
4131        handle_2.update(cx, |model, c| {
4132            model.count = 5;
4133            c.notify()
4134        });
4135        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
4136    }
4137
4138    #[crate::test(self)]
4139    fn test_view_handles(cx: &mut MutableAppContext) {
4140        struct View {
4141            other: Option<ViewHandle<View>>,
4142            events: Vec<String>,
4143        }
4144
4145        impl Entity for View {
4146            type Event = usize;
4147        }
4148
4149        impl super::View for View {
4150            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4151                Empty::new().boxed()
4152            }
4153
4154            fn ui_name() -> &'static str {
4155                "View"
4156            }
4157        }
4158
4159        impl View {
4160            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
4161                if let Some(other) = other.as_ref() {
4162                    cx.subscribe(other, |me, _, event, _| {
4163                        me.events.push(format!("observed event {}", event));
4164                    })
4165                    .detach();
4166                }
4167                Self {
4168                    other,
4169                    events: Vec::new(),
4170                }
4171            }
4172        }
4173
4174        let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
4175        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
4176        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
4177        assert_eq!(cx.cx.views.len(), 3);
4178
4179        handle_1.update(cx, |view, cx| {
4180            view.events.push("updated".into());
4181            cx.emit(1);
4182            cx.emit(2);
4183        });
4184        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4185        assert_eq!(
4186            handle_2.read(cx).events,
4187            vec![
4188                "observed event 1".to_string(),
4189                "observed event 2".to_string(),
4190            ]
4191        );
4192
4193        handle_2.update(cx, |view, _| {
4194            drop(handle_1);
4195            view.other.take();
4196        });
4197
4198        assert_eq!(cx.cx.views.len(), 2);
4199        assert!(cx.subscriptions.lock().is_empty());
4200        assert!(cx.observations.lock().is_empty());
4201    }
4202
4203    #[crate::test(self)]
4204    fn test_add_window(cx: &mut MutableAppContext) {
4205        struct View {
4206            mouse_down_count: Arc<AtomicUsize>,
4207        }
4208
4209        impl Entity for View {
4210            type Event = ();
4211        }
4212
4213        impl super::View for View {
4214            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4215                let mouse_down_count = self.mouse_down_count.clone();
4216                EventHandler::new(Empty::new().boxed())
4217                    .on_mouse_down(move |_| {
4218                        mouse_down_count.fetch_add(1, SeqCst);
4219                        true
4220                    })
4221                    .boxed()
4222            }
4223
4224            fn ui_name() -> &'static str {
4225                "View"
4226            }
4227        }
4228
4229        let mouse_down_count = Arc::new(AtomicUsize::new(0));
4230        let (window_id, _) = cx.add_window(Default::default(), |_| View {
4231            mouse_down_count: mouse_down_count.clone(),
4232        });
4233        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
4234        // Ensure window's root element is in a valid lifecycle state.
4235        presenter.borrow_mut().dispatch_event(
4236            Event::LeftMouseDown {
4237                position: Default::default(),
4238                ctrl: false,
4239                alt: false,
4240                shift: false,
4241                cmd: false,
4242                click_count: 1,
4243            },
4244            cx,
4245        );
4246        assert_eq!(mouse_down_count.load(SeqCst), 1);
4247    }
4248
4249    #[crate::test(self)]
4250    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
4251        struct Model {
4252            released: Rc<Cell<bool>>,
4253        }
4254
4255        struct View {
4256            released: Rc<Cell<bool>>,
4257        }
4258
4259        impl Entity for Model {
4260            type Event = ();
4261
4262            fn release(&mut self, _: &mut MutableAppContext) {
4263                self.released.set(true);
4264            }
4265        }
4266
4267        impl Entity for View {
4268            type Event = ();
4269
4270            fn release(&mut self, _: &mut MutableAppContext) {
4271                self.released.set(true);
4272            }
4273        }
4274
4275        impl super::View for View {
4276            fn ui_name() -> &'static str {
4277                "View"
4278            }
4279
4280            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4281                Empty::new().boxed()
4282            }
4283        }
4284
4285        let model_released = Rc::new(Cell::new(false));
4286        let model_release_observed = Rc::new(Cell::new(false));
4287        let view_released = Rc::new(Cell::new(false));
4288        let view_release_observed = Rc::new(Cell::new(false));
4289
4290        let model = cx.add_model(|_| Model {
4291            released: model_released.clone(),
4292        });
4293        let (window_id, view) = cx.add_window(Default::default(), |_| View {
4294            released: view_released.clone(),
4295        });
4296        assert!(!model_released.get());
4297        assert!(!view_released.get());
4298
4299        cx.observe_release(&model, {
4300            let model_release_observed = model_release_observed.clone();
4301            move |_| model_release_observed.set(true)
4302        })
4303        .detach();
4304        cx.observe_release(&view, {
4305            let view_release_observed = view_release_observed.clone();
4306            move |_| view_release_observed.set(true)
4307        })
4308        .detach();
4309
4310        cx.update(move |_| {
4311            drop(model);
4312        });
4313        assert!(model_released.get());
4314        assert!(model_release_observed.get());
4315
4316        drop(view);
4317        cx.remove_window(window_id);
4318        assert!(view_released.get());
4319        assert!(view_release_observed.get());
4320    }
4321
4322    #[crate::test(self)]
4323    fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) {
4324        #[derive(Default)]
4325        struct View {
4326            events: Vec<usize>,
4327        }
4328
4329        impl Entity for View {
4330            type Event = usize;
4331        }
4332
4333        impl super::View for View {
4334            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4335                Empty::new().boxed()
4336            }
4337
4338            fn ui_name() -> &'static str {
4339                "View"
4340            }
4341        }
4342
4343        struct Model;
4344
4345        impl Entity for Model {
4346            type Event = usize;
4347        }
4348
4349        let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
4350        let handle_2 = cx.add_view(window_id, |_| View::default());
4351        let handle_3 = cx.add_model(|_| Model);
4352
4353        handle_1.update(cx, |_, c| {
4354            c.subscribe(&handle_2, move |me, emitter, event, c| {
4355                me.events.push(*event);
4356
4357                c.subscribe(&emitter, |me, _, event, _| {
4358                    me.events.push(*event * 2);
4359                })
4360                .detach();
4361            })
4362            .detach();
4363
4364            c.subscribe(&handle_3, |me, _, event, _| {
4365                me.events.push(*event);
4366            })
4367            .detach();
4368        });
4369
4370        handle_2.update(cx, |_, c| c.emit(7));
4371        assert_eq!(handle_1.read(cx).events, vec![7]);
4372
4373        handle_2.update(cx, |_, c| c.emit(5));
4374        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4375
4376        handle_3.update(cx, |_, c| c.emit(9));
4377        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
4378    }
4379
4380    #[crate::test(self)]
4381    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
4382        struct View;
4383
4384        impl Entity for View {
4385            type Event = ();
4386        }
4387
4388        impl super::View for View {
4389            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4390                Empty::new().boxed()
4391            }
4392
4393            fn ui_name() -> &'static str {
4394                "View"
4395            }
4396        }
4397
4398        struct Model;
4399
4400        impl Entity for Model {
4401            type Event = ();
4402        }
4403
4404        let (window_id, _) = cx.add_window(Default::default(), |_| View);
4405        let observing_view = cx.add_view(window_id, |_| View);
4406        let emitting_view = cx.add_view(window_id, |_| View);
4407        let observing_model = cx.add_model(|_| Model);
4408        let observed_model = cx.add_model(|_| Model);
4409
4410        observing_view.update(cx, |_, cx| {
4411            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
4412            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4413        });
4414        observing_model.update(cx, |_, cx| {
4415            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4416        });
4417
4418        cx.update(|_| {
4419            drop(observing_view);
4420            drop(observing_model);
4421        });
4422
4423        emitting_view.update(cx, |_, cx| cx.emit(()));
4424        observed_model.update(cx, |_, cx| cx.emit(()));
4425    }
4426
4427    #[crate::test(self)]
4428    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
4429        #[derive(Default)]
4430        struct View {
4431            events: Vec<usize>,
4432        }
4433
4434        impl Entity for View {
4435            type Event = usize;
4436        }
4437
4438        impl super::View for View {
4439            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4440                Empty::new().boxed()
4441            }
4442
4443            fn ui_name() -> &'static str {
4444                "View"
4445            }
4446        }
4447
4448        #[derive(Default)]
4449        struct Model {
4450            count: usize,
4451        }
4452
4453        impl Entity for Model {
4454            type Event = ();
4455        }
4456
4457        let (_, view) = cx.add_window(Default::default(), |_| View::default());
4458        let model = cx.add_model(|_| Model::default());
4459
4460        view.update(cx, |_, c| {
4461            c.observe(&model, |me, observed, c| {
4462                me.events.push(observed.read(c).count)
4463            })
4464            .detach();
4465        });
4466
4467        model.update(cx, |model, c| {
4468            model.count = 11;
4469            c.notify();
4470        });
4471        assert_eq!(view.read(cx).events, vec![11]);
4472    }
4473
4474    #[crate::test(self)]
4475    fn test_dropping_observers(cx: &mut MutableAppContext) {
4476        struct View;
4477
4478        impl Entity for View {
4479            type Event = ();
4480        }
4481
4482        impl super::View for View {
4483            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4484                Empty::new().boxed()
4485            }
4486
4487            fn ui_name() -> &'static str {
4488                "View"
4489            }
4490        }
4491
4492        struct Model;
4493
4494        impl Entity for Model {
4495            type Event = ();
4496        }
4497
4498        let (window_id, _) = cx.add_window(Default::default(), |_| View);
4499        let observing_view = cx.add_view(window_id, |_| View);
4500        let observing_model = cx.add_model(|_| Model);
4501        let observed_model = cx.add_model(|_| Model);
4502
4503        observing_view.update(cx, |_, cx| {
4504            cx.observe(&observed_model, |_, _, _| {}).detach();
4505        });
4506        observing_model.update(cx, |_, cx| {
4507            cx.observe(&observed_model, |_, _, _| {}).detach();
4508        });
4509
4510        cx.update(|_| {
4511            drop(observing_view);
4512            drop(observing_model);
4513        });
4514
4515        observed_model.update(cx, |_, cx| cx.notify());
4516    }
4517
4518    #[crate::test(self)]
4519    fn test_focus(cx: &mut MutableAppContext) {
4520        struct View {
4521            name: String,
4522            events: Arc<Mutex<Vec<String>>>,
4523        }
4524
4525        impl Entity for View {
4526            type Event = ();
4527        }
4528
4529        impl super::View for View {
4530            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4531                Empty::new().boxed()
4532            }
4533
4534            fn ui_name() -> &'static str {
4535                "View"
4536            }
4537
4538            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
4539                self.events.lock().push(format!("{} focused", &self.name));
4540            }
4541
4542            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
4543                self.events.lock().push(format!("{} blurred", &self.name));
4544            }
4545        }
4546
4547        let events: Arc<Mutex<Vec<String>>> = Default::default();
4548        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
4549            events: events.clone(),
4550            name: "view 1".to_string(),
4551        });
4552        let view_2 = cx.add_view(window_id, |_| View {
4553            events: events.clone(),
4554            name: "view 2".to_string(),
4555        });
4556
4557        view_1.update(cx, |_, cx| cx.focus(&view_2));
4558        view_1.update(cx, |_, cx| cx.focus(&view_1));
4559        view_1.update(cx, |_, cx| cx.focus(&view_2));
4560        view_1.update(cx, |_, _| drop(view_2));
4561
4562        assert_eq!(
4563            *events.lock(),
4564            [
4565                "view 1 focused".to_string(),
4566                "view 1 blurred".to_string(),
4567                "view 2 focused".to_string(),
4568                "view 2 blurred".to_string(),
4569                "view 1 focused".to_string(),
4570                "view 1 blurred".to_string(),
4571                "view 2 focused".to_string(),
4572                "view 1 focused".to_string(),
4573            ],
4574        );
4575    }
4576
4577    #[crate::test(self)]
4578    fn test_dispatch_action(cx: &mut MutableAppContext) {
4579        struct ViewA {
4580            id: usize,
4581        }
4582
4583        impl Entity for ViewA {
4584            type Event = ();
4585        }
4586
4587        impl View for ViewA {
4588            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4589                Empty::new().boxed()
4590            }
4591
4592            fn ui_name() -> &'static str {
4593                "View"
4594            }
4595        }
4596
4597        struct ViewB {
4598            id: usize,
4599        }
4600
4601        impl Entity for ViewB {
4602            type Event = ();
4603        }
4604
4605        impl View for ViewB {
4606            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4607                Empty::new().boxed()
4608            }
4609
4610            fn ui_name() -> &'static str {
4611                "View"
4612            }
4613        }
4614
4615        action!(Action, &'static str);
4616
4617        let actions = Rc::new(RefCell::new(Vec::new()));
4618
4619        {
4620            let actions = actions.clone();
4621            cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
4622                actions.borrow_mut().push("global".to_string());
4623            });
4624        }
4625
4626        {
4627            let actions = actions.clone();
4628            cx.add_action(move |view: &mut ViewA, action: &Action, cx| {
4629                assert_eq!(action.0, "bar");
4630                cx.propagate_action();
4631                actions.borrow_mut().push(format!("{} a", view.id));
4632            });
4633        }
4634
4635        {
4636            let actions = actions.clone();
4637            cx.add_action(move |view: &mut ViewA, _: &Action, cx| {
4638                if view.id != 1 {
4639                    cx.add_view(|cx| {
4640                        cx.propagate_action(); // Still works on a nested ViewContext
4641                        ViewB { id: 5 }
4642                    });
4643                }
4644                actions.borrow_mut().push(format!("{} b", view.id));
4645            });
4646        }
4647
4648        {
4649            let actions = actions.clone();
4650            cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
4651                cx.propagate_action();
4652                actions.borrow_mut().push(format!("{} c", view.id));
4653            });
4654        }
4655
4656        {
4657            let actions = actions.clone();
4658            cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
4659                cx.propagate_action();
4660                actions.borrow_mut().push(format!("{} d", view.id));
4661            });
4662        }
4663
4664        {
4665            let actions = actions.clone();
4666            cx.capture_action(move |view: &mut ViewA, _: &Action, cx| {
4667                cx.propagate_action();
4668                actions.borrow_mut().push(format!("{} capture", view.id));
4669            });
4670        }
4671
4672        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
4673        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
4674        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
4675        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
4676
4677        cx.dispatch_action(
4678            window_id,
4679            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
4680            &Action("bar"),
4681        );
4682
4683        assert_eq!(
4684            *actions.borrow(),
4685            vec![
4686                "1 capture",
4687                "3 capture",
4688                "4 d",
4689                "4 c",
4690                "3 b",
4691                "3 a",
4692                "2 d",
4693                "2 c",
4694                "1 b"
4695            ]
4696        );
4697
4698        // Remove view_1, which doesn't propagate the action
4699        actions.borrow_mut().clear();
4700        cx.dispatch_action(
4701            window_id,
4702            vec![view_2.id(), view_3.id(), view_4.id()],
4703            &Action("bar"),
4704        );
4705
4706        assert_eq!(
4707            *actions.borrow(),
4708            vec![
4709                "3 capture",
4710                "4 d",
4711                "4 c",
4712                "3 b",
4713                "3 a",
4714                "2 d",
4715                "2 c",
4716                "global"
4717            ]
4718        );
4719    }
4720
4721    #[crate::test(self)]
4722    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
4723        use std::cell::Cell;
4724
4725        action!(Action, &'static str);
4726
4727        struct View {
4728            id: usize,
4729            keymap_context: keymap::Context,
4730        }
4731
4732        impl Entity for View {
4733            type Event = ();
4734        }
4735
4736        impl super::View for View {
4737            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4738                Empty::new().boxed()
4739            }
4740
4741            fn ui_name() -> &'static str {
4742                "View"
4743            }
4744
4745            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
4746                self.keymap_context.clone()
4747            }
4748        }
4749
4750        impl View {
4751            fn new(id: usize) -> Self {
4752                View {
4753                    id,
4754                    keymap_context: keymap::Context::default(),
4755                }
4756            }
4757        }
4758
4759        let mut view_1 = View::new(1);
4760        let mut view_2 = View::new(2);
4761        let mut view_3 = View::new(3);
4762        view_1.keymap_context.set.insert("a".into());
4763        view_2.keymap_context.set.insert("a".into());
4764        view_2.keymap_context.set.insert("b".into());
4765        view_3.keymap_context.set.insert("a".into());
4766        view_3.keymap_context.set.insert("b".into());
4767        view_3.keymap_context.set.insert("c".into());
4768
4769        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
4770        let view_2 = cx.add_view(window_id, |_| view_2);
4771        let view_3 = cx.add_view(window_id, |_| view_3);
4772
4773        // This keymap's only binding dispatches an action on view 2 because that view will have
4774        // "a" and "b" in its context, but not "c".
4775        cx.add_bindings(vec![keymap::Binding::new(
4776            "a",
4777            Action("a"),
4778            Some("a && b && !c"),
4779        )]);
4780
4781        let handled_action = Rc::new(Cell::new(false));
4782        let handled_action_clone = handled_action.clone();
4783        cx.add_action(move |view: &mut View, action: &Action, _| {
4784            handled_action_clone.set(true);
4785            assert_eq!(view.id, 2);
4786            assert_eq!(action.0, "a");
4787        });
4788
4789        cx.dispatch_keystroke(
4790            window_id,
4791            vec![view_1.id(), view_2.id(), view_3.id()],
4792            &Keystroke::parse("a").unwrap(),
4793        )
4794        .unwrap();
4795
4796        assert!(handled_action.get());
4797    }
4798
4799    #[crate::test(self)]
4800    async fn test_model_condition(cx: &mut TestAppContext) {
4801        struct Counter(usize);
4802
4803        impl super::Entity for Counter {
4804            type Event = ();
4805        }
4806
4807        impl Counter {
4808            fn inc(&mut self, cx: &mut ModelContext<Self>) {
4809                self.0 += 1;
4810                cx.notify();
4811            }
4812        }
4813
4814        let model = cx.add_model(|_| Counter(0));
4815
4816        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
4817        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
4818        smol::pin!(condition1, condition2);
4819
4820        model.update(cx, |model, cx| model.inc(cx));
4821        assert_eq!(poll_once(&mut condition1).await, None);
4822        assert_eq!(poll_once(&mut condition2).await, None);
4823
4824        model.update(cx, |model, cx| model.inc(cx));
4825        assert_eq!(poll_once(&mut condition1).await, Some(()));
4826        assert_eq!(poll_once(&mut condition2).await, None);
4827
4828        model.update(cx, |model, cx| model.inc(cx));
4829        assert_eq!(poll_once(&mut condition2).await, Some(()));
4830
4831        model.update(cx, |_, cx| cx.notify());
4832    }
4833
4834    #[crate::test(self)]
4835    #[should_panic]
4836    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
4837        struct Model;
4838
4839        impl super::Entity for Model {
4840            type Event = ();
4841        }
4842
4843        let model = cx.add_model(|_| Model);
4844        model.condition(&cx, |_, _| false).await;
4845    }
4846
4847    #[crate::test(self)]
4848    #[should_panic(expected = "model dropped with pending condition")]
4849    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
4850        struct Model;
4851
4852        impl super::Entity for Model {
4853            type Event = ();
4854        }
4855
4856        let model = cx.add_model(|_| Model);
4857        let condition = model.condition(&cx, |_, _| false);
4858        cx.update(|_| drop(model));
4859        condition.await;
4860    }
4861
4862    #[crate::test(self)]
4863    async fn test_view_condition(cx: &mut TestAppContext) {
4864        struct Counter(usize);
4865
4866        impl super::Entity for Counter {
4867            type Event = ();
4868        }
4869
4870        impl super::View for Counter {
4871            fn ui_name() -> &'static str {
4872                "test view"
4873            }
4874
4875            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4876                Empty::new().boxed()
4877            }
4878        }
4879
4880        impl Counter {
4881            fn inc(&mut self, cx: &mut ViewContext<Self>) {
4882                self.0 += 1;
4883                cx.notify();
4884            }
4885        }
4886
4887        let (_, view) = cx.add_window(|_| Counter(0));
4888
4889        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
4890        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
4891        smol::pin!(condition1, condition2);
4892
4893        view.update(cx, |view, cx| view.inc(cx));
4894        assert_eq!(poll_once(&mut condition1).await, None);
4895        assert_eq!(poll_once(&mut condition2).await, None);
4896
4897        view.update(cx, |view, cx| view.inc(cx));
4898        assert_eq!(poll_once(&mut condition1).await, Some(()));
4899        assert_eq!(poll_once(&mut condition2).await, None);
4900
4901        view.update(cx, |view, cx| view.inc(cx));
4902        assert_eq!(poll_once(&mut condition2).await, Some(()));
4903        view.update(cx, |_, cx| cx.notify());
4904    }
4905
4906    #[crate::test(self)]
4907    #[should_panic]
4908    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
4909        struct View;
4910
4911        impl super::Entity for View {
4912            type Event = ();
4913        }
4914
4915        impl super::View for View {
4916            fn ui_name() -> &'static str {
4917                "test view"
4918            }
4919
4920            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4921                Empty::new().boxed()
4922            }
4923        }
4924
4925        let (_, view) = cx.add_window(|_| View);
4926        view.condition(&cx, |_, _| false).await;
4927    }
4928
4929    #[crate::test(self)]
4930    #[should_panic(expected = "view dropped with pending condition")]
4931    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
4932        struct View;
4933
4934        impl super::Entity for View {
4935            type Event = ();
4936        }
4937
4938        impl super::View for View {
4939            fn ui_name() -> &'static str {
4940                "test view"
4941            }
4942
4943            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4944                Empty::new().boxed()
4945            }
4946        }
4947
4948        let window_id = cx.add_window(|_| View).0;
4949        let view = cx.add_view(window_id, |_| View);
4950
4951        let condition = view.condition(&cx, |_, _| false);
4952        cx.update(|_| drop(view));
4953        condition.await;
4954    }
4955}