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