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::{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: Some(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 == Some(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, Some(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: Option<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).and_then(|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(focused_id) = focused_id {
1784                if let Some(mut focused_view) = this.cx.views.remove(&(window_id, focused_id)) {
1785                    focused_view.on_focus(this, window_id, focused_id);
1786                    this.cx.views.insert((window_id, focused_id), focused_view);
1787                }
1788            }
1789        })
1790    }
1791
1792    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
1793    where
1794        F: FnOnce(AsyncAppContext) -> Fut,
1795        Fut: 'static + Future<Output = T>,
1796        T: 'static,
1797    {
1798        let future = f(self.to_async());
1799        let cx = self.to_async();
1800        self.foreground.spawn(async move {
1801            let result = future.await;
1802            cx.0.borrow_mut().flush_effects();
1803            result
1804        })
1805    }
1806
1807    pub fn to_async(&self) -> AsyncAppContext {
1808        AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
1809    }
1810
1811    pub fn write_to_clipboard(&self, item: ClipboardItem) {
1812        self.cx.platform.write_to_clipboard(item);
1813    }
1814
1815    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1816        self.cx.platform.read_from_clipboard()
1817    }
1818
1819    #[cfg(any(test, feature = "test-support"))]
1820    pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
1821        self.cx.ref_counts.lock().leak_detector.clone()
1822    }
1823}
1824
1825impl ReadModel for MutableAppContext {
1826    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1827        if let Some(model) = self.cx.models.get(&handle.model_id) {
1828            model
1829                .as_any()
1830                .downcast_ref()
1831                .expect("downcast is type safe")
1832        } else {
1833            panic!("circular model reference");
1834        }
1835    }
1836}
1837
1838impl UpdateModel for MutableAppContext {
1839    fn update_model<T: Entity, V>(
1840        &mut self,
1841        handle: &ModelHandle<T>,
1842        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
1843    ) -> V {
1844        if let Some(mut model) = self.cx.models.remove(&handle.model_id) {
1845            self.update(|this| {
1846                let mut cx = ModelContext::new(this, handle.model_id);
1847                let result = update(
1848                    model
1849                        .as_any_mut()
1850                        .downcast_mut()
1851                        .expect("downcast is type safe"),
1852                    &mut cx,
1853                );
1854                this.cx.models.insert(handle.model_id, model);
1855                result
1856            })
1857        } else {
1858            panic!("circular model update");
1859        }
1860    }
1861}
1862
1863impl UpgradeModelHandle for MutableAppContext {
1864    fn upgrade_model_handle<T: Entity>(
1865        &self,
1866        handle: &WeakModelHandle<T>,
1867    ) -> Option<ModelHandle<T>> {
1868        self.cx.upgrade_model_handle(handle)
1869    }
1870
1871    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
1872        self.cx.model_handle_is_upgradable(handle)
1873    }
1874
1875    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
1876        self.cx.upgrade_any_model_handle(handle)
1877    }
1878}
1879
1880impl UpgradeViewHandle for MutableAppContext {
1881    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
1882        self.cx.upgrade_view_handle(handle)
1883    }
1884}
1885
1886impl ReadView for MutableAppContext {
1887    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1888        if let Some(view) = self.cx.views.get(&(handle.window_id, handle.view_id)) {
1889            view.as_any().downcast_ref().expect("downcast is type safe")
1890        } else {
1891            panic!("circular view reference");
1892        }
1893    }
1894}
1895
1896impl UpdateView for MutableAppContext {
1897    fn update_view<T, S>(
1898        &mut self,
1899        handle: &ViewHandle<T>,
1900        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
1901    ) -> S
1902    where
1903        T: View,
1904    {
1905        self.update(|this| {
1906            let mut view = this
1907                .cx
1908                .views
1909                .remove(&(handle.window_id, handle.view_id))
1910                .expect("circular view update");
1911
1912            let mut cx = ViewContext::new(this, handle.window_id, handle.view_id);
1913            let result = update(
1914                view.as_any_mut()
1915                    .downcast_mut()
1916                    .expect("downcast is type safe"),
1917                &mut cx,
1918            );
1919            this.cx
1920                .views
1921                .insert((handle.window_id, handle.view_id), view);
1922            result
1923        })
1924    }
1925}
1926
1927impl AsRef<AppContext> for MutableAppContext {
1928    fn as_ref(&self) -> &AppContext {
1929        &self.cx
1930    }
1931}
1932
1933impl Deref for MutableAppContext {
1934    type Target = AppContext;
1935
1936    fn deref(&self) -> &Self::Target {
1937        &self.cx
1938    }
1939}
1940
1941pub struct AppContext {
1942    models: HashMap<usize, Box<dyn AnyModel>>,
1943    views: HashMap<(usize, usize), Box<dyn AnyView>>,
1944    windows: HashMap<usize, Window>,
1945    app_states: HashMap<TypeId, Box<dyn Any>>,
1946    element_states: HashMap<ElementStateId, Box<dyn Any>>,
1947    background: Arc<executor::Background>,
1948    ref_counts: Arc<Mutex<RefCounts>>,
1949    font_cache: Arc<FontCache>,
1950    platform: Arc<dyn Platform>,
1951}
1952
1953impl AppContext {
1954    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
1955        self.windows
1956            .get(&window_id)
1957            .map(|window| window.root_view.id())
1958    }
1959
1960    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
1961        self.windows
1962            .get(&window_id)
1963            .and_then(|window| window.focused_view_id)
1964    }
1965
1966    pub fn background(&self) -> &Arc<executor::Background> {
1967        &self.background
1968    }
1969
1970    pub fn font_cache(&self) -> &Arc<FontCache> {
1971        &self.font_cache
1972    }
1973
1974    pub fn platform(&self) -> &Arc<dyn Platform> {
1975        &self.platform
1976    }
1977
1978    pub fn app_state<T: 'static>(&self) -> &T {
1979        self.app_states
1980            .get(&TypeId::of::<T>())
1981            .expect("no app state has been added for this type")
1982            .downcast_ref()
1983            .unwrap()
1984    }
1985}
1986
1987impl ReadModel for AppContext {
1988    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1989        if let Some(model) = self.models.get(&handle.model_id) {
1990            model
1991                .as_any()
1992                .downcast_ref()
1993                .expect("downcast should be type safe")
1994        } else {
1995            panic!("circular model reference");
1996        }
1997    }
1998}
1999
2000impl UpgradeModelHandle for AppContext {
2001    fn upgrade_model_handle<T: Entity>(
2002        &self,
2003        handle: &WeakModelHandle<T>,
2004    ) -> Option<ModelHandle<T>> {
2005        if self.models.contains_key(&handle.model_id) {
2006            Some(ModelHandle::new(handle.model_id, &self.ref_counts))
2007        } else {
2008            None
2009        }
2010    }
2011
2012    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2013        self.models.contains_key(&handle.model_id)
2014    }
2015
2016    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2017        if self.models.contains_key(&handle.model_id) {
2018            Some(AnyModelHandle::new(
2019                handle.model_id,
2020                handle.model_type,
2021                self.ref_counts.clone(),
2022            ))
2023        } else {
2024            None
2025        }
2026    }
2027}
2028
2029impl UpgradeViewHandle for AppContext {
2030    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2031        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2032            Some(ViewHandle::new(
2033                handle.window_id,
2034                handle.view_id,
2035                &self.ref_counts,
2036            ))
2037        } else {
2038            None
2039        }
2040    }
2041}
2042
2043impl ReadView for AppContext {
2044    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2045        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
2046            view.as_any()
2047                .downcast_ref()
2048                .expect("downcast should be type safe")
2049        } else {
2050            panic!("circular view reference");
2051        }
2052    }
2053}
2054
2055struct Window {
2056    root_view: AnyViewHandle,
2057    focused_view_id: Option<usize>,
2058    invalidation: Option<WindowInvalidation>,
2059}
2060
2061#[derive(Default, Clone)]
2062pub struct WindowInvalidation {
2063    pub updated: HashSet<usize>,
2064    pub removed: Vec<usize>,
2065}
2066
2067pub enum Effect {
2068    Event {
2069        entity_id: usize,
2070        payload: Box<dyn Any>,
2071    },
2072    ModelNotification {
2073        model_id: usize,
2074    },
2075    ViewNotification {
2076        window_id: usize,
2077        view_id: usize,
2078    },
2079    Deferred(Box<dyn FnOnce(&mut MutableAppContext)>),
2080    Release {
2081        entity_id: usize,
2082    },
2083    Focus {
2084        window_id: usize,
2085        view_id: Option<usize>,
2086    },
2087    ResizeWindow {
2088        window_id: usize,
2089    },
2090    RefreshWindows,
2091}
2092
2093impl Debug for Effect {
2094    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2095        match self {
2096            Effect::Event { entity_id, .. } => f
2097                .debug_struct("Effect::Event")
2098                .field("entity_id", entity_id)
2099                .finish(),
2100            Effect::ModelNotification { model_id } => f
2101                .debug_struct("Effect::ModelNotification")
2102                .field("model_id", model_id)
2103                .finish(),
2104            Effect::ViewNotification { window_id, view_id } => f
2105                .debug_struct("Effect::ViewNotification")
2106                .field("window_id", window_id)
2107                .field("view_id", view_id)
2108                .finish(),
2109            Effect::Deferred(_) => f.debug_struct("Effect::Deferred").finish(),
2110            Effect::Release { entity_id } => f
2111                .debug_struct("Effect::Release")
2112                .field("entity_id", entity_id)
2113                .finish(),
2114            Effect::Focus { window_id, view_id } => f
2115                .debug_struct("Effect::Focus")
2116                .field("window_id", window_id)
2117                .field("view_id", view_id)
2118                .finish(),
2119            Effect::ResizeWindow { window_id } => f
2120                .debug_struct("Effect::RefreshWindow")
2121                .field("window_id", window_id)
2122                .finish(),
2123            Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
2124        }
2125    }
2126}
2127
2128pub trait AnyModel {
2129    fn as_any(&self) -> &dyn Any;
2130    fn as_any_mut(&mut self) -> &mut dyn Any;
2131    fn release(&mut self, cx: &mut MutableAppContext);
2132    fn app_will_quit(
2133        &mut self,
2134        cx: &mut MutableAppContext,
2135    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2136}
2137
2138impl<T> AnyModel for T
2139where
2140    T: Entity,
2141{
2142    fn as_any(&self) -> &dyn Any {
2143        self
2144    }
2145
2146    fn as_any_mut(&mut self) -> &mut dyn Any {
2147        self
2148    }
2149
2150    fn release(&mut self, cx: &mut MutableAppContext) {
2151        self.release(cx);
2152    }
2153
2154    fn app_will_quit(
2155        &mut self,
2156        cx: &mut MutableAppContext,
2157    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2158        self.app_will_quit(cx)
2159    }
2160}
2161
2162pub trait AnyView {
2163    fn as_any(&self) -> &dyn Any;
2164    fn as_any_mut(&mut self) -> &mut dyn Any;
2165    fn release(&mut self, cx: &mut MutableAppContext);
2166    fn app_will_quit(
2167        &mut self,
2168        cx: &mut MutableAppContext,
2169    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2170    fn ui_name(&self) -> &'static str;
2171    fn render<'a>(
2172        &mut self,
2173        window_id: usize,
2174        view_id: usize,
2175        titlebar_height: f32,
2176        refreshing: bool,
2177        cx: &mut MutableAppContext,
2178    ) -> ElementBox;
2179    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
2180    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
2181    fn keymap_context(&self, cx: &AppContext) -> keymap::Context;
2182}
2183
2184impl<T> AnyView for T
2185where
2186    T: View,
2187{
2188    fn as_any(&self) -> &dyn Any {
2189        self
2190    }
2191
2192    fn as_any_mut(&mut self) -> &mut dyn Any {
2193        self
2194    }
2195
2196    fn release(&mut self, cx: &mut MutableAppContext) {
2197        self.release(cx);
2198    }
2199
2200    fn app_will_quit(
2201        &mut self,
2202        cx: &mut MutableAppContext,
2203    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2204        self.app_will_quit(cx)
2205    }
2206
2207    fn ui_name(&self) -> &'static str {
2208        T::ui_name()
2209    }
2210
2211    fn render<'a>(
2212        &mut self,
2213        window_id: usize,
2214        view_id: usize,
2215        titlebar_height: f32,
2216        refreshing: bool,
2217        cx: &mut MutableAppContext,
2218    ) -> ElementBox {
2219        View::render(
2220            self,
2221            &mut RenderContext {
2222                window_id,
2223                view_id,
2224                app: cx,
2225                view_type: PhantomData::<T>,
2226                titlebar_height,
2227                refreshing,
2228            },
2229        )
2230    }
2231
2232    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
2233        let mut cx = ViewContext::new(cx, window_id, view_id);
2234        View::on_focus(self, &mut cx);
2235    }
2236
2237    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
2238        let mut cx = ViewContext::new(cx, window_id, view_id);
2239        View::on_blur(self, &mut cx);
2240    }
2241
2242    fn keymap_context(&self, cx: &AppContext) -> keymap::Context {
2243        View::keymap_context(self, cx)
2244    }
2245}
2246
2247pub struct ModelContext<'a, T: ?Sized> {
2248    app: &'a mut MutableAppContext,
2249    model_id: usize,
2250    model_type: PhantomData<T>,
2251    halt_stream: bool,
2252}
2253
2254impl<'a, T: Entity> ModelContext<'a, T> {
2255    fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
2256        Self {
2257            app,
2258            model_id,
2259            model_type: PhantomData,
2260            halt_stream: false,
2261        }
2262    }
2263
2264    pub fn background(&self) -> &Arc<executor::Background> {
2265        &self.app.cx.background
2266    }
2267
2268    pub fn halt_stream(&mut self) {
2269        self.halt_stream = true;
2270    }
2271
2272    pub fn model_id(&self) -> usize {
2273        self.model_id
2274    }
2275
2276    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2277    where
2278        S: Entity,
2279        F: FnOnce(&mut ModelContext<S>) -> S,
2280    {
2281        self.app.add_model(build_model)
2282    }
2283
2284    pub fn emit(&mut self, payload: T::Event) {
2285        self.app.pending_effects.push_back(Effect::Event {
2286            entity_id: self.model_id,
2287            payload: Box::new(payload),
2288        });
2289    }
2290
2291    pub fn notify(&mut self) {
2292        self.app.notify_model(self.model_id);
2293    }
2294
2295    pub fn subscribe<S: Entity, F>(
2296        &mut self,
2297        handle: &ModelHandle<S>,
2298        mut callback: F,
2299    ) -> Subscription
2300    where
2301        S::Event: 'static,
2302        F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
2303    {
2304        let subscriber = self.weak_handle();
2305        self.app
2306            .subscribe_internal(handle, move |emitter, event, cx| {
2307                if let Some(subscriber) = subscriber.upgrade(cx) {
2308                    subscriber.update(cx, |subscriber, cx| {
2309                        callback(subscriber, emitter, event, cx);
2310                    });
2311                    true
2312                } else {
2313                    false
2314                }
2315            })
2316    }
2317
2318    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
2319    where
2320        S: Entity,
2321        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
2322    {
2323        let observer = self.weak_handle();
2324        self.app.observe_internal(handle, move |observed, cx| {
2325            if let Some(observer) = observer.upgrade(cx) {
2326                observer.update(cx, |observer, cx| {
2327                    callback(observer, observed, cx);
2328                });
2329                true
2330            } else {
2331                false
2332            }
2333        })
2334    }
2335
2336    pub fn observe_release<S, F>(
2337        &mut self,
2338        handle: &ModelHandle<S>,
2339        mut callback: F,
2340    ) -> Subscription
2341    where
2342        S: Entity,
2343        F: 'static + FnMut(&mut T, &mut ModelContext<T>),
2344    {
2345        let observer = self.weak_handle();
2346        self.app.observe_release(handle, move |cx| {
2347            if let Some(observer) = observer.upgrade(cx) {
2348                observer.update(cx, |observer, cx| {
2349                    callback(observer, cx);
2350                });
2351            }
2352        })
2353    }
2354
2355    pub fn handle(&self) -> ModelHandle<T> {
2356        ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
2357    }
2358
2359    pub fn weak_handle(&self) -> WeakModelHandle<T> {
2360        WeakModelHandle::new(self.model_id)
2361    }
2362
2363    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2364    where
2365        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
2366        Fut: 'static + Future<Output = S>,
2367        S: 'static,
2368    {
2369        let handle = self.handle();
2370        self.app.spawn(|cx| f(handle, cx))
2371    }
2372
2373    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
2374    where
2375        F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
2376        Fut: 'static + Future<Output = S>,
2377        S: 'static,
2378    {
2379        let handle = self.weak_handle();
2380        self.app.spawn(|cx| f(handle, cx))
2381    }
2382}
2383
2384impl<M> AsRef<AppContext> for ModelContext<'_, M> {
2385    fn as_ref(&self) -> &AppContext {
2386        &self.app.cx
2387    }
2388}
2389
2390impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
2391    fn as_mut(&mut self) -> &mut MutableAppContext {
2392        self.app
2393    }
2394}
2395
2396impl<M> ReadModel for ModelContext<'_, M> {
2397    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2398        self.app.read_model(handle)
2399    }
2400}
2401
2402impl<M> UpdateModel for ModelContext<'_, M> {
2403    fn update_model<T: Entity, V>(
2404        &mut self,
2405        handle: &ModelHandle<T>,
2406        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
2407    ) -> V {
2408        self.app.update_model(handle, update)
2409    }
2410}
2411
2412impl<M> UpgradeModelHandle for ModelContext<'_, M> {
2413    fn upgrade_model_handle<T: Entity>(
2414        &self,
2415        handle: &WeakModelHandle<T>,
2416    ) -> Option<ModelHandle<T>> {
2417        self.cx.upgrade_model_handle(handle)
2418    }
2419
2420    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2421        self.cx.model_handle_is_upgradable(handle)
2422    }
2423
2424    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2425        self.cx.upgrade_any_model_handle(handle)
2426    }
2427}
2428
2429impl<M> Deref for ModelContext<'_, M> {
2430    type Target = MutableAppContext;
2431
2432    fn deref(&self) -> &Self::Target {
2433        &self.app
2434    }
2435}
2436
2437impl<M> DerefMut for ModelContext<'_, M> {
2438    fn deref_mut(&mut self) -> &mut Self::Target {
2439        &mut self.app
2440    }
2441}
2442
2443pub struct ViewContext<'a, T: ?Sized> {
2444    app: &'a mut MutableAppContext,
2445    window_id: usize,
2446    view_id: usize,
2447    view_type: PhantomData<T>,
2448}
2449
2450impl<'a, T: View> ViewContext<'a, T> {
2451    fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
2452        Self {
2453            app,
2454            window_id,
2455            view_id,
2456            view_type: PhantomData,
2457        }
2458    }
2459
2460    pub fn handle(&self) -> ViewHandle<T> {
2461        ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
2462    }
2463
2464    pub fn weak_handle(&self) -> WeakViewHandle<T> {
2465        WeakViewHandle::new(self.window_id, self.view_id)
2466    }
2467
2468    pub fn window_id(&self) -> usize {
2469        self.window_id
2470    }
2471
2472    pub fn view_id(&self) -> usize {
2473        self.view_id
2474    }
2475
2476    pub fn foreground(&self) -> &Rc<executor::Foreground> {
2477        self.app.foreground()
2478    }
2479
2480    pub fn background_executor(&self) -> &Arc<executor::Background> {
2481        &self.app.cx.background
2482    }
2483
2484    pub fn platform(&self) -> Arc<dyn Platform> {
2485        self.app.platform()
2486    }
2487
2488    pub fn prompt(
2489        &self,
2490        level: PromptLevel,
2491        msg: &str,
2492        answers: &[&str],
2493    ) -> oneshot::Receiver<usize> {
2494        self.app.prompt(self.window_id, level, msg, answers)
2495    }
2496
2497    pub fn prompt_for_paths(
2498        &self,
2499        options: PathPromptOptions,
2500    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2501        self.app.prompt_for_paths(options)
2502    }
2503
2504    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
2505        self.app.prompt_for_new_path(directory)
2506    }
2507
2508    pub fn debug_elements(&self) -> crate::json::Value {
2509        self.app.debug_elements(self.window_id).unwrap()
2510    }
2511
2512    pub fn focus<S>(&mut self, handle: S)
2513    where
2514        S: Into<AnyViewHandle>,
2515    {
2516        let handle = handle.into();
2517        self.app.pending_effects.push_back(Effect::Focus {
2518            window_id: handle.window_id,
2519            view_id: Some(handle.view_id),
2520        });
2521    }
2522
2523    pub fn focus_self(&mut self) {
2524        self.app.pending_effects.push_back(Effect::Focus {
2525            window_id: self.window_id,
2526            view_id: Some(self.view_id),
2527        });
2528    }
2529
2530    pub fn blur(&mut self) {
2531        self.app.pending_effects.push_back(Effect::Focus {
2532            window_id: self.window_id,
2533            view_id: None,
2534        });
2535    }
2536
2537    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2538    where
2539        S: Entity,
2540        F: FnOnce(&mut ModelContext<S>) -> S,
2541    {
2542        self.app.add_model(build_model)
2543    }
2544
2545    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
2546    where
2547        S: View,
2548        F: FnOnce(&mut ViewContext<S>) -> S,
2549    {
2550        self.app.add_view(self.window_id, build_view)
2551    }
2552
2553    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
2554    where
2555        S: View,
2556        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
2557    {
2558        self.app.add_option_view(self.window_id, build_view)
2559    }
2560
2561    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
2562    where
2563        E: Entity,
2564        E::Event: 'static,
2565        H: Handle<E>,
2566        F: 'static + FnMut(&mut T, H, &E::Event, &mut ViewContext<T>),
2567    {
2568        let subscriber = self.weak_handle();
2569        self.app
2570            .subscribe_internal(handle, move |emitter, event, cx| {
2571                if let Some(subscriber) = subscriber.upgrade(cx) {
2572                    subscriber.update(cx, |subscriber, cx| {
2573                        callback(subscriber, emitter, event, cx);
2574                    });
2575                    true
2576                } else {
2577                    false
2578                }
2579            })
2580    }
2581
2582    pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2583    where
2584        E: Entity,
2585        H: Handle<E>,
2586        F: 'static + FnMut(&mut T, H, &mut ViewContext<T>),
2587    {
2588        let observer = self.weak_handle();
2589        self.app.observe_internal(handle, move |observed, cx| {
2590            if let Some(observer) = observer.upgrade(cx) {
2591                observer.update(cx, |observer, cx| {
2592                    callback(observer, observed, cx);
2593                });
2594                true
2595            } else {
2596                false
2597            }
2598        })
2599    }
2600
2601    pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2602    where
2603        E: Entity,
2604        H: Handle<E>,
2605        F: 'static + FnMut(&mut T, &mut ViewContext<T>),
2606    {
2607        let observer = self.weak_handle();
2608        self.app.observe_release(handle, move |cx| {
2609            if let Some(observer) = observer.upgrade(cx) {
2610                observer.update(cx, |observer, cx| {
2611                    callback(observer, cx);
2612                });
2613            }
2614        })
2615    }
2616
2617    pub fn emit(&mut self, payload: T::Event) {
2618        self.app.pending_effects.push_back(Effect::Event {
2619            entity_id: self.view_id,
2620            payload: Box::new(payload),
2621        });
2622    }
2623
2624    pub fn notify(&mut self) {
2625        self.app.notify_view(self.window_id, self.view_id);
2626    }
2627
2628    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>)) {
2629        let handle = self.handle();
2630        self.app.defer(Box::new(move |cx| {
2631            handle.update(cx, |view, cx| {
2632                callback(view, cx);
2633            })
2634        }))
2635    }
2636
2637    pub fn propagate_action(&mut self) {
2638        self.app.halt_action_dispatch = false;
2639    }
2640
2641    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2642    where
2643        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
2644        Fut: 'static + Future<Output = S>,
2645        S: 'static,
2646    {
2647        let handle = self.handle();
2648        self.app.spawn(|cx| f(handle, cx))
2649    }
2650
2651    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
2652    where
2653        F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut,
2654        Fut: 'static + Future<Output = S>,
2655        S: 'static,
2656    {
2657        let handle = self.weak_handle();
2658        self.app.spawn(|cx| f(handle, cx))
2659    }
2660}
2661
2662pub struct RenderContext<'a, T: View> {
2663    pub app: &'a mut MutableAppContext,
2664    pub titlebar_height: f32,
2665    pub refreshing: bool,
2666    window_id: usize,
2667    view_id: usize,
2668    view_type: PhantomData<T>,
2669}
2670
2671impl<'a, T: View> RenderContext<'a, T> {
2672    pub fn handle(&self) -> WeakViewHandle<T> {
2673        WeakViewHandle::new(self.window_id, self.view_id)
2674    }
2675
2676    pub fn view_id(&self) -> usize {
2677        self.view_id
2678    }
2679}
2680
2681impl AsRef<AppContext> for &AppContext {
2682    fn as_ref(&self) -> &AppContext {
2683        self
2684    }
2685}
2686
2687impl<V: View> Deref for RenderContext<'_, V> {
2688    type Target = MutableAppContext;
2689
2690    fn deref(&self) -> &Self::Target {
2691        self.app
2692    }
2693}
2694
2695impl<V: View> DerefMut for RenderContext<'_, V> {
2696    fn deref_mut(&mut self) -> &mut Self::Target {
2697        self.app
2698    }
2699}
2700
2701impl<V: View> ReadModel for RenderContext<'_, V> {
2702    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2703        self.app.read_model(handle)
2704    }
2705}
2706
2707impl<V: View> UpdateModel for RenderContext<'_, V> {
2708    fn update_model<T: Entity, O>(
2709        &mut self,
2710        handle: &ModelHandle<T>,
2711        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
2712    ) -> O {
2713        self.app.update_model(handle, update)
2714    }
2715}
2716
2717impl<V: View> ReadView for RenderContext<'_, V> {
2718    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2719        self.app.read_view(handle)
2720    }
2721}
2722
2723impl<V: View> ElementStateContext for RenderContext<'_, V> {
2724    fn current_view_id(&self) -> usize {
2725        self.view_id
2726    }
2727}
2728
2729impl<M> AsRef<AppContext> for ViewContext<'_, M> {
2730    fn as_ref(&self) -> &AppContext {
2731        &self.app.cx
2732    }
2733}
2734
2735impl<M> Deref for ViewContext<'_, M> {
2736    type Target = MutableAppContext;
2737
2738    fn deref(&self) -> &Self::Target {
2739        &self.app
2740    }
2741}
2742
2743impl<M> DerefMut for ViewContext<'_, M> {
2744    fn deref_mut(&mut self) -> &mut Self::Target {
2745        &mut self.app
2746    }
2747}
2748
2749impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
2750    fn as_mut(&mut self) -> &mut MutableAppContext {
2751        self.app
2752    }
2753}
2754
2755impl<V> ReadModel for ViewContext<'_, V> {
2756    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2757        self.app.read_model(handle)
2758    }
2759}
2760
2761impl<V> UpgradeModelHandle for ViewContext<'_, V> {
2762    fn upgrade_model_handle<T: Entity>(
2763        &self,
2764        handle: &WeakModelHandle<T>,
2765    ) -> Option<ModelHandle<T>> {
2766        self.cx.upgrade_model_handle(handle)
2767    }
2768
2769    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2770        self.cx.model_handle_is_upgradable(handle)
2771    }
2772
2773    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2774        self.cx.upgrade_any_model_handle(handle)
2775    }
2776}
2777
2778impl<V> UpgradeViewHandle for ViewContext<'_, V> {
2779    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2780        self.cx.upgrade_view_handle(handle)
2781    }
2782}
2783
2784impl<V: View> UpdateModel for ViewContext<'_, V> {
2785    fn update_model<T: Entity, O>(
2786        &mut self,
2787        handle: &ModelHandle<T>,
2788        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
2789    ) -> O {
2790        self.app.update_model(handle, update)
2791    }
2792}
2793
2794impl<V: View> ReadView for ViewContext<'_, V> {
2795    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2796        self.app.read_view(handle)
2797    }
2798}
2799
2800impl<V: View> UpdateView for ViewContext<'_, V> {
2801    fn update_view<T, S>(
2802        &mut self,
2803        handle: &ViewHandle<T>,
2804        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
2805    ) -> S
2806    where
2807        T: View,
2808    {
2809        self.app.update_view(handle, update)
2810    }
2811}
2812
2813impl<V: View> ElementStateContext for ViewContext<'_, V> {
2814    fn current_view_id(&self) -> usize {
2815        self.view_id
2816    }
2817}
2818
2819pub trait Handle<T> {
2820    type Weak: 'static;
2821    fn id(&self) -> usize;
2822    fn location(&self) -> EntityLocation;
2823    fn downgrade(&self) -> Self::Weak;
2824    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2825    where
2826        Self: Sized;
2827}
2828
2829#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
2830pub enum EntityLocation {
2831    Model(usize),
2832    View(usize, usize),
2833}
2834
2835pub struct ModelHandle<T: Entity> {
2836    model_id: usize,
2837    model_type: PhantomData<T>,
2838    ref_counts: Arc<Mutex<RefCounts>>,
2839
2840    #[cfg(any(test, feature = "test-support"))]
2841    handle_id: usize,
2842}
2843
2844impl<T: Entity> ModelHandle<T> {
2845    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2846        ref_counts.lock().inc_model(model_id);
2847
2848        #[cfg(any(test, feature = "test-support"))]
2849        let handle_id = ref_counts
2850            .lock()
2851            .leak_detector
2852            .lock()
2853            .handle_created(Some(type_name::<T>()), model_id);
2854
2855        Self {
2856            model_id,
2857            model_type: PhantomData,
2858            ref_counts: ref_counts.clone(),
2859
2860            #[cfg(any(test, feature = "test-support"))]
2861            handle_id,
2862        }
2863    }
2864
2865    pub fn downgrade(&self) -> WeakModelHandle<T> {
2866        WeakModelHandle::new(self.model_id)
2867    }
2868
2869    pub fn id(&self) -> usize {
2870        self.model_id
2871    }
2872
2873    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
2874        cx.read_model(self)
2875    }
2876
2877    pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
2878    where
2879        C: ReadModelWith,
2880        F: FnOnce(&T, &AppContext) -> S,
2881    {
2882        let mut read = Some(read);
2883        cx.read_model_with(self, &mut |model, cx| {
2884            let read = read.take().unwrap();
2885            read(model, cx)
2886        })
2887    }
2888
2889    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2890    where
2891        C: UpdateModel,
2892        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2893    {
2894        let mut update = Some(update);
2895        cx.update_model(self, &mut |model, cx| {
2896            let update = update.take().unwrap();
2897            update(model, cx)
2898        })
2899    }
2900
2901    #[cfg(any(test, feature = "test-support"))]
2902    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
2903        use postage::prelude::{Sink as _, Stream as _};
2904
2905        let (mut tx, mut rx) = postage::mpsc::channel(1);
2906        let mut cx = cx.cx.borrow_mut();
2907        let subscription = cx.observe(self, move |_, _| {
2908            tx.try_send(()).ok();
2909        });
2910
2911        let duration = if std::env::var("CI").is_ok() {
2912            Duration::from_secs(5)
2913        } else {
2914            Duration::from_secs(1)
2915        };
2916
2917        async move {
2918            let notification = crate::util::timeout(duration, rx.recv())
2919                .await
2920                .expect("next notification timed out");
2921            drop(subscription);
2922            notification.expect("model dropped while test was waiting for its next notification")
2923        }
2924    }
2925
2926    #[cfg(any(test, feature = "test-support"))]
2927    pub fn next_event(&self, cx: &TestAppContext) -> impl Future<Output = T::Event>
2928    where
2929        T::Event: Clone,
2930    {
2931        use postage::prelude::{Sink as _, Stream as _};
2932
2933        let (mut tx, mut rx) = postage::mpsc::channel(1);
2934        let mut cx = cx.cx.borrow_mut();
2935        let subscription = cx.subscribe(self, move |_, event, _| {
2936            tx.blocking_send(event.clone()).ok();
2937        });
2938
2939        let duration = if std::env::var("CI").is_ok() {
2940            Duration::from_secs(5)
2941        } else {
2942            Duration::from_secs(1)
2943        };
2944
2945        async move {
2946            let event = crate::util::timeout(duration, rx.recv())
2947                .await
2948                .expect("next event timed out");
2949            drop(subscription);
2950            event.expect("model dropped while test was waiting for its next event")
2951        }
2952    }
2953
2954    #[cfg(any(test, feature = "test-support"))]
2955    pub fn condition(
2956        &self,
2957        cx: &TestAppContext,
2958        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2959    ) -> impl Future<Output = ()> {
2960        use postage::prelude::{Sink as _, Stream as _};
2961
2962        let (tx, mut rx) = postage::mpsc::channel(1024);
2963
2964        let mut cx = cx.cx.borrow_mut();
2965        let subscriptions = (
2966            cx.observe(self, {
2967                let mut tx = tx.clone();
2968                move |_, _| {
2969                    tx.blocking_send(()).ok();
2970                }
2971            }),
2972            cx.subscribe(self, {
2973                let mut tx = tx.clone();
2974                move |_, _, _| {
2975                    tx.blocking_send(()).ok();
2976                }
2977            }),
2978        );
2979
2980        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2981        let handle = self.downgrade();
2982        let duration = if std::env::var("CI").is_ok() {
2983            Duration::from_secs(5)
2984        } else {
2985            Duration::from_secs(1)
2986        };
2987
2988        async move {
2989            crate::util::timeout(duration, async move {
2990                loop {
2991                    {
2992                        let cx = cx.borrow();
2993                        let cx = cx.as_ref();
2994                        if predicate(
2995                            handle
2996                                .upgrade(cx)
2997                                .expect("model dropped with pending condition")
2998                                .read(cx),
2999                            cx,
3000                        ) {
3001                            break;
3002                        }
3003                    }
3004
3005                    cx.borrow().foreground().start_waiting();
3006                    rx.recv()
3007                        .await
3008                        .expect("model dropped with pending condition");
3009                    cx.borrow().foreground().finish_waiting();
3010                }
3011            })
3012            .await
3013            .expect("condition timed out");
3014            drop(subscriptions);
3015        }
3016    }
3017}
3018
3019impl<T: Entity> Clone for ModelHandle<T> {
3020    fn clone(&self) -> Self {
3021        Self::new(self.model_id, &self.ref_counts)
3022    }
3023}
3024
3025impl<T: Entity> PartialEq for ModelHandle<T> {
3026    fn eq(&self, other: &Self) -> bool {
3027        self.model_id == other.model_id
3028    }
3029}
3030
3031impl<T: Entity> Eq for ModelHandle<T> {}
3032
3033impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
3034    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
3035        self.model_id == other.model_id
3036    }
3037}
3038
3039impl<T: Entity> Hash for ModelHandle<T> {
3040    fn hash<H: Hasher>(&self, state: &mut H) {
3041        self.model_id.hash(state);
3042    }
3043}
3044
3045impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
3046    fn borrow(&self) -> &usize {
3047        &self.model_id
3048    }
3049}
3050
3051impl<T: Entity> Debug for ModelHandle<T> {
3052    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3053        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
3054            .field(&self.model_id)
3055            .finish()
3056    }
3057}
3058
3059unsafe impl<T: Entity> Send for ModelHandle<T> {}
3060unsafe impl<T: Entity> Sync for ModelHandle<T> {}
3061
3062impl<T: Entity> Drop for ModelHandle<T> {
3063    fn drop(&mut self) {
3064        let mut ref_counts = self.ref_counts.lock();
3065        ref_counts.dec_model(self.model_id);
3066
3067        #[cfg(any(test, feature = "test-support"))]
3068        ref_counts
3069            .leak_detector
3070            .lock()
3071            .handle_dropped(self.model_id, self.handle_id);
3072    }
3073}
3074
3075impl<T: Entity> Handle<T> for ModelHandle<T> {
3076    type Weak = WeakModelHandle<T>;
3077
3078    fn id(&self) -> usize {
3079        self.model_id
3080    }
3081
3082    fn location(&self) -> EntityLocation {
3083        EntityLocation::Model(self.model_id)
3084    }
3085
3086    fn downgrade(&self) -> Self::Weak {
3087        self.downgrade()
3088    }
3089
3090    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3091    where
3092        Self: Sized,
3093    {
3094        weak.upgrade(cx)
3095    }
3096}
3097
3098pub struct WeakModelHandle<T> {
3099    model_id: usize,
3100    model_type: PhantomData<T>,
3101}
3102
3103unsafe impl<T> Send for WeakModelHandle<T> {}
3104unsafe impl<T> Sync for WeakModelHandle<T> {}
3105
3106impl<T: Entity> WeakModelHandle<T> {
3107    fn new(model_id: usize) -> Self {
3108        Self {
3109            model_id,
3110            model_type: PhantomData,
3111        }
3112    }
3113
3114    pub fn id(&self) -> usize {
3115        self.model_id
3116    }
3117
3118    pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
3119        cx.model_handle_is_upgradable(self)
3120    }
3121
3122    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
3123        cx.upgrade_model_handle(self)
3124    }
3125}
3126
3127impl<T> Hash for WeakModelHandle<T> {
3128    fn hash<H: Hasher>(&self, state: &mut H) {
3129        self.model_id.hash(state)
3130    }
3131}
3132
3133impl<T> PartialEq for WeakModelHandle<T> {
3134    fn eq(&self, other: &Self) -> bool {
3135        self.model_id == other.model_id
3136    }
3137}
3138
3139impl<T> Eq for WeakModelHandle<T> {}
3140
3141impl<T> Clone for WeakModelHandle<T> {
3142    fn clone(&self) -> Self {
3143        Self {
3144            model_id: self.model_id,
3145            model_type: PhantomData,
3146        }
3147    }
3148}
3149
3150impl<T> Copy for WeakModelHandle<T> {}
3151
3152pub struct ViewHandle<T> {
3153    window_id: usize,
3154    view_id: usize,
3155    view_type: PhantomData<T>,
3156    ref_counts: Arc<Mutex<RefCounts>>,
3157    #[cfg(any(test, feature = "test-support"))]
3158    handle_id: usize,
3159}
3160
3161impl<T: View> ViewHandle<T> {
3162    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3163        ref_counts.lock().inc_view(window_id, view_id);
3164        #[cfg(any(test, feature = "test-support"))]
3165        let handle_id = ref_counts
3166            .lock()
3167            .leak_detector
3168            .lock()
3169            .handle_created(Some(type_name::<T>()), view_id);
3170
3171        Self {
3172            window_id,
3173            view_id,
3174            view_type: PhantomData,
3175            ref_counts: ref_counts.clone(),
3176
3177            #[cfg(any(test, feature = "test-support"))]
3178            handle_id,
3179        }
3180    }
3181
3182    pub fn downgrade(&self) -> WeakViewHandle<T> {
3183        WeakViewHandle::new(self.window_id, self.view_id)
3184    }
3185
3186    pub fn window_id(&self) -> usize {
3187        self.window_id
3188    }
3189
3190    pub fn id(&self) -> usize {
3191        self.view_id
3192    }
3193
3194    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
3195        cx.read_view(self)
3196    }
3197
3198    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3199    where
3200        C: ReadViewWith,
3201        F: FnOnce(&T, &AppContext) -> S,
3202    {
3203        let mut read = Some(read);
3204        cx.read_view_with(self, &mut |view, cx| {
3205            let read = read.take().unwrap();
3206            read(view, cx)
3207        })
3208    }
3209
3210    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3211    where
3212        C: UpdateView,
3213        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
3214    {
3215        let mut update = Some(update);
3216        cx.update_view(self, &mut |view, cx| {
3217            let update = update.take().unwrap();
3218            update(view, cx)
3219        })
3220    }
3221
3222    pub fn defer<C, F>(&self, cx: &mut C, update: F)
3223    where
3224        C: AsMut<MutableAppContext>,
3225        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
3226    {
3227        let this = self.clone();
3228        cx.as_mut().defer(Box::new(move |cx| {
3229            this.update(cx, |view, cx| update(view, cx));
3230        }));
3231    }
3232
3233    pub fn is_focused(&self, cx: &AppContext) -> bool {
3234        cx.focused_view_id(self.window_id)
3235            .map_or(false, |focused_id| focused_id == self.view_id)
3236    }
3237
3238    #[cfg(any(test, feature = "test-support"))]
3239    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
3240        use postage::prelude::{Sink as _, Stream as _};
3241
3242        let (mut tx, mut rx) = postage::mpsc::channel(1);
3243        let mut cx = cx.cx.borrow_mut();
3244        let subscription = cx.observe(self, move |_, _| {
3245            tx.try_send(()).ok();
3246        });
3247
3248        let duration = if std::env::var("CI").is_ok() {
3249            Duration::from_secs(5)
3250        } else {
3251            Duration::from_secs(1)
3252        };
3253
3254        async move {
3255            let notification = crate::util::timeout(duration, rx.recv())
3256                .await
3257                .expect("next notification timed out");
3258            drop(subscription);
3259            notification.expect("model dropped while test was waiting for its next notification")
3260        }
3261    }
3262
3263    #[cfg(any(test, feature = "test-support"))]
3264    pub fn condition(
3265        &self,
3266        cx: &TestAppContext,
3267        mut predicate: impl FnMut(&T, &AppContext) -> bool,
3268    ) -> impl Future<Output = ()> {
3269        use postage::prelude::{Sink as _, Stream as _};
3270
3271        let (tx, mut rx) = postage::mpsc::channel(1024);
3272
3273        let mut cx = cx.cx.borrow_mut();
3274        let subscriptions = self.update(&mut *cx, |_, cx| {
3275            (
3276                cx.observe(self, {
3277                    let mut tx = tx.clone();
3278                    move |_, _, _| {
3279                        tx.blocking_send(()).ok();
3280                    }
3281                }),
3282                cx.subscribe(self, {
3283                    let mut tx = tx.clone();
3284                    move |_, _, _, _| {
3285                        tx.blocking_send(()).ok();
3286                    }
3287                }),
3288            )
3289        });
3290
3291        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
3292        let handle = self.downgrade();
3293        let duration = if std::env::var("CI").is_ok() {
3294            Duration::from_secs(2)
3295        } else {
3296            Duration::from_millis(500)
3297        };
3298
3299        async move {
3300            crate::util::timeout(duration, async move {
3301                loop {
3302                    {
3303                        let cx = cx.borrow();
3304                        let cx = cx.as_ref();
3305                        if predicate(
3306                            handle
3307                                .upgrade(cx)
3308                                .expect("view dropped with pending condition")
3309                                .read(cx),
3310                            cx,
3311                        ) {
3312                            break;
3313                        }
3314                    }
3315
3316                    cx.borrow().foreground().start_waiting();
3317                    rx.recv()
3318                        .await
3319                        .expect("view dropped with pending condition");
3320                    cx.borrow().foreground().finish_waiting();
3321                }
3322            })
3323            .await
3324            .expect("condition timed out");
3325            drop(subscriptions);
3326        }
3327    }
3328}
3329
3330impl<T: View> Clone for ViewHandle<T> {
3331    fn clone(&self) -> Self {
3332        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
3333    }
3334}
3335
3336impl<T> PartialEq for ViewHandle<T> {
3337    fn eq(&self, other: &Self) -> bool {
3338        self.window_id == other.window_id && self.view_id == other.view_id
3339    }
3340}
3341
3342impl<T> Eq for ViewHandle<T> {}
3343
3344impl<T> Debug for ViewHandle<T> {
3345    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3346        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
3347            .field("window_id", &self.window_id)
3348            .field("view_id", &self.view_id)
3349            .finish()
3350    }
3351}
3352
3353impl<T> Drop for ViewHandle<T> {
3354    fn drop(&mut self) {
3355        self.ref_counts
3356            .lock()
3357            .dec_view(self.window_id, self.view_id);
3358        #[cfg(any(test, feature = "test-support"))]
3359        self.ref_counts
3360            .lock()
3361            .leak_detector
3362            .lock()
3363            .handle_dropped(self.view_id, self.handle_id);
3364    }
3365}
3366
3367impl<T: View> Handle<T> for ViewHandle<T> {
3368    type Weak = WeakViewHandle<T>;
3369
3370    fn id(&self) -> usize {
3371        self.view_id
3372    }
3373
3374    fn location(&self) -> EntityLocation {
3375        EntityLocation::View(self.window_id, self.view_id)
3376    }
3377
3378    fn downgrade(&self) -> Self::Weak {
3379        self.downgrade()
3380    }
3381
3382    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3383    where
3384        Self: Sized,
3385    {
3386        weak.upgrade(cx)
3387    }
3388}
3389
3390pub struct AnyViewHandle {
3391    window_id: usize,
3392    view_id: usize,
3393    view_type: TypeId,
3394    ref_counts: Arc<Mutex<RefCounts>>,
3395
3396    #[cfg(any(test, feature = "test-support"))]
3397    handle_id: usize,
3398}
3399
3400impl AnyViewHandle {
3401    fn new(
3402        window_id: usize,
3403        view_id: usize,
3404        view_type: TypeId,
3405        ref_counts: Arc<Mutex<RefCounts>>,
3406    ) -> Self {
3407        ref_counts.lock().inc_view(window_id, view_id);
3408
3409        #[cfg(any(test, feature = "test-support"))]
3410        let handle_id = ref_counts
3411            .lock()
3412            .leak_detector
3413            .lock()
3414            .handle_created(None, view_id);
3415
3416        Self {
3417            window_id,
3418            view_id,
3419            view_type,
3420            ref_counts,
3421            #[cfg(any(test, feature = "test-support"))]
3422            handle_id,
3423        }
3424    }
3425
3426    pub fn id(&self) -> usize {
3427        self.view_id
3428    }
3429
3430    pub fn is<T: 'static>(&self) -> bool {
3431        TypeId::of::<T>() == self.view_type
3432    }
3433
3434    pub fn is_focused(&self, cx: &AppContext) -> bool {
3435        cx.focused_view_id(self.window_id)
3436            .map_or(false, |focused_id| focused_id == self.view_id)
3437    }
3438
3439    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
3440        if self.is::<T>() {
3441            let result = Some(ViewHandle {
3442                window_id: self.window_id,
3443                view_id: self.view_id,
3444                ref_counts: self.ref_counts.clone(),
3445                view_type: PhantomData,
3446                #[cfg(any(test, feature = "test-support"))]
3447                handle_id: self.handle_id,
3448            });
3449            unsafe {
3450                Arc::decrement_strong_count(&self.ref_counts);
3451            }
3452            std::mem::forget(self);
3453            result
3454        } else {
3455            None
3456        }
3457    }
3458}
3459
3460impl Clone for AnyViewHandle {
3461    fn clone(&self) -> Self {
3462        Self::new(
3463            self.window_id,
3464            self.view_id,
3465            self.view_type,
3466            self.ref_counts.clone(),
3467        )
3468    }
3469}
3470
3471impl From<&AnyViewHandle> for AnyViewHandle {
3472    fn from(handle: &AnyViewHandle) -> Self {
3473        handle.clone()
3474    }
3475}
3476
3477impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
3478    fn from(handle: &ViewHandle<T>) -> Self {
3479        Self::new(
3480            handle.window_id,
3481            handle.view_id,
3482            TypeId::of::<T>(),
3483            handle.ref_counts.clone(),
3484        )
3485    }
3486}
3487
3488impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
3489    fn from(handle: ViewHandle<T>) -> Self {
3490        let any_handle = AnyViewHandle {
3491            window_id: handle.window_id,
3492            view_id: handle.view_id,
3493            view_type: TypeId::of::<T>(),
3494            ref_counts: handle.ref_counts.clone(),
3495            #[cfg(any(test, feature = "test-support"))]
3496            handle_id: handle.handle_id,
3497        };
3498        unsafe {
3499            Arc::decrement_strong_count(&handle.ref_counts);
3500        }
3501        std::mem::forget(handle);
3502        any_handle
3503    }
3504}
3505
3506impl Drop for AnyViewHandle {
3507    fn drop(&mut self) {
3508        self.ref_counts
3509            .lock()
3510            .dec_view(self.window_id, self.view_id);
3511        #[cfg(any(test, feature = "test-support"))]
3512        self.ref_counts
3513            .lock()
3514            .leak_detector
3515            .lock()
3516            .handle_dropped(self.view_id, self.handle_id);
3517    }
3518}
3519
3520pub struct AnyModelHandle {
3521    model_id: usize,
3522    model_type: TypeId,
3523    ref_counts: Arc<Mutex<RefCounts>>,
3524
3525    #[cfg(any(test, feature = "test-support"))]
3526    handle_id: usize,
3527}
3528
3529impl AnyModelHandle {
3530    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
3531        ref_counts.lock().inc_model(model_id);
3532
3533        #[cfg(any(test, feature = "test-support"))]
3534        let handle_id = ref_counts
3535            .lock()
3536            .leak_detector
3537            .lock()
3538            .handle_created(None, model_id);
3539
3540        Self {
3541            model_id,
3542            model_type,
3543            ref_counts,
3544
3545            #[cfg(any(test, feature = "test-support"))]
3546            handle_id,
3547        }
3548    }
3549
3550    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
3551        if self.is::<T>() {
3552            let result = Some(ModelHandle {
3553                model_id: self.model_id,
3554                model_type: PhantomData,
3555                ref_counts: self.ref_counts.clone(),
3556
3557                #[cfg(any(test, feature = "test-support"))]
3558                handle_id: self.handle_id,
3559            });
3560            unsafe {
3561                Arc::decrement_strong_count(&self.ref_counts);
3562            }
3563            std::mem::forget(self);
3564            result
3565        } else {
3566            None
3567        }
3568    }
3569
3570    pub fn downgrade(&self) -> AnyWeakModelHandle {
3571        AnyWeakModelHandle {
3572            model_id: self.model_id,
3573            model_type: self.model_type,
3574        }
3575    }
3576
3577    pub fn is<T: Entity>(&self) -> bool {
3578        self.model_type == TypeId::of::<T>()
3579    }
3580}
3581
3582impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
3583    fn from(handle: ModelHandle<T>) -> Self {
3584        Self::new(
3585            handle.model_id,
3586            TypeId::of::<T>(),
3587            handle.ref_counts.clone(),
3588        )
3589    }
3590}
3591
3592impl Clone for AnyModelHandle {
3593    fn clone(&self) -> Self {
3594        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
3595    }
3596}
3597
3598impl Drop for AnyModelHandle {
3599    fn drop(&mut self) {
3600        let mut ref_counts = self.ref_counts.lock();
3601        ref_counts.dec_model(self.model_id);
3602
3603        #[cfg(any(test, feature = "test-support"))]
3604        ref_counts
3605            .leak_detector
3606            .lock()
3607            .handle_dropped(self.model_id, self.handle_id);
3608    }
3609}
3610
3611pub struct AnyWeakModelHandle {
3612    model_id: usize,
3613    model_type: TypeId,
3614}
3615
3616impl AnyWeakModelHandle {
3617    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
3618        cx.upgrade_any_model_handle(self)
3619    }
3620}
3621
3622impl<T: Entity> From<WeakModelHandle<T>> for AnyWeakModelHandle {
3623    fn from(handle: WeakModelHandle<T>) -> Self {
3624        AnyWeakModelHandle {
3625            model_id: handle.model_id,
3626            model_type: TypeId::of::<T>(),
3627        }
3628    }
3629}
3630
3631pub struct WeakViewHandle<T> {
3632    window_id: usize,
3633    view_id: usize,
3634    view_type: PhantomData<T>,
3635}
3636
3637impl<T: View> WeakViewHandle<T> {
3638    fn new(window_id: usize, view_id: usize) -> Self {
3639        Self {
3640            window_id,
3641            view_id,
3642            view_type: PhantomData,
3643        }
3644    }
3645
3646    pub fn id(&self) -> usize {
3647        self.view_id
3648    }
3649
3650    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
3651        cx.upgrade_view_handle(self)
3652    }
3653}
3654
3655impl<T> Clone for WeakViewHandle<T> {
3656    fn clone(&self) -> Self {
3657        Self {
3658            window_id: self.window_id,
3659            view_id: self.view_id,
3660            view_type: PhantomData,
3661        }
3662    }
3663}
3664
3665impl<T> PartialEq for WeakViewHandle<T> {
3666    fn eq(&self, other: &Self) -> bool {
3667        self.window_id == other.window_id && self.view_id == other.view_id
3668    }
3669}
3670
3671impl<T> Eq for WeakViewHandle<T> {}
3672
3673impl<T> Hash for WeakViewHandle<T> {
3674    fn hash<H: Hasher>(&self, state: &mut H) {
3675        self.window_id.hash(state);
3676        self.view_id.hash(state);
3677    }
3678}
3679
3680#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3681pub struct ElementStateId {
3682    view_id: usize,
3683    element_id: usize,
3684    tag: TypeId,
3685}
3686
3687pub struct ElementStateHandle<T> {
3688    value_type: PhantomData<T>,
3689    id: ElementStateId,
3690    ref_counts: Weak<Mutex<RefCounts>>,
3691}
3692
3693impl<T: 'static> ElementStateHandle<T> {
3694    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3695        ref_counts.lock().inc_element_state(id, frame_id);
3696        Self {
3697            value_type: PhantomData,
3698            id,
3699            ref_counts: Arc::downgrade(ref_counts),
3700        }
3701    }
3702
3703    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3704        cx.element_states
3705            .get(&self.id)
3706            .unwrap()
3707            .downcast_ref()
3708            .unwrap()
3709    }
3710
3711    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
3712    where
3713        C: DerefMut<Target = MutableAppContext>,
3714    {
3715        let mut element_state = cx.deref_mut().cx.element_states.remove(&self.id).unwrap();
3716        let result = f(element_state.downcast_mut().unwrap(), cx);
3717        cx.deref_mut()
3718            .cx
3719            .element_states
3720            .insert(self.id, element_state);
3721        result
3722    }
3723}
3724
3725impl<T> Drop for ElementStateHandle<T> {
3726    fn drop(&mut self) {
3727        if let Some(ref_counts) = self.ref_counts.upgrade() {
3728            ref_counts.lock().dec_element_state(self.id);
3729        }
3730    }
3731}
3732
3733pub struct CursorStyleHandle {
3734    id: usize,
3735    next_cursor_style_handle_id: Arc<AtomicUsize>,
3736    platform: Arc<dyn Platform>,
3737}
3738
3739impl Drop for CursorStyleHandle {
3740    fn drop(&mut self) {
3741        if self.id + 1 == self.next_cursor_style_handle_id.load(SeqCst) {
3742            self.platform.set_cursor_style(CursorStyle::Arrow);
3743        }
3744    }
3745}
3746
3747#[must_use]
3748pub enum Subscription {
3749    Subscription {
3750        id: usize,
3751        entity_id: usize,
3752        subscriptions: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>>,
3753    },
3754    Observation {
3755        id: usize,
3756        entity_id: usize,
3757        observations: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ObservationCallback>>>>>,
3758    },
3759    ReleaseObservation {
3760        id: usize,
3761        entity_id: usize,
3762        observations:
3763            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>>,
3764    },
3765}
3766
3767impl Subscription {
3768    pub fn detach(&mut self) {
3769        match self {
3770            Subscription::Subscription { subscriptions, .. } => {
3771                subscriptions.take();
3772            }
3773            Subscription::Observation { observations, .. } => {
3774                observations.take();
3775            }
3776            Subscription::ReleaseObservation { observations, .. } => {
3777                observations.take();
3778            }
3779        }
3780    }
3781}
3782
3783impl Drop for Subscription {
3784    fn drop(&mut self) {
3785        match self {
3786            Subscription::Observation {
3787                id,
3788                entity_id,
3789                observations,
3790            } => {
3791                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3792                    if let Some(observations) = observations.lock().get_mut(entity_id) {
3793                        observations.remove(id);
3794                    }
3795                }
3796            }
3797            Subscription::ReleaseObservation {
3798                id,
3799                entity_id,
3800                observations,
3801            } => {
3802                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3803                    if let Some(observations) = observations.lock().get_mut(entity_id) {
3804                        observations.remove(id);
3805                    }
3806                }
3807            }
3808            Subscription::Subscription {
3809                id,
3810                entity_id,
3811                subscriptions,
3812            } => {
3813                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
3814                    if let Some(subscriptions) = subscriptions.lock().get_mut(entity_id) {
3815                        subscriptions.remove(id);
3816                    }
3817                }
3818            }
3819        }
3820    }
3821}
3822
3823lazy_static! {
3824    static ref LEAK_BACKTRACE: bool =
3825        std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty());
3826}
3827
3828#[cfg(any(test, feature = "test-support"))]
3829#[derive(Default)]
3830pub struct LeakDetector {
3831    next_handle_id: usize,
3832    handle_backtraces: HashMap<
3833        usize,
3834        (
3835            Option<&'static str>,
3836            HashMap<usize, Option<backtrace::Backtrace>>,
3837        ),
3838    >,
3839}
3840
3841#[cfg(any(test, feature = "test-support"))]
3842impl LeakDetector {
3843    fn handle_created(&mut self, type_name: Option<&'static str>, entity_id: usize) -> usize {
3844        let handle_id = post_inc(&mut self.next_handle_id);
3845        let entry = self.handle_backtraces.entry(entity_id).or_default();
3846        let backtrace = if *LEAK_BACKTRACE {
3847            Some(backtrace::Backtrace::new_unresolved())
3848        } else {
3849            None
3850        };
3851        if let Some(type_name) = type_name {
3852            entry.0.get_or_insert(type_name);
3853        }
3854        entry.1.insert(handle_id, backtrace);
3855        handle_id
3856    }
3857
3858    fn handle_dropped(&mut self, entity_id: usize, handle_id: usize) {
3859        if let Some((_, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
3860            assert!(backtraces.remove(&handle_id).is_some());
3861            if backtraces.is_empty() {
3862                self.handle_backtraces.remove(&entity_id);
3863            }
3864        }
3865    }
3866
3867    pub fn detect(&mut self) {
3868        let mut found_leaks = false;
3869        for (id, (type_name, backtraces)) in self.handle_backtraces.iter_mut() {
3870            eprintln!(
3871                "leaked {} handles to {:?} {}",
3872                backtraces.len(),
3873                type_name.unwrap_or("entity"),
3874                id
3875            );
3876            for trace in backtraces.values_mut() {
3877                if let Some(trace) = trace {
3878                    trace.resolve();
3879                    eprintln!("{:?}", crate::util::CwdBacktrace(trace));
3880                }
3881            }
3882            found_leaks = true;
3883        }
3884
3885        let hint = if *LEAK_BACKTRACE {
3886            ""
3887        } else {
3888            " – set LEAK_BACKTRACE=1 for more information"
3889        };
3890        assert!(!found_leaks, "detected leaked handles{}", hint);
3891    }
3892}
3893
3894#[derive(Default)]
3895struct RefCounts {
3896    entity_counts: HashMap<usize, usize>,
3897    element_state_counts: HashMap<ElementStateId, ElementStateRefCount>,
3898    dropped_models: HashSet<usize>,
3899    dropped_views: HashSet<(usize, usize)>,
3900    dropped_element_states: HashSet<ElementStateId>,
3901
3902    #[cfg(any(test, feature = "test-support"))]
3903    leak_detector: Arc<Mutex<LeakDetector>>,
3904}
3905
3906struct ElementStateRefCount {
3907    ref_count: usize,
3908    frame_id: usize,
3909}
3910
3911impl RefCounts {
3912    fn inc_model(&mut self, model_id: usize) {
3913        match self.entity_counts.entry(model_id) {
3914            Entry::Occupied(mut entry) => {
3915                *entry.get_mut() += 1;
3916            }
3917            Entry::Vacant(entry) => {
3918                entry.insert(1);
3919                self.dropped_models.remove(&model_id);
3920            }
3921        }
3922    }
3923
3924    fn inc_view(&mut self, window_id: usize, view_id: usize) {
3925        match self.entity_counts.entry(view_id) {
3926            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3927            Entry::Vacant(entry) => {
3928                entry.insert(1);
3929                self.dropped_views.remove(&(window_id, view_id));
3930            }
3931        }
3932    }
3933
3934    fn inc_element_state(&mut self, id: ElementStateId, frame_id: usize) {
3935        match self.element_state_counts.entry(id) {
3936            Entry::Occupied(mut entry) => {
3937                let entry = entry.get_mut();
3938                if entry.frame_id == frame_id || entry.ref_count >= 2 {
3939                    panic!("used the same element state more than once in the same frame");
3940                }
3941                entry.ref_count += 1;
3942                entry.frame_id = frame_id;
3943            }
3944            Entry::Vacant(entry) => {
3945                entry.insert(ElementStateRefCount {
3946                    ref_count: 1,
3947                    frame_id,
3948                });
3949                self.dropped_element_states.remove(&id);
3950            }
3951        }
3952    }
3953
3954    fn dec_model(&mut self, model_id: usize) {
3955        let count = self.entity_counts.get_mut(&model_id).unwrap();
3956        *count -= 1;
3957        if *count == 0 {
3958            self.entity_counts.remove(&model_id);
3959            self.dropped_models.insert(model_id);
3960        }
3961    }
3962
3963    fn dec_view(&mut self, window_id: usize, view_id: usize) {
3964        let count = self.entity_counts.get_mut(&view_id).unwrap();
3965        *count -= 1;
3966        if *count == 0 {
3967            self.entity_counts.remove(&view_id);
3968            self.dropped_views.insert((window_id, view_id));
3969        }
3970    }
3971
3972    fn dec_element_state(&mut self, id: ElementStateId) {
3973        let entry = self.element_state_counts.get_mut(&id).unwrap();
3974        entry.ref_count -= 1;
3975        if entry.ref_count == 0 {
3976            self.element_state_counts.remove(&id);
3977            self.dropped_element_states.insert(id);
3978        }
3979    }
3980
3981    fn is_entity_alive(&self, entity_id: usize) -> bool {
3982        self.entity_counts.contains_key(&entity_id)
3983    }
3984
3985    fn take_dropped(
3986        &mut self,
3987    ) -> (
3988        HashSet<usize>,
3989        HashSet<(usize, usize)>,
3990        HashSet<ElementStateId>,
3991    ) {
3992        (
3993            std::mem::take(&mut self.dropped_models),
3994            std::mem::take(&mut self.dropped_views),
3995            std::mem::take(&mut self.dropped_element_states),
3996        )
3997    }
3998}
3999
4000#[cfg(test)]
4001mod tests {
4002    use super::*;
4003    use crate::elements::*;
4004    use smol::future::poll_once;
4005    use std::{
4006        cell::Cell,
4007        sync::atomic::{AtomicUsize, Ordering::SeqCst},
4008    };
4009
4010    #[crate::test(self)]
4011    fn test_model_handles(cx: &mut MutableAppContext) {
4012        struct Model {
4013            other: Option<ModelHandle<Model>>,
4014            events: Vec<String>,
4015        }
4016
4017        impl Entity for Model {
4018            type Event = usize;
4019        }
4020
4021        impl Model {
4022            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
4023                if let Some(other) = other.as_ref() {
4024                    cx.observe(other, |me, _, _| {
4025                        me.events.push("notified".into());
4026                    })
4027                    .detach();
4028                    cx.subscribe(other, |me, _, event, _| {
4029                        me.events.push(format!("observed event {}", event));
4030                    })
4031                    .detach();
4032                }
4033
4034                Self {
4035                    other,
4036                    events: Vec::new(),
4037                }
4038            }
4039        }
4040
4041        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
4042        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
4043        assert_eq!(cx.cx.models.len(), 2);
4044
4045        handle_1.update(cx, |model, cx| {
4046            model.events.push("updated".into());
4047            cx.emit(1);
4048            cx.notify();
4049            cx.emit(2);
4050        });
4051        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4052        assert_eq!(
4053            handle_2.read(cx).events,
4054            vec![
4055                "observed event 1".to_string(),
4056                "notified".to_string(),
4057                "observed event 2".to_string(),
4058            ]
4059        );
4060
4061        handle_2.update(cx, |model, _| {
4062            drop(handle_1);
4063            model.other.take();
4064        });
4065
4066        assert_eq!(cx.cx.models.len(), 1);
4067        assert!(cx.subscriptions.lock().is_empty());
4068        assert!(cx.observations.lock().is_empty());
4069    }
4070
4071    #[crate::test(self)]
4072    fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) {
4073        #[derive(Default)]
4074        struct Model {
4075            events: Vec<usize>,
4076        }
4077
4078        impl Entity for Model {
4079            type Event = usize;
4080        }
4081
4082        let handle_1 = cx.add_model(|_| Model::default());
4083        let handle_2 = cx.add_model(|_| Model::default());
4084        handle_1.update(cx, |_, c| {
4085            c.subscribe(&handle_2, move |model: &mut Model, emitter, event, c| {
4086                model.events.push(*event);
4087
4088                c.subscribe(&emitter, |model, _, event, _| {
4089                    model.events.push(*event * 2);
4090                })
4091                .detach();
4092            })
4093            .detach();
4094        });
4095
4096        handle_2.update(cx, |_, c| c.emit(7));
4097        assert_eq!(handle_1.read(cx).events, vec![7]);
4098
4099        handle_2.update(cx, |_, c| c.emit(5));
4100        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4101    }
4102
4103    #[crate::test(self)]
4104    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
4105        #[derive(Default)]
4106        struct Model {
4107            count: usize,
4108            events: Vec<usize>,
4109        }
4110
4111        impl Entity for Model {
4112            type Event = ();
4113        }
4114
4115        let handle_1 = cx.add_model(|_| Model::default());
4116        let handle_2 = cx.add_model(|_| Model::default());
4117
4118        handle_1.update(cx, |_, c| {
4119            c.observe(&handle_2, move |model, observed, c| {
4120                model.events.push(observed.read(c).count);
4121                c.observe(&observed, |model, observed, c| {
4122                    model.events.push(observed.read(c).count * 2);
4123                })
4124                .detach();
4125            })
4126            .detach();
4127        });
4128
4129        handle_2.update(cx, |model, c| {
4130            model.count = 7;
4131            c.notify()
4132        });
4133        assert_eq!(handle_1.read(cx).events, vec![7]);
4134
4135        handle_2.update(cx, |model, c| {
4136            model.count = 5;
4137            c.notify()
4138        });
4139        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
4140    }
4141
4142    #[crate::test(self)]
4143    fn test_view_handles(cx: &mut MutableAppContext) {
4144        struct View {
4145            other: Option<ViewHandle<View>>,
4146            events: Vec<String>,
4147        }
4148
4149        impl Entity for View {
4150            type Event = usize;
4151        }
4152
4153        impl super::View for View {
4154            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4155                Empty::new().boxed()
4156            }
4157
4158            fn ui_name() -> &'static str {
4159                "View"
4160            }
4161        }
4162
4163        impl View {
4164            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
4165                if let Some(other) = other.as_ref() {
4166                    cx.subscribe(other, |me, _, event, _| {
4167                        me.events.push(format!("observed event {}", event));
4168                    })
4169                    .detach();
4170                }
4171                Self {
4172                    other,
4173                    events: Vec::new(),
4174                }
4175            }
4176        }
4177
4178        let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
4179        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
4180        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
4181        assert_eq!(cx.cx.views.len(), 3);
4182
4183        handle_1.update(cx, |view, cx| {
4184            view.events.push("updated".into());
4185            cx.emit(1);
4186            cx.emit(2);
4187        });
4188        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4189        assert_eq!(
4190            handle_2.read(cx).events,
4191            vec![
4192                "observed event 1".to_string(),
4193                "observed event 2".to_string(),
4194            ]
4195        );
4196
4197        handle_2.update(cx, |view, _| {
4198            drop(handle_1);
4199            view.other.take();
4200        });
4201
4202        assert_eq!(cx.cx.views.len(), 2);
4203        assert!(cx.subscriptions.lock().is_empty());
4204        assert!(cx.observations.lock().is_empty());
4205    }
4206
4207    #[crate::test(self)]
4208    fn test_add_window(cx: &mut MutableAppContext) {
4209        struct View {
4210            mouse_down_count: Arc<AtomicUsize>,
4211        }
4212
4213        impl Entity for View {
4214            type Event = ();
4215        }
4216
4217        impl super::View for View {
4218            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4219                let mouse_down_count = self.mouse_down_count.clone();
4220                EventHandler::new(Empty::new().boxed())
4221                    .on_mouse_down(move |_| {
4222                        mouse_down_count.fetch_add(1, SeqCst);
4223                        true
4224                    })
4225                    .boxed()
4226            }
4227
4228            fn ui_name() -> &'static str {
4229                "View"
4230            }
4231        }
4232
4233        let mouse_down_count = Arc::new(AtomicUsize::new(0));
4234        let (window_id, _) = cx.add_window(Default::default(), |_| View {
4235            mouse_down_count: mouse_down_count.clone(),
4236        });
4237        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
4238        // Ensure window's root element is in a valid lifecycle state.
4239        presenter.borrow_mut().dispatch_event(
4240            Event::LeftMouseDown {
4241                position: Default::default(),
4242                ctrl: false,
4243                alt: false,
4244                shift: false,
4245                cmd: false,
4246                click_count: 1,
4247            },
4248            cx,
4249        );
4250        assert_eq!(mouse_down_count.load(SeqCst), 1);
4251    }
4252
4253    #[crate::test(self)]
4254    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
4255        struct Model {
4256            released: Rc<Cell<bool>>,
4257        }
4258
4259        struct View {
4260            released: Rc<Cell<bool>>,
4261        }
4262
4263        impl Entity for Model {
4264            type Event = ();
4265
4266            fn release(&mut self, _: &mut MutableAppContext) {
4267                self.released.set(true);
4268            }
4269        }
4270
4271        impl Entity for View {
4272            type Event = ();
4273
4274            fn release(&mut self, _: &mut MutableAppContext) {
4275                self.released.set(true);
4276            }
4277        }
4278
4279        impl super::View for View {
4280            fn ui_name() -> &'static str {
4281                "View"
4282            }
4283
4284            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4285                Empty::new().boxed()
4286            }
4287        }
4288
4289        let model_released = Rc::new(Cell::new(false));
4290        let model_release_observed = Rc::new(Cell::new(false));
4291        let view_released = Rc::new(Cell::new(false));
4292        let view_release_observed = Rc::new(Cell::new(false));
4293
4294        let model = cx.add_model(|_| Model {
4295            released: model_released.clone(),
4296        });
4297        let (window_id, view) = cx.add_window(Default::default(), |_| View {
4298            released: view_released.clone(),
4299        });
4300        assert!(!model_released.get());
4301        assert!(!view_released.get());
4302
4303        cx.observe_release(&model, {
4304            let model_release_observed = model_release_observed.clone();
4305            move |_| model_release_observed.set(true)
4306        })
4307        .detach();
4308        cx.observe_release(&view, {
4309            let view_release_observed = view_release_observed.clone();
4310            move |_| view_release_observed.set(true)
4311        })
4312        .detach();
4313
4314        cx.update(move |_| {
4315            drop(model);
4316        });
4317        assert!(model_released.get());
4318        assert!(model_release_observed.get());
4319
4320        drop(view);
4321        cx.remove_window(window_id);
4322        assert!(view_released.get());
4323        assert!(view_release_observed.get());
4324    }
4325
4326    #[crate::test(self)]
4327    fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) {
4328        #[derive(Default)]
4329        struct View {
4330            events: Vec<usize>,
4331        }
4332
4333        impl Entity for View {
4334            type Event = usize;
4335        }
4336
4337        impl super::View for View {
4338            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4339                Empty::new().boxed()
4340            }
4341
4342            fn ui_name() -> &'static str {
4343                "View"
4344            }
4345        }
4346
4347        struct Model;
4348
4349        impl Entity for Model {
4350            type Event = usize;
4351        }
4352
4353        let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
4354        let handle_2 = cx.add_view(window_id, |_| View::default());
4355        let handle_3 = cx.add_model(|_| Model);
4356
4357        handle_1.update(cx, |_, c| {
4358            c.subscribe(&handle_2, move |me, emitter, event, c| {
4359                me.events.push(*event);
4360
4361                c.subscribe(&emitter, |me, _, event, _| {
4362                    me.events.push(*event * 2);
4363                })
4364                .detach();
4365            })
4366            .detach();
4367
4368            c.subscribe(&handle_3, |me, _, event, _| {
4369                me.events.push(*event);
4370            })
4371            .detach();
4372        });
4373
4374        handle_2.update(cx, |_, c| c.emit(7));
4375        assert_eq!(handle_1.read(cx).events, vec![7]);
4376
4377        handle_2.update(cx, |_, c| c.emit(5));
4378        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4379
4380        handle_3.update(cx, |_, c| c.emit(9));
4381        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
4382    }
4383
4384    #[crate::test(self)]
4385    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
4386        struct View;
4387
4388        impl Entity for View {
4389            type Event = ();
4390        }
4391
4392        impl super::View for View {
4393            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4394                Empty::new().boxed()
4395            }
4396
4397            fn ui_name() -> &'static str {
4398                "View"
4399            }
4400        }
4401
4402        struct Model;
4403
4404        impl Entity for Model {
4405            type Event = ();
4406        }
4407
4408        let (window_id, _) = cx.add_window(Default::default(), |_| View);
4409        let observing_view = cx.add_view(window_id, |_| View);
4410        let emitting_view = cx.add_view(window_id, |_| View);
4411        let observing_model = cx.add_model(|_| Model);
4412        let observed_model = cx.add_model(|_| Model);
4413
4414        observing_view.update(cx, |_, cx| {
4415            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
4416            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4417        });
4418        observing_model.update(cx, |_, cx| {
4419            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4420        });
4421
4422        cx.update(|_| {
4423            drop(observing_view);
4424            drop(observing_model);
4425        });
4426
4427        emitting_view.update(cx, |_, cx| cx.emit(()));
4428        observed_model.update(cx, |_, cx| cx.emit(()));
4429    }
4430
4431    #[crate::test(self)]
4432    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
4433        #[derive(Default)]
4434        struct View {
4435            events: Vec<usize>,
4436        }
4437
4438        impl Entity for View {
4439            type Event = usize;
4440        }
4441
4442        impl super::View for View {
4443            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4444                Empty::new().boxed()
4445            }
4446
4447            fn ui_name() -> &'static str {
4448                "View"
4449            }
4450        }
4451
4452        #[derive(Default)]
4453        struct Model {
4454            count: usize,
4455        }
4456
4457        impl Entity for Model {
4458            type Event = ();
4459        }
4460
4461        let (_, view) = cx.add_window(Default::default(), |_| View::default());
4462        let model = cx.add_model(|_| Model::default());
4463
4464        view.update(cx, |_, c| {
4465            c.observe(&model, |me, observed, c| {
4466                me.events.push(observed.read(c).count)
4467            })
4468            .detach();
4469        });
4470
4471        model.update(cx, |model, c| {
4472            model.count = 11;
4473            c.notify();
4474        });
4475        assert_eq!(view.read(cx).events, vec![11]);
4476    }
4477
4478    #[crate::test(self)]
4479    fn test_dropping_observers(cx: &mut MutableAppContext) {
4480        struct View;
4481
4482        impl Entity for View {
4483            type Event = ();
4484        }
4485
4486        impl super::View for View {
4487            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4488                Empty::new().boxed()
4489            }
4490
4491            fn ui_name() -> &'static str {
4492                "View"
4493            }
4494        }
4495
4496        struct Model;
4497
4498        impl Entity for Model {
4499            type Event = ();
4500        }
4501
4502        let (window_id, _) = cx.add_window(Default::default(), |_| View);
4503        let observing_view = cx.add_view(window_id, |_| View);
4504        let observing_model = cx.add_model(|_| Model);
4505        let observed_model = cx.add_model(|_| Model);
4506
4507        observing_view.update(cx, |_, cx| {
4508            cx.observe(&observed_model, |_, _, _| {}).detach();
4509        });
4510        observing_model.update(cx, |_, cx| {
4511            cx.observe(&observed_model, |_, _, _| {}).detach();
4512        });
4513
4514        cx.update(|_| {
4515            drop(observing_view);
4516            drop(observing_model);
4517        });
4518
4519        observed_model.update(cx, |_, cx| cx.notify());
4520    }
4521
4522    #[crate::test(self)]
4523    fn test_focus(cx: &mut MutableAppContext) {
4524        struct View {
4525            name: String,
4526            events: Arc<Mutex<Vec<String>>>,
4527        }
4528
4529        impl Entity for View {
4530            type Event = ();
4531        }
4532
4533        impl super::View for View {
4534            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4535                Empty::new().boxed()
4536            }
4537
4538            fn ui_name() -> &'static str {
4539                "View"
4540            }
4541
4542            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
4543                self.events.lock().push(format!("{} focused", &self.name));
4544            }
4545
4546            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
4547                self.events.lock().push(format!("{} blurred", &self.name));
4548            }
4549        }
4550
4551        let events: Arc<Mutex<Vec<String>>> = Default::default();
4552        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
4553            events: events.clone(),
4554            name: "view 1".to_string(),
4555        });
4556        let view_2 = cx.add_view(window_id, |_| View {
4557            events: events.clone(),
4558            name: "view 2".to_string(),
4559        });
4560
4561        view_1.update(cx, |_, cx| cx.focus(&view_2));
4562        view_1.update(cx, |_, cx| cx.focus(&view_1));
4563        view_1.update(cx, |_, cx| cx.focus(&view_2));
4564        view_1.update(cx, |_, _| drop(view_2));
4565
4566        assert_eq!(
4567            *events.lock(),
4568            [
4569                "view 1 focused".to_string(),
4570                "view 1 blurred".to_string(),
4571                "view 2 focused".to_string(),
4572                "view 2 blurred".to_string(),
4573                "view 1 focused".to_string(),
4574                "view 1 blurred".to_string(),
4575                "view 2 focused".to_string(),
4576                "view 1 focused".to_string(),
4577            ],
4578        );
4579    }
4580
4581    #[crate::test(self)]
4582    fn test_dispatch_action(cx: &mut MutableAppContext) {
4583        struct ViewA {
4584            id: usize,
4585        }
4586
4587        impl Entity for ViewA {
4588            type Event = ();
4589        }
4590
4591        impl View for ViewA {
4592            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4593                Empty::new().boxed()
4594            }
4595
4596            fn ui_name() -> &'static str {
4597                "View"
4598            }
4599        }
4600
4601        struct ViewB {
4602            id: usize,
4603        }
4604
4605        impl Entity for ViewB {
4606            type Event = ();
4607        }
4608
4609        impl View for ViewB {
4610            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4611                Empty::new().boxed()
4612            }
4613
4614            fn ui_name() -> &'static str {
4615                "View"
4616            }
4617        }
4618
4619        action!(Action, &'static str);
4620
4621        let actions = Rc::new(RefCell::new(Vec::new()));
4622
4623        {
4624            let actions = actions.clone();
4625            cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
4626                actions.borrow_mut().push("global".to_string());
4627            });
4628        }
4629
4630        {
4631            let actions = actions.clone();
4632            cx.add_action(move |view: &mut ViewA, action: &Action, cx| {
4633                assert_eq!(action.0, "bar");
4634                cx.propagate_action();
4635                actions.borrow_mut().push(format!("{} a", view.id));
4636            });
4637        }
4638
4639        {
4640            let actions = actions.clone();
4641            cx.add_action(move |view: &mut ViewA, _: &Action, cx| {
4642                if view.id != 1 {
4643                    cx.add_view(|cx| {
4644                        cx.propagate_action(); // Still works on a nested ViewContext
4645                        ViewB { id: 5 }
4646                    });
4647                }
4648                actions.borrow_mut().push(format!("{} b", view.id));
4649            });
4650        }
4651
4652        {
4653            let actions = actions.clone();
4654            cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
4655                cx.propagate_action();
4656                actions.borrow_mut().push(format!("{} c", view.id));
4657            });
4658        }
4659
4660        {
4661            let actions = actions.clone();
4662            cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
4663                cx.propagate_action();
4664                actions.borrow_mut().push(format!("{} d", view.id));
4665            });
4666        }
4667
4668        {
4669            let actions = actions.clone();
4670            cx.capture_action(move |view: &mut ViewA, _: &Action, cx| {
4671                cx.propagate_action();
4672                actions.borrow_mut().push(format!("{} capture", view.id));
4673            });
4674        }
4675
4676        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
4677        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
4678        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
4679        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
4680
4681        cx.dispatch_action(
4682            window_id,
4683            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
4684            &Action("bar"),
4685        );
4686
4687        assert_eq!(
4688            *actions.borrow(),
4689            vec![
4690                "1 capture",
4691                "3 capture",
4692                "4 d",
4693                "4 c",
4694                "3 b",
4695                "3 a",
4696                "2 d",
4697                "2 c",
4698                "1 b"
4699            ]
4700        );
4701
4702        // Remove view_1, which doesn't propagate the action
4703        actions.borrow_mut().clear();
4704        cx.dispatch_action(
4705            window_id,
4706            vec![view_2.id(), view_3.id(), view_4.id()],
4707            &Action("bar"),
4708        );
4709
4710        assert_eq!(
4711            *actions.borrow(),
4712            vec![
4713                "3 capture",
4714                "4 d",
4715                "4 c",
4716                "3 b",
4717                "3 a",
4718                "2 d",
4719                "2 c",
4720                "global"
4721            ]
4722        );
4723    }
4724
4725    #[crate::test(self)]
4726    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
4727        use std::cell::Cell;
4728
4729        action!(Action, &'static str);
4730
4731        struct View {
4732            id: usize,
4733            keymap_context: keymap::Context,
4734        }
4735
4736        impl Entity for View {
4737            type Event = ();
4738        }
4739
4740        impl super::View for View {
4741            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4742                Empty::new().boxed()
4743            }
4744
4745            fn ui_name() -> &'static str {
4746                "View"
4747            }
4748
4749            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
4750                self.keymap_context.clone()
4751            }
4752        }
4753
4754        impl View {
4755            fn new(id: usize) -> Self {
4756                View {
4757                    id,
4758                    keymap_context: keymap::Context::default(),
4759                }
4760            }
4761        }
4762
4763        let mut view_1 = View::new(1);
4764        let mut view_2 = View::new(2);
4765        let mut view_3 = View::new(3);
4766        view_1.keymap_context.set.insert("a".into());
4767        view_2.keymap_context.set.insert("a".into());
4768        view_2.keymap_context.set.insert("b".into());
4769        view_3.keymap_context.set.insert("a".into());
4770        view_3.keymap_context.set.insert("b".into());
4771        view_3.keymap_context.set.insert("c".into());
4772
4773        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
4774        let view_2 = cx.add_view(window_id, |_| view_2);
4775        let view_3 = cx.add_view(window_id, |_| view_3);
4776
4777        // This keymap's only binding dispatches an action on view 2 because that view will have
4778        // "a" and "b" in its context, but not "c".
4779        cx.add_bindings(vec![keymap::Binding::new(
4780            "a",
4781            Action("a"),
4782            Some("a && b && !c"),
4783        )]);
4784
4785        let handled_action = Rc::new(Cell::new(false));
4786        let handled_action_clone = handled_action.clone();
4787        cx.add_action(move |view: &mut View, action: &Action, _| {
4788            handled_action_clone.set(true);
4789            assert_eq!(view.id, 2);
4790            assert_eq!(action.0, "a");
4791        });
4792
4793        cx.dispatch_keystroke(
4794            window_id,
4795            vec![view_1.id(), view_2.id(), view_3.id()],
4796            &Keystroke::parse("a").unwrap(),
4797        )
4798        .unwrap();
4799
4800        assert!(handled_action.get());
4801    }
4802
4803    #[crate::test(self)]
4804    async fn test_model_condition(cx: &mut TestAppContext) {
4805        struct Counter(usize);
4806
4807        impl super::Entity for Counter {
4808            type Event = ();
4809        }
4810
4811        impl Counter {
4812            fn inc(&mut self, cx: &mut ModelContext<Self>) {
4813                self.0 += 1;
4814                cx.notify();
4815            }
4816        }
4817
4818        let model = cx.add_model(|_| Counter(0));
4819
4820        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
4821        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
4822        smol::pin!(condition1, condition2);
4823
4824        model.update(cx, |model, cx| model.inc(cx));
4825        assert_eq!(poll_once(&mut condition1).await, None);
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 condition1).await, Some(()));
4830        assert_eq!(poll_once(&mut condition2).await, None);
4831
4832        model.update(cx, |model, cx| model.inc(cx));
4833        assert_eq!(poll_once(&mut condition2).await, Some(()));
4834
4835        model.update(cx, |_, cx| cx.notify());
4836    }
4837
4838    #[crate::test(self)]
4839    #[should_panic]
4840    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
4841        struct Model;
4842
4843        impl super::Entity for Model {
4844            type Event = ();
4845        }
4846
4847        let model = cx.add_model(|_| Model);
4848        model.condition(&cx, |_, _| false).await;
4849    }
4850
4851    #[crate::test(self)]
4852    #[should_panic(expected = "model dropped with pending condition")]
4853    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
4854        struct Model;
4855
4856        impl super::Entity for Model {
4857            type Event = ();
4858        }
4859
4860        let model = cx.add_model(|_| Model);
4861        let condition = model.condition(&cx, |_, _| false);
4862        cx.update(|_| drop(model));
4863        condition.await;
4864    }
4865
4866    #[crate::test(self)]
4867    async fn test_view_condition(cx: &mut TestAppContext) {
4868        struct Counter(usize);
4869
4870        impl super::Entity for Counter {
4871            type Event = ();
4872        }
4873
4874        impl super::View for Counter {
4875            fn ui_name() -> &'static str {
4876                "test view"
4877            }
4878
4879            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4880                Empty::new().boxed()
4881            }
4882        }
4883
4884        impl Counter {
4885            fn inc(&mut self, cx: &mut ViewContext<Self>) {
4886                self.0 += 1;
4887                cx.notify();
4888            }
4889        }
4890
4891        let (_, view) = cx.add_window(|_| Counter(0));
4892
4893        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
4894        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
4895        smol::pin!(condition1, condition2);
4896
4897        view.update(cx, |view, cx| view.inc(cx));
4898        assert_eq!(poll_once(&mut condition1).await, None);
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 condition1).await, Some(()));
4903        assert_eq!(poll_once(&mut condition2).await, None);
4904
4905        view.update(cx, |view, cx| view.inc(cx));
4906        assert_eq!(poll_once(&mut condition2).await, Some(()));
4907        view.update(cx, |_, cx| cx.notify());
4908    }
4909
4910    #[crate::test(self)]
4911    #[should_panic]
4912    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
4913        struct View;
4914
4915        impl super::Entity for View {
4916            type Event = ();
4917        }
4918
4919        impl super::View for View {
4920            fn ui_name() -> &'static str {
4921                "test view"
4922            }
4923
4924            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4925                Empty::new().boxed()
4926            }
4927        }
4928
4929        let (_, view) = cx.add_window(|_| View);
4930        view.condition(&cx, |_, _| false).await;
4931    }
4932
4933    #[crate::test(self)]
4934    #[should_panic(expected = "view dropped with pending condition")]
4935    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
4936        struct View;
4937
4938        impl super::Entity for View {
4939            type Event = ();
4940        }
4941
4942        impl super::View for View {
4943            fn ui_name() -> &'static str {
4944                "test view"
4945            }
4946
4947            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4948                Empty::new().boxed()
4949            }
4950        }
4951
4952        let window_id = cx.add_window(|_| View).0;
4953        let view = cx.add_view(window_id, |_| View);
4954
4955        let condition = view.condition(&cx, |_, _| false);
4956        cx.update(|_| drop(view));
4957        condition.await;
4958    }
4959}