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