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