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