app.rs

   1use crate::{
   2    elements::ElementBox,
   3    executor,
   4    keymap::{self, Keystroke},
   5    platform::{self, Platform, PromptLevel, WindowOptions},
   6    presenter::Presenter,
   7    util::{post_inc, timeout},
   8    AssetCache, AssetSource, ClipboardItem, FontCache, PathPromptOptions, TextLayoutCache,
   9};
  10use anyhow::{anyhow, Result};
  11use async_task::Task;
  12use keymap::MatchResult;
  13use parking_lot::{Mutex, RwLock};
  14use pathfinder_geometry::{rect::RectF, vector::vec2f};
  15use platform::Event;
  16use postage::{mpsc, sink::Sink as _, stream::Stream as _};
  17use smol::prelude::*;
  18use std::{
  19    any::{type_name, Any, TypeId},
  20    cell::RefCell,
  21    collections::{hash_map::Entry, HashMap, HashSet, VecDeque},
  22    fmt::{self, Debug},
  23    hash::{Hash, Hasher},
  24    marker::PhantomData,
  25    path::{Path, PathBuf},
  26    rc::{self, Rc},
  27    sync::{Arc, Weak},
  28    time::Duration,
  29};
  30
  31pub trait Entity: 'static + Send + Sync {
  32    type Event;
  33}
  34
  35pub trait View: Entity {
  36    fn ui_name() -> &'static str;
  37    fn render<'a>(&self, cx: &AppContext) -> ElementBox;
  38    fn on_focus(&mut self, _: &mut ViewContext<Self>) {}
  39    fn on_blur(&mut self, _: &mut ViewContext<Self>) {}
  40    fn keymap_context(&self, _: &AppContext) -> keymap::Context {
  41        Self::default_keymap_context()
  42    }
  43    fn default_keymap_context() -> keymap::Context {
  44        let mut cx = keymap::Context::default();
  45        cx.set.insert(Self::ui_name().into());
  46        cx
  47    }
  48}
  49
  50pub trait ReadModel {
  51    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T;
  52}
  53
  54pub trait ReadModelWith {
  55    fn read_model_with<E: Entity, F: FnOnce(&E, &AppContext) -> T, T>(
  56        &self,
  57        handle: &ModelHandle<E>,
  58        read: F,
  59    ) -> T;
  60}
  61
  62pub trait UpdateModel {
  63    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
  64    where
  65        T: Entity,
  66        F: FnOnce(&mut T, &mut ModelContext<T>) -> S;
  67}
  68
  69pub trait ReadView {
  70    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T;
  71}
  72
  73pub trait ReadViewWith {
  74    fn read_view_with<V, F, T>(&self, handle: &ViewHandle<V>, read: F) -> T
  75    where
  76        V: View,
  77        F: FnOnce(&V, &AppContext) -> T;
  78}
  79
  80pub trait UpdateView {
  81    fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
  82    where
  83        T: View,
  84        F: FnOnce(&mut T, &mut ViewContext<T>) -> S;
  85}
  86
  87pub struct Menu<'a> {
  88    pub name: &'a str,
  89    pub items: Vec<MenuItem<'a>>,
  90}
  91
  92pub enum MenuItem<'a> {
  93    Action {
  94        name: &'a str,
  95        keystroke: Option<&'a str>,
  96        action: &'a str,
  97        arg: Option<Box<dyn Any + 'static>>,
  98    },
  99    Separator,
 100}
 101
 102#[derive(Clone)]
 103pub struct App(Rc<RefCell<MutableAppContext>>);
 104
 105pub struct AsyncAppContext(Rc<RefCell<MutableAppContext>>);
 106
 107#[derive(Clone)]
 108pub struct TestAppContext {
 109    cx: Rc<RefCell<MutableAppContext>>,
 110    foreground_platform: Rc<platform::test::ForegroundPlatform>,
 111}
 112
 113impl App {
 114    pub fn test<T, A: AssetSource, F: FnOnce(&mut MutableAppContext) -> T>(
 115        asset_source: A,
 116        f: F,
 117    ) -> T {
 118        let foreground_platform = platform::test::foreground_platform();
 119        let platform = platform::test::platform();
 120        let foreground = Rc::new(executor::Foreground::test());
 121        let cx = Rc::new(RefCell::new(MutableAppContext::new(
 122            foreground,
 123            Arc::new(platform),
 124            Rc::new(foreground_platform),
 125            asset_source,
 126        )));
 127        cx.borrow_mut().weak_self = Some(Rc::downgrade(&cx));
 128        let mut cx = cx.borrow_mut();
 129        f(&mut *cx)
 130    }
 131
 132    pub fn test_async<T, F, A: AssetSource, Fn>(asset_source: A, f: Fn) -> T
 133    where
 134        Fn: FnOnce(TestAppContext) -> F,
 135        F: Future<Output = T>,
 136    {
 137        let platform = Arc::new(platform::test::platform());
 138        let foreground_platform = Rc::new(platform::test::foreground_platform());
 139        let foreground = Rc::new(executor::Foreground::test());
 140        let cx = TestAppContext {
 141            cx: Rc::new(RefCell::new(MutableAppContext::new(
 142                foreground.clone(),
 143                platform,
 144                foreground_platform.clone(),
 145                asset_source,
 146            ))),
 147            foreground_platform,
 148        };
 149        cx.cx.borrow_mut().weak_self = Some(Rc::downgrade(&cx.cx));
 150
 151        let future = f(cx);
 152        smol::block_on(foreground.run(future))
 153    }
 154
 155    pub fn new(asset_source: impl AssetSource) -> Result<Self> {
 156        let platform = platform::current::platform();
 157        let foreground_platform = platform::current::foreground_platform();
 158        let foreground = Rc::new(executor::Foreground::platform(platform.dispatcher())?);
 159        let app = Self(Rc::new(RefCell::new(MutableAppContext::new(
 160            foreground,
 161            platform.clone(),
 162            foreground_platform.clone(),
 163            asset_source,
 164        ))));
 165
 166        let cx = app.0.clone();
 167        foreground_platform.on_menu_command(Box::new(move |command, arg| {
 168            let mut cx = cx.borrow_mut();
 169            if let Some(key_window_id) = cx.platform.key_window_id() {
 170                if let Some((presenter, _)) = cx.presenters_and_platform_windows.get(&key_window_id)
 171                {
 172                    let presenter = presenter.clone();
 173                    let path = presenter.borrow().dispatch_path(cx.as_ref());
 174                    cx.dispatch_action_any(key_window_id, &path, command, arg.unwrap_or(&()));
 175                } else {
 176                    cx.dispatch_global_action_any(command, arg.unwrap_or(&()));
 177                }
 178            } else {
 179                cx.dispatch_global_action_any(command, arg.unwrap_or(&()));
 180            }
 181        }));
 182
 183        app.0.borrow_mut().weak_self = Some(Rc::downgrade(&app.0));
 184        Ok(app)
 185    }
 186
 187    pub fn on_become_active<F>(self, mut callback: F) -> Self
 188    where
 189        F: 'static + FnMut(&mut MutableAppContext),
 190    {
 191        let cx = self.0.clone();
 192        self.0
 193            .borrow_mut()
 194            .foreground_platform
 195            .on_become_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 196        self
 197    }
 198
 199    pub fn on_resign_active<F>(self, mut callback: F) -> Self
 200    where
 201        F: 'static + FnMut(&mut MutableAppContext),
 202    {
 203        let cx = self.0.clone();
 204        self.0
 205            .borrow_mut()
 206            .foreground_platform
 207            .on_resign_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 208        self
 209    }
 210
 211    pub fn on_event<F>(self, mut callback: F) -> Self
 212    where
 213        F: 'static + FnMut(Event, &mut MutableAppContext) -> bool,
 214    {
 215        let cx = self.0.clone();
 216        self.0
 217            .borrow_mut()
 218            .foreground_platform
 219            .on_event(Box::new(move |event| {
 220                callback(event, &mut *cx.borrow_mut())
 221            }));
 222        self
 223    }
 224
 225    pub fn on_open_files<F>(self, mut callback: F) -> Self
 226    where
 227        F: 'static + FnMut(Vec<PathBuf>, &mut MutableAppContext),
 228    {
 229        let cx = self.0.clone();
 230        self.0
 231            .borrow_mut()
 232            .foreground_platform
 233            .on_open_files(Box::new(move |paths| {
 234                callback(paths, &mut *cx.borrow_mut())
 235            }));
 236        self
 237    }
 238
 239    pub fn run<F>(self, on_finish_launching: F)
 240    where
 241        F: 'static + FnOnce(&mut MutableAppContext),
 242    {
 243        let platform = self.0.borrow().foreground_platform.clone();
 244        platform.run(Box::new(move || {
 245            let mut cx = self.0.borrow_mut();
 246            on_finish_launching(&mut *cx);
 247        }))
 248    }
 249
 250    pub fn font_cache(&self) -> Arc<FontCache> {
 251        self.0.borrow().cx.font_cache.clone()
 252    }
 253
 254    fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 255        let mut state = self.0.borrow_mut();
 256        state.pending_flushes += 1;
 257        let result = callback(&mut *state);
 258        state.flush_effects();
 259        result
 260    }
 261}
 262
 263impl TestAppContext {
 264    pub fn dispatch_action<T: 'static + Any>(
 265        &self,
 266        window_id: usize,
 267        responder_chain: Vec<usize>,
 268        name: &str,
 269        arg: T,
 270    ) {
 271        self.cx.borrow_mut().dispatch_action_any(
 272            window_id,
 273            &responder_chain,
 274            name,
 275            Box::new(arg).as_ref(),
 276        );
 277    }
 278
 279    pub fn dispatch_keystroke(
 280        &self,
 281        window_id: usize,
 282        responder_chain: Vec<usize>,
 283        keystroke: &Keystroke,
 284    ) -> Result<bool> {
 285        let mut state = self.cx.borrow_mut();
 286        state.dispatch_keystroke(window_id, responder_chain, keystroke)
 287    }
 288
 289    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 290    where
 291        T: Entity,
 292        F: FnOnce(&mut ModelContext<T>) -> T,
 293    {
 294        let mut state = self.cx.borrow_mut();
 295        state.pending_flushes += 1;
 296        let handle = state.add_model(build_model);
 297        state.flush_effects();
 298        handle
 299    }
 300
 301    pub fn add_window<T, F>(&mut self, build_root_view: F) -> (usize, ViewHandle<T>)
 302    where
 303        T: View,
 304        F: FnOnce(&mut ViewContext<T>) -> T,
 305    {
 306        self.cx.borrow_mut().add_window(build_root_view)
 307    }
 308
 309    pub fn window_ids(&self) -> Vec<usize> {
 310        self.cx.borrow().window_ids().collect()
 311    }
 312
 313    pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
 314        self.cx.borrow().root_view(window_id)
 315    }
 316
 317    pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
 318    where
 319        T: View,
 320        F: FnOnce(&mut ViewContext<T>) -> T,
 321    {
 322        let mut state = self.cx.borrow_mut();
 323        state.pending_flushes += 1;
 324        let handle = state.add_view(window_id, build_view);
 325        state.flush_effects();
 326        handle
 327    }
 328
 329    pub fn add_option_view<T, F>(
 330        &mut self,
 331        window_id: usize,
 332        build_view: F,
 333    ) -> Option<ViewHandle<T>>
 334    where
 335        T: View,
 336        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
 337    {
 338        let mut state = self.cx.borrow_mut();
 339        state.pending_flushes += 1;
 340        let handle = state.add_option_view(window_id, build_view);
 341        state.flush_effects();
 342        handle
 343    }
 344
 345    pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
 346        callback(self.cx.borrow().as_ref())
 347    }
 348
 349    pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 350        let mut state = self.cx.borrow_mut();
 351        // Don't increment pending flushes in order to effects to be flushed before the callback
 352        // completes, which is helpful in tests.
 353        let result = callback(&mut *state);
 354        // Flush effects after the callback just in case there are any. This can happen in edge
 355        // cases such as the closure dropping handles.
 356        state.flush_effects();
 357        result
 358    }
 359
 360    pub fn font_cache(&self) -> Arc<FontCache> {
 361        self.cx.borrow().cx.font_cache.clone()
 362    }
 363
 364    pub fn platform(&self) -> Arc<dyn platform::Platform> {
 365        self.cx.borrow().platform.clone()
 366    }
 367
 368    pub fn simulate_new_path_selection(&self, result: impl FnOnce(PathBuf) -> Option<PathBuf>) {
 369        self.foreground_platform.simulate_new_path_selection(result);
 370    }
 371
 372    pub fn did_prompt_for_new_path(&self) -> bool {
 373        self.foreground_platform.as_ref().did_prompt_for_new_path()
 374    }
 375
 376    pub fn simulate_prompt_answer(&self, window_id: usize, answer: usize) {
 377        let mut state = self.cx.borrow_mut();
 378        let (_, window) = state
 379            .presenters_and_platform_windows
 380            .get_mut(&window_id)
 381            .unwrap();
 382        let test_window = window
 383            .as_any_mut()
 384            .downcast_mut::<platform::test::Window>()
 385            .unwrap();
 386        let callback = test_window
 387            .last_prompt
 388            .take()
 389            .expect("prompt was not called");
 390        (callback)(answer);
 391    }
 392}
 393
 394impl AsyncAppContext {
 395    pub fn read<T, F: FnOnce(&AppContext) -> T>(&mut self, callback: F) -> T {
 396        callback(self.0.borrow().as_ref())
 397    }
 398
 399    pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 400        let mut state = self.0.borrow_mut();
 401        state.pending_flushes += 1;
 402        let result = callback(&mut *state);
 403        state.flush_effects();
 404        result
 405    }
 406
 407    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 408    where
 409        T: Entity,
 410        F: FnOnce(&mut ModelContext<T>) -> T,
 411    {
 412        self.update(|cx| cx.add_model(build_model))
 413    }
 414
 415    pub fn platform(&self) -> Arc<dyn Platform> {
 416        self.0.borrow().platform()
 417    }
 418
 419    pub fn background_executor(&self) -> Arc<executor::Background> {
 420        self.0.borrow().cx.background.clone()
 421    }
 422}
 423
 424impl UpdateModel for AsyncAppContext {
 425    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
 426    where
 427        T: Entity,
 428        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
 429    {
 430        let mut state = self.0.borrow_mut();
 431        state.pending_flushes += 1;
 432        let result = state.update_model(handle, update);
 433        state.flush_effects();
 434        result
 435    }
 436}
 437
 438impl ReadModelWith for AsyncAppContext {
 439    fn read_model_with<E: Entity, F: FnOnce(&E, &AppContext) -> T, T>(
 440        &self,
 441        handle: &ModelHandle<E>,
 442        read: F,
 443    ) -> T {
 444        let cx = self.0.borrow();
 445        let cx = cx.as_ref();
 446        read(handle.read(cx), cx)
 447    }
 448}
 449
 450impl UpdateView for AsyncAppContext {
 451    fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
 452    where
 453        T: View,
 454        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
 455    {
 456        let mut state = self.0.borrow_mut();
 457        state.pending_flushes += 1;
 458        let result = state.update_view(handle, update);
 459        state.flush_effects();
 460        result
 461    }
 462}
 463
 464impl ReadViewWith for AsyncAppContext {
 465    fn read_view_with<V, F, T>(&self, handle: &ViewHandle<V>, read: F) -> T
 466    where
 467        V: View,
 468        F: FnOnce(&V, &AppContext) -> T,
 469    {
 470        let cx = self.0.borrow();
 471        let cx = cx.as_ref();
 472        read(handle.read(cx), cx)
 473    }
 474}
 475
 476impl UpdateModel for TestAppContext {
 477    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
 478    where
 479        T: Entity,
 480        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
 481    {
 482        let mut state = self.cx.borrow_mut();
 483        state.pending_flushes += 1;
 484        let result = state.update_model(handle, update);
 485        state.flush_effects();
 486        result
 487    }
 488}
 489
 490impl ReadModelWith for TestAppContext {
 491    fn read_model_with<E: Entity, F: FnOnce(&E, &AppContext) -> T, T>(
 492        &self,
 493        handle: &ModelHandle<E>,
 494        read: F,
 495    ) -> T {
 496        let cx = self.cx.borrow();
 497        let cx = cx.as_ref();
 498        read(handle.read(cx), cx)
 499    }
 500}
 501
 502impl UpdateView for TestAppContext {
 503    fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
 504    where
 505        T: View,
 506        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
 507    {
 508        let mut state = self.cx.borrow_mut();
 509        state.pending_flushes += 1;
 510        let result = state.update_view(handle, update);
 511        state.flush_effects();
 512        result
 513    }
 514}
 515
 516impl ReadViewWith for TestAppContext {
 517    fn read_view_with<V, F, T>(&self, handle: &ViewHandle<V>, read: F) -> T
 518    where
 519        V: View,
 520        F: FnOnce(&V, &AppContext) -> T,
 521    {
 522        let cx = self.cx.borrow();
 523        let cx = cx.as_ref();
 524        read(handle.read(cx), cx)
 525    }
 526}
 527
 528type ActionCallback =
 529    dyn FnMut(&mut dyn AnyView, &dyn Any, &mut MutableAppContext, usize, usize) -> bool;
 530
 531type GlobalActionCallback = dyn FnMut(&dyn Any, &mut MutableAppContext);
 532
 533pub struct MutableAppContext {
 534    weak_self: Option<rc::Weak<RefCell<Self>>>,
 535    foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 536    platform: Arc<dyn platform::Platform>,
 537    assets: Arc<AssetCache>,
 538    cx: AppContext,
 539    actions: HashMap<TypeId, HashMap<String, Vec<Box<ActionCallback>>>>,
 540    global_actions: HashMap<String, Vec<Box<GlobalActionCallback>>>,
 541    keystroke_matcher: keymap::Matcher,
 542    next_entity_id: usize,
 543    next_window_id: usize,
 544    subscriptions: HashMap<usize, Vec<Subscription>>,
 545    model_observations: HashMap<usize, Vec<ModelObservation>>,
 546    view_observations: HashMap<usize, Vec<ViewObservation>>,
 547    presenters_and_platform_windows:
 548        HashMap<usize, (Rc<RefCell<Presenter>>, Box<dyn platform::Window>)>,
 549    debug_elements_callbacks: HashMap<usize, Box<dyn Fn(&AppContext) -> crate::json::Value>>,
 550    foreground: Rc<executor::Foreground>,
 551    pending_effects: VecDeque<Effect>,
 552    pending_flushes: usize,
 553    flushing_effects: bool,
 554}
 555
 556impl MutableAppContext {
 557    fn new(
 558        foreground: Rc<executor::Foreground>,
 559        platform: Arc<dyn platform::Platform>,
 560        foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 561        asset_source: impl AssetSource,
 562    ) -> Self {
 563        let fonts = platform.fonts();
 564        Self {
 565            weak_self: None,
 566            foreground_platform,
 567            platform,
 568            assets: Arc::new(AssetCache::new(asset_source)),
 569            cx: AppContext {
 570                models: Default::default(),
 571                views: Default::default(),
 572                windows: Default::default(),
 573                values: Default::default(),
 574                ref_counts: Arc::new(Mutex::new(RefCounts::default())),
 575                background: Arc::new(executor::Background::new()),
 576                thread_pool: scoped_pool::Pool::new(num_cpus::get(), "app"),
 577                font_cache: Arc::new(FontCache::new(fonts)),
 578            },
 579            actions: HashMap::new(),
 580            global_actions: HashMap::new(),
 581            keystroke_matcher: keymap::Matcher::default(),
 582            next_entity_id: 0,
 583            next_window_id: 0,
 584            subscriptions: HashMap::new(),
 585            model_observations: HashMap::new(),
 586            view_observations: HashMap::new(),
 587            presenters_and_platform_windows: HashMap::new(),
 588            debug_elements_callbacks: HashMap::new(),
 589            foreground,
 590            pending_effects: VecDeque::new(),
 591            pending_flushes: 0,
 592            flushing_effects: false,
 593        }
 594    }
 595
 596    pub fn upgrade(&self) -> App {
 597        App(self.weak_self.as_ref().unwrap().upgrade().unwrap())
 598    }
 599
 600    pub fn platform(&self) -> Arc<dyn platform::Platform> {
 601        self.platform.clone()
 602    }
 603
 604    pub fn font_cache(&self) -> &Arc<FontCache> {
 605        &self.cx.font_cache
 606    }
 607
 608    pub fn foreground_executor(&self) -> &Rc<executor::Foreground> {
 609        &self.foreground
 610    }
 611
 612    pub fn background_executor(&self) -> &Arc<executor::Background> {
 613        &self.cx.background
 614    }
 615
 616    pub fn on_debug_elements<F>(&mut self, window_id: usize, callback: F)
 617    where
 618        F: 'static + Fn(&AppContext) -> crate::json::Value,
 619    {
 620        self.debug_elements_callbacks
 621            .insert(window_id, Box::new(callback));
 622    }
 623
 624    pub fn debug_elements(&self, window_id: usize) -> Option<crate::json::Value> {
 625        self.debug_elements_callbacks
 626            .get(&window_id)
 627            .map(|debug_elements| debug_elements(&self.cx))
 628    }
 629
 630    pub fn add_action<S, V, T, F>(&mut self, name: S, mut handler: F)
 631    where
 632        S: Into<String>,
 633        V: View,
 634        T: Any,
 635        F: 'static + FnMut(&mut V, &T, &mut ViewContext<V>),
 636    {
 637        let name = name.into();
 638        let name_clone = name.clone();
 639        let handler = Box::new(
 640            move |view: &mut dyn AnyView,
 641                  arg: &dyn Any,
 642                  cx: &mut MutableAppContext,
 643                  window_id: usize,
 644                  view_id: usize| {
 645                match arg.downcast_ref() {
 646                    Some(arg) => {
 647                        let mut cx = ViewContext::new(cx, window_id, view_id);
 648                        handler(
 649                            view.as_any_mut()
 650                                .downcast_mut()
 651                                .expect("downcast is type safe"),
 652                            arg,
 653                            &mut cx,
 654                        );
 655                        cx.halt_action_dispatch
 656                    }
 657                    None => {
 658                        log::error!("Could not downcast argument for action {}", name_clone);
 659                        false
 660                    }
 661                }
 662            },
 663        );
 664
 665        self.actions
 666            .entry(TypeId::of::<V>())
 667            .or_default()
 668            .entry(name)
 669            .or_default()
 670            .push(handler);
 671    }
 672
 673    pub fn add_global_action<S, T, F>(&mut self, name: S, mut handler: F)
 674    where
 675        S: Into<String>,
 676        T: 'static + Any,
 677        F: 'static + FnMut(&T, &mut MutableAppContext),
 678    {
 679        let name = name.into();
 680        let name_clone = name.clone();
 681        let handler = Box::new(move |arg: &dyn Any, cx: &mut MutableAppContext| {
 682            if let Some(arg) = arg.downcast_ref() {
 683                handler(arg, cx);
 684            } else {
 685                log::error!("Could not downcast argument for action {}", name_clone);
 686            }
 687        });
 688
 689        self.global_actions.entry(name).or_default().push(handler);
 690    }
 691
 692    pub fn window_ids(&self) -> impl Iterator<Item = usize> + '_ {
 693        self.cx.windows.keys().cloned()
 694    }
 695
 696    pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
 697        self.cx
 698            .windows
 699            .get(&window_id)
 700            .and_then(|window| window.root_view.clone().downcast::<T>())
 701    }
 702
 703    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
 704        self.cx.root_view_id(window_id)
 705    }
 706
 707    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
 708        self.cx.focused_view_id(window_id)
 709    }
 710
 711    pub fn render_view(&self, window_id: usize, view_id: usize) -> Result<ElementBox> {
 712        self.cx.render_view(window_id, view_id)
 713    }
 714
 715    pub fn render_views(&self, window_id: usize) -> HashMap<usize, ElementBox> {
 716        self.cx.render_views(window_id)
 717    }
 718
 719    pub fn update<T, F: FnOnce() -> T>(&mut self, callback: F) -> T {
 720        self.pending_flushes += 1;
 721        let result = callback();
 722        self.flush_effects();
 723        result
 724    }
 725
 726    pub fn set_menus(&mut self, menus: Vec<Menu>) {
 727        self.foreground_platform.set_menus(menus);
 728    }
 729
 730    fn prompt<F>(
 731        &self,
 732        window_id: usize,
 733        level: PromptLevel,
 734        msg: &str,
 735        answers: &[&str],
 736        done_fn: F,
 737    ) where
 738        F: 'static + FnOnce(usize, &mut MutableAppContext),
 739    {
 740        let app = self.weak_self.as_ref().unwrap().upgrade().unwrap();
 741        let foreground = self.foreground.clone();
 742        let (_, window) = &self.presenters_and_platform_windows[&window_id];
 743        window.prompt(
 744            level,
 745            msg,
 746            answers,
 747            Box::new(move |answer| {
 748                foreground
 749                    .spawn(async move { (done_fn)(answer, &mut *app.borrow_mut()) })
 750                    .detach();
 751            }),
 752        );
 753    }
 754
 755    pub fn prompt_for_paths<F>(&self, options: PathPromptOptions, done_fn: F)
 756    where
 757        F: 'static + FnOnce(Option<Vec<PathBuf>>, &mut MutableAppContext),
 758    {
 759        let app = self.weak_self.as_ref().unwrap().upgrade().unwrap();
 760        let foreground = self.foreground.clone();
 761        self.foreground_platform.prompt_for_paths(
 762            options,
 763            Box::new(move |paths| {
 764                foreground
 765                    .spawn(async move { (done_fn)(paths, &mut *app.borrow_mut()) })
 766                    .detach();
 767            }),
 768        );
 769    }
 770
 771    pub fn prompt_for_new_path<F>(&self, directory: &Path, done_fn: F)
 772    where
 773        F: 'static + FnOnce(Option<PathBuf>, &mut MutableAppContext),
 774    {
 775        let app = self.weak_self.as_ref().unwrap().upgrade().unwrap();
 776        let foreground = self.foreground.clone();
 777        self.foreground_platform.prompt_for_new_path(
 778            directory,
 779            Box::new(move |path| {
 780                foreground
 781                    .spawn(async move { (done_fn)(path, &mut *app.borrow_mut()) })
 782                    .detach();
 783            }),
 784        );
 785    }
 786
 787    pub(crate) fn notify_view(&mut self, window_id: usize, view_id: usize) {
 788        self.pending_effects
 789            .push_back(Effect::ViewNotification { window_id, view_id });
 790    }
 791
 792    pub fn dispatch_action<T: 'static + Any>(
 793        &mut self,
 794        window_id: usize,
 795        responder_chain: Vec<usize>,
 796        name: &str,
 797        arg: T,
 798    ) {
 799        self.dispatch_action_any(window_id, &responder_chain, name, Box::new(arg).as_ref());
 800    }
 801
 802    pub(crate) fn dispatch_action_any(
 803        &mut self,
 804        window_id: usize,
 805        path: &[usize],
 806        name: &str,
 807        arg: &dyn Any,
 808    ) -> bool {
 809        self.pending_flushes += 1;
 810        let mut halted_dispatch = false;
 811
 812        for view_id in path.iter().rev() {
 813            if let Some(mut view) = self.cx.views.remove(&(window_id, *view_id)) {
 814                let type_id = view.as_any().type_id();
 815
 816                if let Some((name, mut handlers)) = self
 817                    .actions
 818                    .get_mut(&type_id)
 819                    .and_then(|h| h.remove_entry(name))
 820                {
 821                    for handler in handlers.iter_mut().rev() {
 822                        let halt_dispatch = handler(view.as_mut(), arg, self, window_id, *view_id);
 823                        if halt_dispatch {
 824                            halted_dispatch = true;
 825                            break;
 826                        }
 827                    }
 828                    self.actions
 829                        .get_mut(&type_id)
 830                        .unwrap()
 831                        .insert(name, handlers);
 832                }
 833
 834                self.cx.views.insert((window_id, *view_id), view);
 835
 836                if halted_dispatch {
 837                    break;
 838                }
 839            }
 840        }
 841
 842        if !halted_dispatch {
 843            self.dispatch_global_action_any(name, arg);
 844        }
 845
 846        self.flush_effects();
 847        halted_dispatch
 848    }
 849
 850    pub fn dispatch_global_action<T: 'static + Any>(&mut self, name: &str, arg: T) {
 851        self.dispatch_global_action_any(name, Box::new(arg).as_ref());
 852    }
 853
 854    fn dispatch_global_action_any(&mut self, name: &str, arg: &dyn Any) {
 855        if let Some((name, mut handlers)) = self.global_actions.remove_entry(name) {
 856            self.pending_flushes += 1;
 857            for handler in handlers.iter_mut().rev() {
 858                handler(arg, self);
 859            }
 860            self.global_actions.insert(name, handlers);
 861            self.flush_effects();
 862        }
 863    }
 864
 865    pub fn add_bindings<T: IntoIterator<Item = keymap::Binding>>(&mut self, bindings: T) {
 866        self.keystroke_matcher.add_bindings(bindings);
 867    }
 868
 869    pub fn dispatch_keystroke(
 870        &mut self,
 871        window_id: usize,
 872        responder_chain: Vec<usize>,
 873        keystroke: &Keystroke,
 874    ) -> Result<bool> {
 875        let mut context_chain = Vec::new();
 876        let mut context = keymap::Context::default();
 877        for view_id in &responder_chain {
 878            if let Some(view) = self.cx.views.get(&(window_id, *view_id)) {
 879                context.extend(view.keymap_context(self.as_ref()));
 880                context_chain.push(context.clone());
 881            } else {
 882                return Err(anyhow!(
 883                    "View {} in responder chain does not exist",
 884                    view_id
 885                ));
 886            }
 887        }
 888
 889        let mut pending = false;
 890        for (i, cx) in context_chain.iter().enumerate().rev() {
 891            match self
 892                .keystroke_matcher
 893                .push_keystroke(keystroke.clone(), responder_chain[i], cx)
 894            {
 895                MatchResult::None => {}
 896                MatchResult::Pending => pending = true,
 897                MatchResult::Action { name, arg } => {
 898                    if self.dispatch_action_any(
 899                        window_id,
 900                        &responder_chain[0..=i],
 901                        &name,
 902                        arg.as_ref().map(|arg| arg.as_ref()).unwrap_or(&()),
 903                    ) {
 904                        return Ok(true);
 905                    }
 906                }
 907            }
 908        }
 909
 910        Ok(pending)
 911    }
 912
 913    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 914    where
 915        T: Entity,
 916        F: FnOnce(&mut ModelContext<T>) -> T,
 917    {
 918        self.pending_flushes += 1;
 919        let model_id = post_inc(&mut self.next_entity_id);
 920        let handle = ModelHandle::new(model_id, &self.cx.ref_counts);
 921        let mut cx = ModelContext::new(self, model_id);
 922        let model = build_model(&mut cx);
 923        self.cx.models.insert(model_id, Box::new(model));
 924        self.flush_effects();
 925        handle
 926    }
 927
 928    pub fn add_window<T, F>(&mut self, build_root_view: F) -> (usize, ViewHandle<T>)
 929    where
 930        T: View,
 931        F: FnOnce(&mut ViewContext<T>) -> T,
 932    {
 933        self.pending_flushes += 1;
 934        let window_id = post_inc(&mut self.next_window_id);
 935        let root_view = self.add_view(window_id, build_root_view);
 936
 937        self.cx.windows.insert(
 938            window_id,
 939            Window {
 940                root_view: root_view.clone().into(),
 941                focused_view_id: root_view.id(),
 942                invalidation: None,
 943            },
 944        );
 945        self.open_platform_window(window_id);
 946        root_view.update(self, |view, cx| view.on_focus(cx));
 947        self.flush_effects();
 948
 949        (window_id, root_view)
 950    }
 951
 952    pub fn remove_window(&mut self, window_id: usize) {
 953        self.cx.windows.remove(&window_id);
 954        self.presenters_and_platform_windows.remove(&window_id);
 955        self.remove_dropped_entities();
 956    }
 957
 958    fn open_platform_window(&mut self, window_id: usize) {
 959        let mut window = self.platform.open_window(
 960            window_id,
 961            WindowOptions {
 962                bounds: RectF::new(vec2f(0., 0.), vec2f(1024., 768.)),
 963                title: "Zed".into(),
 964            },
 965            self.foreground.clone(),
 966        );
 967        let text_layout_cache = TextLayoutCache::new(self.platform.fonts());
 968        let presenter = Rc::new(RefCell::new(Presenter::new(
 969            window_id,
 970            self.cx.font_cache.clone(),
 971            text_layout_cache,
 972            self.assets.clone(),
 973            self,
 974        )));
 975
 976        {
 977            let mut app = self.upgrade();
 978            let presenter = presenter.clone();
 979            window.on_event(Box::new(move |event| {
 980                app.update(|cx| {
 981                    if let Event::KeyDown { keystroke, .. } = &event {
 982                        if cx
 983                            .dispatch_keystroke(
 984                                window_id,
 985                                presenter.borrow().dispatch_path(cx.as_ref()),
 986                                keystroke,
 987                            )
 988                            .unwrap()
 989                        {
 990                            return;
 991                        }
 992                    }
 993
 994                    presenter.borrow_mut().dispatch_event(event, cx);
 995                })
 996            }));
 997        }
 998
 999        {
1000            let mut app = self.upgrade();
1001            let presenter = presenter.clone();
1002            window.on_resize(Box::new(move |window| {
1003                app.update(|cx| {
1004                    let scene = presenter.borrow_mut().build_scene(
1005                        window.size(),
1006                        window.scale_factor(),
1007                        cx,
1008                    );
1009                    window.present_scene(scene);
1010                })
1011            }));
1012        }
1013
1014        {
1015            let mut app = self.upgrade();
1016            window.on_close(Box::new(move || {
1017                app.update(|cx| cx.remove_window(window_id));
1018            }));
1019        }
1020
1021        self.presenters_and_platform_windows
1022            .insert(window_id, (presenter.clone(), window));
1023
1024        self.on_debug_elements(window_id, move |cx| {
1025            presenter.borrow().debug_elements(cx).unwrap()
1026        });
1027    }
1028
1029    pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
1030    where
1031        T: View,
1032        F: FnOnce(&mut ViewContext<T>) -> T,
1033    {
1034        self.add_option_view(window_id, |cx| Some(build_view(cx)))
1035            .unwrap()
1036    }
1037
1038    pub fn add_option_view<T, F>(
1039        &mut self,
1040        window_id: usize,
1041        build_view: F,
1042    ) -> Option<ViewHandle<T>>
1043    where
1044        T: View,
1045        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1046    {
1047        let view_id = post_inc(&mut self.next_entity_id);
1048        self.pending_flushes += 1;
1049        let handle = ViewHandle::new(window_id, view_id, &self.cx.ref_counts);
1050        let mut cx = ViewContext::new(self, window_id, view_id);
1051        let handle = if let Some(view) = build_view(&mut cx) {
1052            self.cx.views.insert((window_id, view_id), Box::new(view));
1053            if let Some(window) = self.cx.windows.get_mut(&window_id) {
1054                window
1055                    .invalidation
1056                    .get_or_insert_with(Default::default)
1057                    .updated
1058                    .insert(view_id);
1059            }
1060            Some(handle)
1061        } else {
1062            None
1063        };
1064        self.flush_effects();
1065        handle
1066    }
1067
1068    fn remove_dropped_entities(&mut self) {
1069        loop {
1070            let (dropped_models, dropped_views, dropped_values) =
1071                self.cx.ref_counts.lock().take_dropped();
1072            if dropped_models.is_empty() && dropped_views.is_empty() && dropped_values.is_empty() {
1073                break;
1074            }
1075
1076            for model_id in dropped_models {
1077                self.cx.models.remove(&model_id);
1078                self.subscriptions.remove(&model_id);
1079                self.model_observations.remove(&model_id);
1080            }
1081
1082            for (window_id, view_id) in dropped_views {
1083                self.subscriptions.remove(&view_id);
1084                self.model_observations.remove(&view_id);
1085                self.cx.views.remove(&(window_id, view_id));
1086                let change_focus_to = self.cx.windows.get_mut(&window_id).and_then(|window| {
1087                    window
1088                        .invalidation
1089                        .get_or_insert_with(Default::default)
1090                        .removed
1091                        .push(view_id);
1092                    if window.focused_view_id == view_id {
1093                        Some(window.root_view.id())
1094                    } else {
1095                        None
1096                    }
1097                });
1098
1099                if let Some(view_id) = change_focus_to {
1100                    self.focus(window_id, view_id);
1101                }
1102            }
1103
1104            let mut values = self.cx.values.write();
1105            for key in dropped_values {
1106                values.remove(&key);
1107            }
1108        }
1109    }
1110
1111    fn flush_effects(&mut self) {
1112        self.pending_flushes = self.pending_flushes.saturating_sub(1);
1113
1114        if !self.flushing_effects && self.pending_flushes == 0 {
1115            self.flushing_effects = true;
1116
1117            loop {
1118                if let Some(effect) = self.pending_effects.pop_front() {
1119                    match effect {
1120                        Effect::Event { entity_id, payload } => self.emit_event(entity_id, payload),
1121                        Effect::ModelNotification { model_id } => {
1122                            self.notify_model_observers(model_id)
1123                        }
1124                        Effect::ViewNotification { window_id, view_id } => {
1125                            self.notify_view_observers(window_id, view_id)
1126                        }
1127                        Effect::Focus { window_id, view_id } => {
1128                            self.focus(window_id, view_id);
1129                        }
1130                    }
1131                    self.remove_dropped_entities();
1132                } else {
1133                    self.remove_dropped_entities();
1134                    self.update_windows();
1135
1136                    if self.pending_effects.is_empty() {
1137                        self.flushing_effects = false;
1138                        break;
1139                    }
1140                }
1141            }
1142        }
1143    }
1144
1145    fn update_windows(&mut self) {
1146        let mut invalidations = HashMap::new();
1147        for (window_id, window) in &mut self.cx.windows {
1148            if let Some(invalidation) = window.invalidation.take() {
1149                invalidations.insert(*window_id, invalidation);
1150            }
1151        }
1152
1153        for (window_id, invalidation) in invalidations {
1154            if let Some((presenter, mut window)) =
1155                self.presenters_and_platform_windows.remove(&window_id)
1156            {
1157                {
1158                    let mut presenter = presenter.borrow_mut();
1159                    presenter.invalidate(invalidation, self.as_ref());
1160                    let scene = presenter.build_scene(window.size(), window.scale_factor(), self);
1161                    window.present_scene(scene);
1162                }
1163                self.presenters_and_platform_windows
1164                    .insert(window_id, (presenter, window));
1165            }
1166        }
1167    }
1168
1169    fn emit_event(&mut self, entity_id: usize, payload: Box<dyn Any>) {
1170        if let Some(subscriptions) = self.subscriptions.remove(&entity_id) {
1171            for mut subscription in subscriptions {
1172                let alive = match &mut subscription {
1173                    Subscription::FromModel { model_id, callback } => {
1174                        if let Some(mut model) = self.cx.models.remove(model_id) {
1175                            callback(model.as_any_mut(), payload.as_ref(), self, *model_id);
1176                            self.cx.models.insert(*model_id, model);
1177                            true
1178                        } else {
1179                            false
1180                        }
1181                    }
1182                    Subscription::FromView {
1183                        window_id,
1184                        view_id,
1185                        callback,
1186                    } => {
1187                        if let Some(mut view) = self.cx.views.remove(&(*window_id, *view_id)) {
1188                            callback(
1189                                view.as_any_mut(),
1190                                payload.as_ref(),
1191                                self,
1192                                *window_id,
1193                                *view_id,
1194                            );
1195                            self.cx.views.insert((*window_id, *view_id), view);
1196                            true
1197                        } else {
1198                            false
1199                        }
1200                    }
1201                };
1202
1203                if alive {
1204                    self.subscriptions
1205                        .entry(entity_id)
1206                        .or_default()
1207                        .push(subscription);
1208                }
1209            }
1210        }
1211    }
1212
1213    fn notify_model_observers(&mut self, observed_id: usize) {
1214        if let Some(observations) = self.model_observations.remove(&observed_id) {
1215            if self.cx.models.contains_key(&observed_id) {
1216                for mut observation in observations {
1217                    let alive = match &mut observation {
1218                        ModelObservation::FromModel { model_id, callback } => {
1219                            if let Some(mut model) = self.cx.models.remove(model_id) {
1220                                callback(model.as_any_mut(), observed_id, self, *model_id);
1221                                self.cx.models.insert(*model_id, model);
1222                                true
1223                            } else {
1224                                false
1225                            }
1226                        }
1227                        ModelObservation::FromView {
1228                            window_id,
1229                            view_id,
1230                            callback,
1231                        } => {
1232                            if let Some(mut view) = self.cx.views.remove(&(*window_id, *view_id)) {
1233                                callback(
1234                                    view.as_any_mut(),
1235                                    observed_id,
1236                                    self,
1237                                    *window_id,
1238                                    *view_id,
1239                                );
1240                                self.cx.views.insert((*window_id, *view_id), view);
1241                                true
1242                            } else {
1243                                false
1244                            }
1245                        }
1246                    };
1247
1248                    if alive {
1249                        self.model_observations
1250                            .entry(observed_id)
1251                            .or_default()
1252                            .push(observation);
1253                    }
1254                }
1255            }
1256        }
1257    }
1258
1259    fn notify_view_observers(&mut self, window_id: usize, view_id: usize) {
1260        if let Some(window) = self.cx.windows.get_mut(&window_id) {
1261            window
1262                .invalidation
1263                .get_or_insert_with(Default::default)
1264                .updated
1265                .insert(view_id);
1266        }
1267
1268        if let Some(observations) = self.view_observations.remove(&view_id) {
1269            if self.cx.views.contains_key(&(window_id, view_id)) {
1270                for mut observation in observations {
1271                    let alive = if let Some(mut view) = self
1272                        .cx
1273                        .views
1274                        .remove(&(observation.window_id, observation.view_id))
1275                    {
1276                        (observation.callback)(
1277                            view.as_any_mut(),
1278                            view_id,
1279                            window_id,
1280                            self,
1281                            observation.window_id,
1282                            observation.view_id,
1283                        );
1284                        self.cx
1285                            .views
1286                            .insert((observation.window_id, observation.view_id), view);
1287                        true
1288                    } else {
1289                        false
1290                    };
1291
1292                    if alive {
1293                        self.view_observations
1294                            .entry(view_id)
1295                            .or_default()
1296                            .push(observation);
1297                    }
1298                }
1299            }
1300        }
1301    }
1302
1303    fn focus(&mut self, window_id: usize, focused_id: usize) {
1304        if self
1305            .cx
1306            .windows
1307            .get(&window_id)
1308            .map(|w| w.focused_view_id)
1309            .map_or(false, |cur_focused| cur_focused == focused_id)
1310        {
1311            return;
1312        }
1313
1314        self.pending_flushes += 1;
1315
1316        let blurred_id = self.cx.windows.get_mut(&window_id).map(|window| {
1317            let blurred_id = window.focused_view_id;
1318            window.focused_view_id = focused_id;
1319            blurred_id
1320        });
1321
1322        if let Some(blurred_id) = blurred_id {
1323            if let Some(mut blurred_view) = self.cx.views.remove(&(window_id, blurred_id)) {
1324                blurred_view.on_blur(self, window_id, blurred_id);
1325                self.cx.views.insert((window_id, blurred_id), blurred_view);
1326            }
1327        }
1328
1329        if let Some(mut focused_view) = self.cx.views.remove(&(window_id, focused_id)) {
1330            focused_view.on_focus(self, window_id, focused_id);
1331            self.cx.views.insert((window_id, focused_id), focused_view);
1332        }
1333
1334        self.flush_effects();
1335    }
1336
1337    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
1338    where
1339        F: FnOnce(AsyncAppContext) -> Fut,
1340        Fut: 'static + Future<Output = T>,
1341        T: 'static,
1342    {
1343        let cx = self.to_async();
1344        self.foreground.spawn(f(cx))
1345    }
1346
1347    pub fn to_async(&self) -> AsyncAppContext {
1348        AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
1349    }
1350
1351    pub fn write_to_clipboard(&self, item: ClipboardItem) {
1352        self.platform.write_to_clipboard(item);
1353    }
1354
1355    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1356        self.platform.read_from_clipboard()
1357    }
1358}
1359
1360impl ReadModel for MutableAppContext {
1361    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1362        if let Some(model) = self.cx.models.get(&handle.model_id) {
1363            model
1364                .as_any()
1365                .downcast_ref()
1366                .expect("downcast is type safe")
1367        } else {
1368            panic!("circular model reference");
1369        }
1370    }
1371}
1372
1373impl UpdateModel for MutableAppContext {
1374    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
1375    where
1376        T: Entity,
1377        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
1378    {
1379        if let Some(mut model) = self.cx.models.remove(&handle.model_id) {
1380            self.pending_flushes += 1;
1381            let mut cx = ModelContext::new(self, handle.model_id);
1382            let result = update(
1383                model
1384                    .as_any_mut()
1385                    .downcast_mut()
1386                    .expect("downcast is type safe"),
1387                &mut cx,
1388            );
1389            self.cx.models.insert(handle.model_id, model);
1390            self.flush_effects();
1391            result
1392        } else {
1393            panic!("circular model update");
1394        }
1395    }
1396}
1397
1398impl ReadView for MutableAppContext {
1399    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1400        if let Some(view) = self.cx.views.get(&(handle.window_id, handle.view_id)) {
1401            view.as_any().downcast_ref().expect("downcast is type safe")
1402        } else {
1403            panic!("circular view reference");
1404        }
1405    }
1406}
1407
1408impl UpdateView for MutableAppContext {
1409    fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
1410    where
1411        T: View,
1412        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
1413    {
1414        self.pending_flushes += 1;
1415        let mut view = self
1416            .cx
1417            .views
1418            .remove(&(handle.window_id, handle.view_id))
1419            .expect("circular view update");
1420
1421        let mut cx = ViewContext::new(self, handle.window_id, handle.view_id);
1422        let result = update(
1423            view.as_any_mut()
1424                .downcast_mut()
1425                .expect("downcast is type safe"),
1426            &mut cx,
1427        );
1428        self.cx
1429            .views
1430            .insert((handle.window_id, handle.view_id), view);
1431        self.flush_effects();
1432        result
1433    }
1434}
1435
1436impl AsRef<AppContext> for MutableAppContext {
1437    fn as_ref(&self) -> &AppContext {
1438        &self.cx
1439    }
1440}
1441
1442pub struct AppContext {
1443    models: HashMap<usize, Box<dyn AnyModel>>,
1444    views: HashMap<(usize, usize), Box<dyn AnyView>>,
1445    windows: HashMap<usize, Window>,
1446    values: RwLock<HashMap<(TypeId, usize), Box<dyn Any>>>,
1447    background: Arc<executor::Background>,
1448    ref_counts: Arc<Mutex<RefCounts>>,
1449    thread_pool: scoped_pool::Pool,
1450    font_cache: Arc<FontCache>,
1451}
1452
1453impl AppContext {
1454    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
1455        self.windows
1456            .get(&window_id)
1457            .map(|window| window.root_view.id())
1458    }
1459
1460    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
1461        self.windows
1462            .get(&window_id)
1463            .map(|window| window.focused_view_id)
1464    }
1465
1466    pub fn render_view(&self, window_id: usize, view_id: usize) -> Result<ElementBox> {
1467        self.views
1468            .get(&(window_id, view_id))
1469            .map(|v| v.render(self))
1470            .ok_or(anyhow!("view not found"))
1471    }
1472
1473    pub fn render_views(&self, window_id: usize) -> HashMap<usize, ElementBox> {
1474        self.views
1475            .iter()
1476            .filter_map(|((win_id, view_id), view)| {
1477                if *win_id == window_id {
1478                    Some((*view_id, view.render(self)))
1479                } else {
1480                    None
1481                }
1482            })
1483            .collect::<HashMap<_, ElementBox>>()
1484    }
1485
1486    pub fn background_executor(&self) -> &Arc<executor::Background> {
1487        &self.background
1488    }
1489
1490    pub fn font_cache(&self) -> &FontCache {
1491        &self.font_cache
1492    }
1493
1494    pub fn thread_pool(&self) -> &scoped_pool::Pool {
1495        &self.thread_pool
1496    }
1497
1498    pub fn value<Tag: 'static, T: 'static + Default>(&self, id: usize) -> ValueHandle<T> {
1499        let key = (TypeId::of::<Tag>(), id);
1500        let mut values = self.values.write();
1501        values.entry(key).or_insert_with(|| Box::new(T::default()));
1502        ValueHandle::new(TypeId::of::<Tag>(), id, &self.ref_counts)
1503    }
1504}
1505
1506impl ReadModel for AppContext {
1507    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1508        if let Some(model) = self.models.get(&handle.model_id) {
1509            model
1510                .as_any()
1511                .downcast_ref()
1512                .expect("downcast should be type safe")
1513        } else {
1514            panic!("circular model reference");
1515        }
1516    }
1517}
1518
1519impl ReadView for AppContext {
1520    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1521        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
1522            view.as_any()
1523                .downcast_ref()
1524                .expect("downcast should be type safe")
1525        } else {
1526            panic!("circular view reference");
1527        }
1528    }
1529}
1530
1531struct Window {
1532    root_view: AnyViewHandle,
1533    focused_view_id: usize,
1534    invalidation: Option<WindowInvalidation>,
1535}
1536
1537#[derive(Default, Clone)]
1538pub struct WindowInvalidation {
1539    pub updated: HashSet<usize>,
1540    pub removed: Vec<usize>,
1541}
1542
1543pub enum Effect {
1544    Event {
1545        entity_id: usize,
1546        payload: Box<dyn Any>,
1547    },
1548    ModelNotification {
1549        model_id: usize,
1550    },
1551    ViewNotification {
1552        window_id: usize,
1553        view_id: usize,
1554    },
1555    Focus {
1556        window_id: usize,
1557        view_id: usize,
1558    },
1559}
1560
1561pub trait AnyModel: Send + Sync {
1562    fn as_any(&self) -> &dyn Any;
1563    fn as_any_mut(&mut self) -> &mut dyn Any;
1564}
1565
1566impl<T> AnyModel for T
1567where
1568    T: Entity,
1569{
1570    fn as_any(&self) -> &dyn Any {
1571        self
1572    }
1573
1574    fn as_any_mut(&mut self) -> &mut dyn Any {
1575        self
1576    }
1577}
1578
1579pub trait AnyView: Send + Sync {
1580    fn as_any(&self) -> &dyn Any;
1581    fn as_any_mut(&mut self) -> &mut dyn Any;
1582    fn ui_name(&self) -> &'static str;
1583    fn render<'a>(&self, cx: &AppContext) -> ElementBox;
1584    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
1585    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
1586    fn keymap_context(&self, cx: &AppContext) -> keymap::Context;
1587}
1588
1589impl<T> AnyView for T
1590where
1591    T: View,
1592{
1593    fn as_any(&self) -> &dyn Any {
1594        self
1595    }
1596
1597    fn as_any_mut(&mut self) -> &mut dyn Any {
1598        self
1599    }
1600
1601    fn ui_name(&self) -> &'static str {
1602        T::ui_name()
1603    }
1604
1605    fn render<'a>(&self, cx: &AppContext) -> ElementBox {
1606        View::render(self, cx)
1607    }
1608
1609    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
1610        let mut cx = ViewContext::new(cx, window_id, view_id);
1611        View::on_focus(self, &mut cx);
1612    }
1613
1614    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
1615        let mut cx = ViewContext::new(cx, window_id, view_id);
1616        View::on_blur(self, &mut cx);
1617    }
1618
1619    fn keymap_context(&self, cx: &AppContext) -> keymap::Context {
1620        View::keymap_context(self, cx)
1621    }
1622}
1623
1624pub struct ModelContext<'a, T: ?Sized> {
1625    app: &'a mut MutableAppContext,
1626    model_id: usize,
1627    model_type: PhantomData<T>,
1628    halt_stream: bool,
1629}
1630
1631impl<'a, T: Entity> ModelContext<'a, T> {
1632    fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
1633        Self {
1634            app,
1635            model_id,
1636            model_type: PhantomData,
1637            halt_stream: false,
1638        }
1639    }
1640
1641    pub fn background_executor(&self) -> &Arc<executor::Background> {
1642        &self.app.cx.background
1643    }
1644
1645    pub fn thread_pool(&self) -> &scoped_pool::Pool {
1646        &self.app.cx.thread_pool
1647    }
1648
1649    pub fn halt_stream(&mut self) {
1650        self.halt_stream = true;
1651    }
1652
1653    pub fn model_id(&self) -> usize {
1654        self.model_id
1655    }
1656
1657    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
1658    where
1659        S: Entity,
1660        F: FnOnce(&mut ModelContext<S>) -> S,
1661    {
1662        self.app.add_model(build_model)
1663    }
1664
1665    pub fn subscribe<S: Entity, F>(&mut self, handle: &ModelHandle<S>, mut callback: F)
1666    where
1667        S::Event: 'static,
1668        F: 'static + FnMut(&mut T, &S::Event, &mut ModelContext<T>),
1669    {
1670        self.app
1671            .subscriptions
1672            .entry(handle.model_id)
1673            .or_default()
1674            .push(Subscription::FromModel {
1675                model_id: self.model_id,
1676                callback: Box::new(move |model, payload, app, model_id| {
1677                    let model = model.downcast_mut().expect("downcast is type safe");
1678                    let payload = payload.downcast_ref().expect("downcast is type safe");
1679                    let mut cx = ModelContext::new(app, model_id);
1680                    callback(model, payload, &mut cx);
1681                }),
1682            });
1683    }
1684
1685    pub fn emit(&mut self, payload: T::Event) {
1686        self.app.pending_effects.push_back(Effect::Event {
1687            entity_id: self.model_id,
1688            payload: Box::new(payload),
1689        });
1690    }
1691
1692    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F)
1693    where
1694        S: Entity,
1695        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
1696    {
1697        self.app
1698            .model_observations
1699            .entry(handle.model_id)
1700            .or_default()
1701            .push(ModelObservation::FromModel {
1702                model_id: self.model_id,
1703                callback: Box::new(move |model, observed_id, app, model_id| {
1704                    let model = model.downcast_mut().expect("downcast is type safe");
1705                    let observed = ModelHandle::new(observed_id, &app.cx.ref_counts);
1706                    let mut cx = ModelContext::new(app, model_id);
1707                    callback(model, observed, &mut cx);
1708                }),
1709            });
1710    }
1711
1712    pub fn notify(&mut self) {
1713        self.app
1714            .pending_effects
1715            .push_back(Effect::ModelNotification {
1716                model_id: self.model_id,
1717            });
1718    }
1719
1720    pub fn handle(&self) -> ModelHandle<T> {
1721        ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
1722    }
1723
1724    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
1725    where
1726        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
1727        Fut: 'static + Future<Output = S>,
1728        S: 'static,
1729    {
1730        let handle = self.handle();
1731        self.app.spawn(|cx| f(handle, cx))
1732    }
1733}
1734
1735impl<M> AsRef<AppContext> for ModelContext<'_, M> {
1736    fn as_ref(&self) -> &AppContext {
1737        &self.app.cx
1738    }
1739}
1740
1741impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
1742    fn as_mut(&mut self) -> &mut MutableAppContext {
1743        self.app
1744    }
1745}
1746
1747impl<M> ReadModel for ModelContext<'_, M> {
1748    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1749        self.app.read_model(handle)
1750    }
1751}
1752
1753impl<M> UpdateModel for ModelContext<'_, M> {
1754    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
1755    where
1756        T: Entity,
1757        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
1758    {
1759        self.app.update_model(handle, update)
1760    }
1761}
1762
1763pub struct ViewContext<'a, T: ?Sized> {
1764    app: &'a mut MutableAppContext,
1765    window_id: usize,
1766    view_id: usize,
1767    view_type: PhantomData<T>,
1768    halt_action_dispatch: bool,
1769}
1770
1771impl<'a, T: View> ViewContext<'a, T> {
1772    fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
1773        Self {
1774            app,
1775            window_id,
1776            view_id,
1777            view_type: PhantomData,
1778            halt_action_dispatch: true,
1779        }
1780    }
1781
1782    pub fn handle(&self) -> ViewHandle<T> {
1783        ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
1784    }
1785
1786    pub fn window_id(&self) -> usize {
1787        self.window_id
1788    }
1789
1790    pub fn view_id(&self) -> usize {
1791        self.view_id
1792    }
1793
1794    pub fn foreground(&self) -> &Rc<executor::Foreground> {
1795        self.app.foreground_executor()
1796    }
1797
1798    pub fn background_executor(&self) -> &Arc<executor::Background> {
1799        &self.app.cx.background
1800    }
1801
1802    pub fn platform(&self) -> Arc<dyn Platform> {
1803        self.app.platform()
1804    }
1805
1806    pub fn prompt<F>(&self, level: PromptLevel, msg: &str, answers: &[&str], done_fn: F)
1807    where
1808        F: 'static + FnOnce(usize, &mut MutableAppContext),
1809    {
1810        self.app
1811            .prompt(self.window_id, level, msg, answers, done_fn)
1812    }
1813
1814    pub fn prompt_for_paths<F>(&self, options: PathPromptOptions, done_fn: F)
1815    where
1816        F: 'static + FnOnce(Option<Vec<PathBuf>>, &mut MutableAppContext),
1817    {
1818        self.app.prompt_for_paths(options, done_fn)
1819    }
1820
1821    pub fn prompt_for_new_path<F>(&self, directory: &Path, done_fn: F)
1822    where
1823        F: 'static + FnOnce(Option<PathBuf>, &mut MutableAppContext),
1824    {
1825        self.app.prompt_for_new_path(directory, done_fn)
1826    }
1827
1828    pub fn debug_elements(&self) -> crate::json::Value {
1829        self.app.debug_elements(self.window_id).unwrap()
1830    }
1831
1832    pub fn focus<S>(&mut self, handle: S)
1833    where
1834        S: Into<AnyViewHandle>,
1835    {
1836        let handle = handle.into();
1837        self.app.pending_effects.push_back(Effect::Focus {
1838            window_id: handle.window_id,
1839            view_id: handle.view_id,
1840        });
1841    }
1842
1843    pub fn focus_self(&mut self) {
1844        self.app.pending_effects.push_back(Effect::Focus {
1845            window_id: self.window_id,
1846            view_id: self.view_id,
1847        });
1848    }
1849
1850    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
1851    where
1852        S: Entity,
1853        F: FnOnce(&mut ModelContext<S>) -> S,
1854    {
1855        self.app.add_model(build_model)
1856    }
1857
1858    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
1859    where
1860        S: View,
1861        F: FnOnce(&mut ViewContext<S>) -> S,
1862    {
1863        self.app.add_view(self.window_id, build_view)
1864    }
1865
1866    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
1867    where
1868        S: View,
1869        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
1870    {
1871        self.app.add_option_view(self.window_id, build_view)
1872    }
1873
1874    pub fn subscribe_to_model<E, F>(&mut self, handle: &ModelHandle<E>, mut callback: F)
1875    where
1876        E: Entity,
1877        E::Event: 'static,
1878        F: 'static + FnMut(&mut T, ModelHandle<E>, &E::Event, &mut ViewContext<T>),
1879    {
1880        let emitter_handle = handle.downgrade();
1881        self.subscribe(handle, move |model, payload, cx| {
1882            if let Some(emitter_handle) = emitter_handle.upgrade(cx.as_ref()) {
1883                callback(model, emitter_handle, payload, cx);
1884            }
1885        });
1886    }
1887
1888    pub fn subscribe_to_view<V, F>(&mut self, handle: &ViewHandle<V>, mut callback: F)
1889    where
1890        V: View,
1891        V::Event: 'static,
1892        F: 'static + FnMut(&mut T, ViewHandle<V>, &V::Event, &mut ViewContext<T>),
1893    {
1894        let emitter_handle = handle.downgrade();
1895        self.subscribe(handle, move |view, payload, cx| {
1896            if let Some(emitter_handle) = emitter_handle.upgrade(cx.as_ref()) {
1897                callback(view, emitter_handle, payload, cx);
1898            }
1899        });
1900    }
1901
1902    pub fn subscribe<E, F>(&mut self, handle: &impl Handle<E>, mut callback: F)
1903    where
1904        E: Entity,
1905        E::Event: 'static,
1906        F: 'static + FnMut(&mut T, &E::Event, &mut ViewContext<T>),
1907    {
1908        self.app
1909            .subscriptions
1910            .entry(handle.id())
1911            .or_default()
1912            .push(Subscription::FromView {
1913                window_id: self.window_id,
1914                view_id: self.view_id,
1915                callback: Box::new(move |entity, payload, app, window_id, view_id| {
1916                    let entity = entity.downcast_mut().expect("downcast is type safe");
1917                    let payload = payload.downcast_ref().expect("downcast is type safe");
1918                    let mut cx = ViewContext::new(app, window_id, view_id);
1919                    callback(entity, payload, &mut cx);
1920                }),
1921            });
1922    }
1923
1924    pub fn emit(&mut self, payload: T::Event) {
1925        self.app.pending_effects.push_back(Effect::Event {
1926            entity_id: self.view_id,
1927            payload: Box::new(payload),
1928        });
1929    }
1930
1931    pub fn observe_model<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F)
1932    where
1933        S: Entity,
1934        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ViewContext<T>),
1935    {
1936        self.app
1937            .model_observations
1938            .entry(handle.id())
1939            .or_default()
1940            .push(ModelObservation::FromView {
1941                window_id: self.window_id,
1942                view_id: self.view_id,
1943                callback: Box::new(move |view, observed_id, app, window_id, view_id| {
1944                    let view = view.downcast_mut().expect("downcast is type safe");
1945                    let observed = ModelHandle::new(observed_id, &app.cx.ref_counts);
1946                    let mut cx = ViewContext::new(app, window_id, view_id);
1947                    callback(view, observed, &mut cx);
1948                }),
1949            });
1950    }
1951
1952    pub fn observe_view<S, F>(&mut self, handle: &ViewHandle<S>, mut callback: F)
1953    where
1954        S: View,
1955        F: 'static + FnMut(&mut T, ViewHandle<S>, &mut ViewContext<T>),
1956    {
1957        self.app
1958            .view_observations
1959            .entry(handle.id())
1960            .or_default()
1961            .push(ViewObservation {
1962                window_id: self.window_id,
1963                view_id: self.view_id,
1964                callback: Box::new(
1965                    move |view,
1966                          observed_view_id,
1967                          observed_window_id,
1968                          app,
1969                          observing_window_id,
1970                          observing_view_id| {
1971                        let view = view.downcast_mut().expect("downcast is type safe");
1972                        let observed_handle = ViewHandle::new(
1973                            observed_view_id,
1974                            observed_window_id,
1975                            &app.cx.ref_counts,
1976                        );
1977                        let mut cx = ViewContext::new(app, observing_window_id, observing_view_id);
1978                        callback(view, observed_handle, &mut cx);
1979                    },
1980                ),
1981            });
1982    }
1983
1984    pub fn notify(&mut self) {
1985        self.app.notify_view(self.window_id, self.view_id);
1986    }
1987
1988    pub fn propagate_action(&mut self) {
1989        self.halt_action_dispatch = false;
1990    }
1991
1992    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
1993    where
1994        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
1995        Fut: 'static + Future<Output = S>,
1996        S: 'static,
1997    {
1998        let handle = self.handle();
1999        self.app.spawn(|cx| f(handle, cx))
2000    }
2001}
2002
2003impl AsRef<AppContext> for &AppContext {
2004    fn as_ref(&self) -> &AppContext {
2005        self
2006    }
2007}
2008
2009impl<M> AsRef<AppContext> for ViewContext<'_, M> {
2010    fn as_ref(&self) -> &AppContext {
2011        &self.app.cx
2012    }
2013}
2014
2015impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
2016    fn as_mut(&mut self) -> &mut MutableAppContext {
2017        self.app
2018    }
2019}
2020
2021impl<V> ReadModel for ViewContext<'_, V> {
2022    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2023        self.app.read_model(handle)
2024    }
2025}
2026
2027impl<V: View> UpdateModel for ViewContext<'_, V> {
2028    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
2029    where
2030        T: Entity,
2031        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2032    {
2033        self.app.update_model(handle, update)
2034    }
2035}
2036
2037impl<V: View> ReadView for ViewContext<'_, V> {
2038    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2039        self.app.read_view(handle)
2040    }
2041}
2042
2043impl<V: View> UpdateView for ViewContext<'_, V> {
2044    fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
2045    where
2046        T: View,
2047        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2048    {
2049        self.app.update_view(handle, update)
2050    }
2051}
2052
2053pub trait Handle<T> {
2054    fn id(&self) -> usize;
2055    fn location(&self) -> EntityLocation;
2056}
2057
2058#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
2059pub enum EntityLocation {
2060    Model(usize),
2061    View(usize, usize),
2062}
2063
2064pub struct ModelHandle<T> {
2065    model_id: usize,
2066    model_type: PhantomData<T>,
2067    ref_counts: Arc<Mutex<RefCounts>>,
2068}
2069
2070impl<T: Entity> ModelHandle<T> {
2071    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2072        ref_counts.lock().inc_model(model_id);
2073        Self {
2074            model_id,
2075            model_type: PhantomData,
2076            ref_counts: ref_counts.clone(),
2077        }
2078    }
2079
2080    pub fn downgrade(&self) -> WeakModelHandle<T> {
2081        WeakModelHandle::new(self.model_id)
2082    }
2083
2084    pub fn id(&self) -> usize {
2085        self.model_id
2086    }
2087
2088    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
2089        cx.read_model(self)
2090    }
2091
2092    pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
2093    where
2094        C: ReadModelWith,
2095        F: FnOnce(&T, &AppContext) -> S,
2096    {
2097        cx.read_model_with(self, read)
2098    }
2099
2100    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2101    where
2102        C: UpdateModel,
2103        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2104    {
2105        cx.update_model(self, update)
2106    }
2107
2108    pub fn condition(
2109        &self,
2110        cx: &TestAppContext,
2111        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2112    ) -> impl Future<Output = ()> {
2113        let (tx, mut rx) = mpsc::channel(1024);
2114
2115        let mut cx = cx.cx.borrow_mut();
2116        self.update(&mut *cx, |_, cx| {
2117            cx.observe(self, {
2118                let mut tx = tx.clone();
2119                move |_, _, _| {
2120                    tx.blocking_send(()).ok();
2121                }
2122            });
2123            cx.subscribe(self, {
2124                let mut tx = tx.clone();
2125                move |_, _, _| {
2126                    tx.blocking_send(()).ok();
2127                }
2128            })
2129        });
2130
2131        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2132        let handle = self.downgrade();
2133        let duration = if std::env::var("CI").is_ok() {
2134            Duration::from_secs(5)
2135        } else {
2136            Duration::from_secs(1)
2137        };
2138
2139        async move {
2140            timeout(duration, async move {
2141                loop {
2142                    {
2143                        let cx = cx.borrow();
2144                        let cx = cx.as_ref();
2145                        if predicate(
2146                            handle
2147                                .upgrade(cx)
2148                                .expect("model dropped with pending condition")
2149                                .read(cx),
2150                            cx,
2151                        ) {
2152                            break;
2153                        }
2154                    }
2155
2156                    rx.recv()
2157                        .await
2158                        .expect("model dropped with pending condition");
2159                }
2160            })
2161            .await
2162            .expect("condition timed out");
2163        }
2164    }
2165}
2166
2167impl<T> Clone for ModelHandle<T> {
2168    fn clone(&self) -> Self {
2169        self.ref_counts.lock().inc_model(self.model_id);
2170        Self {
2171            model_id: self.model_id,
2172            model_type: PhantomData,
2173            ref_counts: self.ref_counts.clone(),
2174        }
2175    }
2176}
2177
2178impl<T> PartialEq for ModelHandle<T> {
2179    fn eq(&self, other: &Self) -> bool {
2180        self.model_id == other.model_id
2181    }
2182}
2183
2184impl<T> Eq for ModelHandle<T> {}
2185
2186impl<T> Hash for ModelHandle<T> {
2187    fn hash<H: Hasher>(&self, state: &mut H) {
2188        self.model_id.hash(state);
2189    }
2190}
2191
2192impl<T> std::borrow::Borrow<usize> for ModelHandle<T> {
2193    fn borrow(&self) -> &usize {
2194        &self.model_id
2195    }
2196}
2197
2198impl<T> Debug for ModelHandle<T> {
2199    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2200        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
2201            .field(&self.model_id)
2202            .finish()
2203    }
2204}
2205
2206unsafe impl<T> Send for ModelHandle<T> {}
2207unsafe impl<T> Sync for ModelHandle<T> {}
2208
2209impl<T> Drop for ModelHandle<T> {
2210    fn drop(&mut self) {
2211        self.ref_counts.lock().dec_model(self.model_id);
2212    }
2213}
2214
2215impl<T> Handle<T> for ModelHandle<T> {
2216    fn id(&self) -> usize {
2217        self.model_id
2218    }
2219
2220    fn location(&self) -> EntityLocation {
2221        EntityLocation::Model(self.model_id)
2222    }
2223}
2224
2225pub struct WeakModelHandle<T> {
2226    model_id: usize,
2227    model_type: PhantomData<T>,
2228}
2229
2230impl<T: Entity> WeakModelHandle<T> {
2231    fn new(model_id: usize) -> Self {
2232        Self {
2233            model_id,
2234            model_type: PhantomData,
2235        }
2236    }
2237
2238    pub fn upgrade(&self, cx: impl AsRef<AppContext>) -> Option<ModelHandle<T>> {
2239        let cx = cx.as_ref();
2240        if cx.models.contains_key(&self.model_id) {
2241            Some(ModelHandle::new(self.model_id, &cx.ref_counts))
2242        } else {
2243            None
2244        }
2245    }
2246}
2247
2248impl<T> Hash for WeakModelHandle<T> {
2249    fn hash<H: Hasher>(&self, state: &mut H) {
2250        self.model_id.hash(state)
2251    }
2252}
2253
2254impl<T> PartialEq for WeakModelHandle<T> {
2255    fn eq(&self, other: &Self) -> bool {
2256        self.model_id == other.model_id
2257    }
2258}
2259
2260impl<T> Eq for WeakModelHandle<T> {}
2261
2262impl<T> Clone for WeakModelHandle<T> {
2263    fn clone(&self) -> Self {
2264        Self {
2265            model_id: self.model_id,
2266            model_type: PhantomData,
2267        }
2268    }
2269}
2270
2271pub struct ViewHandle<T> {
2272    window_id: usize,
2273    view_id: usize,
2274    view_type: PhantomData<T>,
2275    ref_counts: Arc<Mutex<RefCounts>>,
2276}
2277
2278impl<T: View> ViewHandle<T> {
2279    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2280        ref_counts.lock().inc_view(window_id, view_id);
2281        Self {
2282            window_id,
2283            view_id,
2284            view_type: PhantomData,
2285            ref_counts: ref_counts.clone(),
2286        }
2287    }
2288
2289    pub fn downgrade(&self) -> WeakViewHandle<T> {
2290        WeakViewHandle::new(self.window_id, self.view_id)
2291    }
2292
2293    pub fn window_id(&self) -> usize {
2294        self.window_id
2295    }
2296
2297    pub fn id(&self) -> usize {
2298        self.view_id
2299    }
2300
2301    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
2302        cx.read_view(self)
2303    }
2304
2305    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
2306    where
2307        C: ReadViewWith,
2308        F: FnOnce(&T, &AppContext) -> S,
2309    {
2310        cx.read_view_with(self, read)
2311    }
2312
2313    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2314    where
2315        C: UpdateView,
2316        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2317    {
2318        cx.update_view(self, update)
2319    }
2320
2321    pub fn is_focused(&self, cx: &AppContext) -> bool {
2322        cx.focused_view_id(self.window_id)
2323            .map_or(false, |focused_id| focused_id == self.view_id)
2324    }
2325
2326    pub fn condition(
2327        &self,
2328        cx: &TestAppContext,
2329        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2330    ) -> impl Future<Output = ()> {
2331        let (tx, mut rx) = mpsc::channel(1024);
2332
2333        let mut cx = cx.cx.borrow_mut();
2334        self.update(&mut *cx, |_, cx| {
2335            cx.observe_view(self, {
2336                let mut tx = tx.clone();
2337                move |_, _, _| {
2338                    tx.blocking_send(()).ok();
2339                }
2340            });
2341
2342            cx.subscribe(self, {
2343                let mut tx = tx.clone();
2344                move |_, _, _| {
2345                    tx.blocking_send(()).ok();
2346                }
2347            })
2348        });
2349
2350        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2351        let handle = self.downgrade();
2352        let duration = if std::env::var("CI").is_ok() {
2353            Duration::from_secs(2)
2354        } else {
2355            Duration::from_millis(500)
2356        };
2357
2358        async move {
2359            timeout(duration, async move {
2360                loop {
2361                    {
2362                        let cx = cx.borrow();
2363                        let cx = cx.as_ref();
2364                        if predicate(
2365                            handle
2366                                .upgrade(cx)
2367                                .expect("view dropped with pending condition")
2368                                .read(cx),
2369                            cx,
2370                        ) {
2371                            break;
2372                        }
2373                    }
2374
2375                    rx.recv()
2376                        .await
2377                        .expect("view dropped with pending condition");
2378                }
2379            })
2380            .await
2381            .expect("condition timed out");
2382        }
2383    }
2384}
2385
2386impl<T> Clone for ViewHandle<T> {
2387    fn clone(&self) -> Self {
2388        self.ref_counts
2389            .lock()
2390            .inc_view(self.window_id, self.view_id);
2391        Self {
2392            window_id: self.window_id,
2393            view_id: self.view_id,
2394            view_type: PhantomData,
2395            ref_counts: self.ref_counts.clone(),
2396        }
2397    }
2398}
2399
2400impl<T> PartialEq for ViewHandle<T> {
2401    fn eq(&self, other: &Self) -> bool {
2402        self.window_id == other.window_id && self.view_id == other.view_id
2403    }
2404}
2405
2406impl<T> Eq for ViewHandle<T> {}
2407
2408impl<T> Debug for ViewHandle<T> {
2409    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2410        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
2411            .field("window_id", &self.window_id)
2412            .field("view_id", &self.view_id)
2413            .finish()
2414    }
2415}
2416
2417impl<T> Drop for ViewHandle<T> {
2418    fn drop(&mut self) {
2419        self.ref_counts
2420            .lock()
2421            .dec_view(self.window_id, self.view_id);
2422    }
2423}
2424
2425impl<T> Handle<T> for ViewHandle<T> {
2426    fn id(&self) -> usize {
2427        self.view_id
2428    }
2429
2430    fn location(&self) -> EntityLocation {
2431        EntityLocation::View(self.window_id, self.view_id)
2432    }
2433}
2434
2435pub struct AnyViewHandle {
2436    window_id: usize,
2437    view_id: usize,
2438    view_type: TypeId,
2439    ref_counts: Arc<Mutex<RefCounts>>,
2440}
2441
2442impl AnyViewHandle {
2443    pub fn id(&self) -> usize {
2444        self.view_id
2445    }
2446
2447    pub fn is<T: 'static>(&self) -> bool {
2448        TypeId::of::<T>() == self.view_type
2449    }
2450
2451    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
2452        if self.is::<T>() {
2453            let result = Some(ViewHandle {
2454                window_id: self.window_id,
2455                view_id: self.view_id,
2456                ref_counts: self.ref_counts.clone(),
2457                view_type: PhantomData,
2458            });
2459            unsafe {
2460                Arc::decrement_strong_count(&self.ref_counts);
2461            }
2462            std::mem::forget(self);
2463            result
2464        } else {
2465            None
2466        }
2467    }
2468}
2469
2470impl Clone for AnyViewHandle {
2471    fn clone(&self) -> Self {
2472        self.ref_counts
2473            .lock()
2474            .inc_view(self.window_id, self.view_id);
2475        Self {
2476            window_id: self.window_id,
2477            view_id: self.view_id,
2478            view_type: self.view_type,
2479            ref_counts: self.ref_counts.clone(),
2480        }
2481    }
2482}
2483
2484impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
2485    fn from(handle: &ViewHandle<T>) -> Self {
2486        handle
2487            .ref_counts
2488            .lock()
2489            .inc_view(handle.window_id, handle.view_id);
2490        AnyViewHandle {
2491            window_id: handle.window_id,
2492            view_id: handle.view_id,
2493            view_type: TypeId::of::<T>(),
2494            ref_counts: handle.ref_counts.clone(),
2495        }
2496    }
2497}
2498
2499impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
2500    fn from(handle: ViewHandle<T>) -> Self {
2501        let any_handle = AnyViewHandle {
2502            window_id: handle.window_id,
2503            view_id: handle.view_id,
2504            view_type: TypeId::of::<T>(),
2505            ref_counts: handle.ref_counts.clone(),
2506        };
2507        unsafe {
2508            Arc::decrement_strong_count(&handle.ref_counts);
2509        }
2510        std::mem::forget(handle);
2511        any_handle
2512    }
2513}
2514
2515impl Drop for AnyViewHandle {
2516    fn drop(&mut self) {
2517        self.ref_counts
2518            .lock()
2519            .dec_view(self.window_id, self.view_id);
2520    }
2521}
2522
2523pub struct AnyModelHandle {
2524    model_id: usize,
2525    ref_counts: Arc<Mutex<RefCounts>>,
2526}
2527
2528impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
2529    fn from(handle: ModelHandle<T>) -> Self {
2530        handle.ref_counts.lock().inc_model(handle.model_id);
2531        Self {
2532            model_id: handle.model_id,
2533            ref_counts: handle.ref_counts.clone(),
2534        }
2535    }
2536}
2537
2538impl Drop for AnyModelHandle {
2539    fn drop(&mut self) {
2540        self.ref_counts.lock().dec_model(self.model_id);
2541    }
2542}
2543pub struct WeakViewHandle<T> {
2544    window_id: usize,
2545    view_id: usize,
2546    view_type: PhantomData<T>,
2547}
2548
2549impl<T: View> WeakViewHandle<T> {
2550    fn new(window_id: usize, view_id: usize) -> Self {
2551        Self {
2552            window_id,
2553            view_id,
2554            view_type: PhantomData,
2555        }
2556    }
2557
2558    pub fn upgrade(&self, cx: impl AsRef<AppContext>) -> Option<ViewHandle<T>> {
2559        let cx = cx.as_ref();
2560        if cx.ref_counts.lock().is_entity_alive(self.view_id) {
2561            Some(ViewHandle::new(
2562                self.window_id,
2563                self.view_id,
2564                &cx.ref_counts,
2565            ))
2566        } else {
2567            None
2568        }
2569    }
2570}
2571
2572impl<T> Clone for WeakViewHandle<T> {
2573    fn clone(&self) -> Self {
2574        Self {
2575            window_id: self.window_id,
2576            view_id: self.view_id,
2577            view_type: PhantomData,
2578        }
2579    }
2580}
2581
2582pub struct ValueHandle<T> {
2583    value_type: PhantomData<T>,
2584    tag_type_id: TypeId,
2585    id: usize,
2586    ref_counts: Weak<Mutex<RefCounts>>,
2587}
2588
2589impl<T: 'static> ValueHandle<T> {
2590    fn new(tag_type_id: TypeId, id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2591        ref_counts.lock().inc_value(tag_type_id, id);
2592        Self {
2593            value_type: PhantomData,
2594            tag_type_id,
2595            id,
2596            ref_counts: Arc::downgrade(ref_counts),
2597        }
2598    }
2599
2600    pub fn read<R>(&self, cx: &AppContext, f: impl FnOnce(&T) -> R) -> R {
2601        f(cx.values
2602            .read()
2603            .get(&(self.tag_type_id, self.id))
2604            .unwrap()
2605            .downcast_ref()
2606            .unwrap())
2607    }
2608
2609    pub fn update<R>(&self, cx: &AppContext, f: impl FnOnce(&mut T) -> R) -> R {
2610        f(cx.values
2611            .write()
2612            .get_mut(&(self.tag_type_id, self.id))
2613            .unwrap()
2614            .downcast_mut()
2615            .unwrap())
2616    }
2617}
2618
2619impl<T> Drop for ValueHandle<T> {
2620    fn drop(&mut self) {
2621        if let Some(ref_counts) = self.ref_counts.upgrade() {
2622            ref_counts.lock().dec_value(self.tag_type_id, self.id);
2623        }
2624    }
2625}
2626
2627#[derive(Default)]
2628struct RefCounts {
2629    entity_counts: HashMap<usize, usize>,
2630    value_counts: HashMap<(TypeId, usize), usize>,
2631    dropped_models: HashSet<usize>,
2632    dropped_views: HashSet<(usize, usize)>,
2633    dropped_values: HashSet<(TypeId, usize)>,
2634}
2635
2636impl RefCounts {
2637    fn inc_model(&mut self, model_id: usize) {
2638        match self.entity_counts.entry(model_id) {
2639            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
2640            Entry::Vacant(entry) => {
2641                entry.insert(1);
2642                self.dropped_models.remove(&model_id);
2643            }
2644        }
2645    }
2646
2647    fn inc_view(&mut self, window_id: usize, view_id: usize) {
2648        match self.entity_counts.entry(view_id) {
2649            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
2650            Entry::Vacant(entry) => {
2651                entry.insert(1);
2652                self.dropped_views.remove(&(window_id, view_id));
2653            }
2654        }
2655    }
2656
2657    fn inc_value(&mut self, tag_type_id: TypeId, id: usize) {
2658        *self.value_counts.entry((tag_type_id, id)).or_insert(0) += 1;
2659    }
2660
2661    fn dec_model(&mut self, model_id: usize) {
2662        let count = self.entity_counts.get_mut(&model_id).unwrap();
2663        *count -= 1;
2664        if *count == 0 {
2665            self.entity_counts.remove(&model_id);
2666            self.dropped_models.insert(model_id);
2667        }
2668    }
2669
2670    fn dec_view(&mut self, window_id: usize, view_id: usize) {
2671        let count = self.entity_counts.get_mut(&view_id).unwrap();
2672        *count -= 1;
2673        if *count == 0 {
2674            self.entity_counts.remove(&view_id);
2675            self.dropped_views.insert((window_id, view_id));
2676        }
2677    }
2678
2679    fn dec_value(&mut self, tag_type_id: TypeId, id: usize) {
2680        let key = (tag_type_id, id);
2681        let count = self.value_counts.get_mut(&key).unwrap();
2682        *count -= 1;
2683        if *count == 0 {
2684            self.value_counts.remove(&key);
2685            self.dropped_values.insert(key);
2686        }
2687    }
2688
2689    fn is_entity_alive(&self, entity_id: usize) -> bool {
2690        self.entity_counts.contains_key(&entity_id)
2691    }
2692
2693    fn take_dropped(
2694        &mut self,
2695    ) -> (
2696        HashSet<usize>,
2697        HashSet<(usize, usize)>,
2698        HashSet<(TypeId, usize)>,
2699    ) {
2700        let mut dropped_models = HashSet::new();
2701        let mut dropped_views = HashSet::new();
2702        let mut dropped_values = HashSet::new();
2703        std::mem::swap(&mut self.dropped_models, &mut dropped_models);
2704        std::mem::swap(&mut self.dropped_views, &mut dropped_views);
2705        std::mem::swap(&mut self.dropped_values, &mut dropped_values);
2706        (dropped_models, dropped_views, dropped_values)
2707    }
2708}
2709
2710enum Subscription {
2711    FromModel {
2712        model_id: usize,
2713        callback: Box<dyn FnMut(&mut dyn Any, &dyn Any, &mut MutableAppContext, usize)>,
2714    },
2715    FromView {
2716        window_id: usize,
2717        view_id: usize,
2718        callback: Box<dyn FnMut(&mut dyn Any, &dyn Any, &mut MutableAppContext, usize, usize)>,
2719    },
2720}
2721
2722enum ModelObservation {
2723    FromModel {
2724        model_id: usize,
2725        callback: Box<dyn FnMut(&mut dyn Any, usize, &mut MutableAppContext, usize)>,
2726    },
2727    FromView {
2728        window_id: usize,
2729        view_id: usize,
2730        callback: Box<dyn FnMut(&mut dyn Any, usize, &mut MutableAppContext, usize, usize)>,
2731    },
2732}
2733
2734struct ViewObservation {
2735    window_id: usize,
2736    view_id: usize,
2737    callback: Box<dyn FnMut(&mut dyn Any, usize, usize, &mut MutableAppContext, usize, usize)>,
2738}
2739
2740#[cfg(test)]
2741mod tests {
2742    use super::*;
2743    use crate::elements::*;
2744    use smol::future::poll_once;
2745
2746    #[crate::test(self)]
2747    fn test_model_handles(cx: &mut MutableAppContext) {
2748        struct Model {
2749            other: Option<ModelHandle<Model>>,
2750            events: Vec<String>,
2751        }
2752
2753        impl Entity for Model {
2754            type Event = usize;
2755        }
2756
2757        impl Model {
2758            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
2759                if let Some(other) = other.as_ref() {
2760                    cx.observe(other, |me, _, _| {
2761                        me.events.push("notified".into());
2762                    });
2763                    cx.subscribe(other, |me, event, _| {
2764                        me.events.push(format!("observed event {}", event));
2765                    });
2766                }
2767
2768                Self {
2769                    other,
2770                    events: Vec::new(),
2771                }
2772            }
2773        }
2774
2775        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
2776        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
2777        assert_eq!(cx.cx.models.len(), 2);
2778
2779        handle_1.update(cx, |model, cx| {
2780            model.events.push("updated".into());
2781            cx.emit(1);
2782            cx.notify();
2783            cx.emit(2);
2784        });
2785        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
2786        assert_eq!(
2787            handle_2.read(cx).events,
2788            vec![
2789                "observed event 1".to_string(),
2790                "notified".to_string(),
2791                "observed event 2".to_string(),
2792            ]
2793        );
2794
2795        handle_2.update(cx, |model, _| {
2796            drop(handle_1);
2797            model.other.take();
2798        });
2799
2800        assert_eq!(cx.cx.models.len(), 1);
2801        assert!(cx.subscriptions.is_empty());
2802        assert!(cx.model_observations.is_empty());
2803    }
2804
2805    #[crate::test(self)]
2806    fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) {
2807        #[derive(Default)]
2808        struct Model {
2809            events: Vec<usize>,
2810        }
2811
2812        impl Entity for Model {
2813            type Event = usize;
2814        }
2815
2816        let handle_1 = cx.add_model(|_| Model::default());
2817        let handle_2 = cx.add_model(|_| Model::default());
2818        let handle_2b = handle_2.clone();
2819
2820        handle_1.update(cx, |_, c| {
2821            c.subscribe(&handle_2, move |model: &mut Model, event, c| {
2822                model.events.push(*event);
2823
2824                c.subscribe(&handle_2b, |model, event, _| {
2825                    model.events.push(*event * 2);
2826                });
2827            });
2828        });
2829
2830        handle_2.update(cx, |_, c| c.emit(7));
2831        assert_eq!(handle_1.read(cx).events, vec![7]);
2832
2833        handle_2.update(cx, |_, c| c.emit(5));
2834        assert_eq!(handle_1.read(cx).events, vec![7, 10, 5]);
2835    }
2836
2837    #[crate::test(self)]
2838    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
2839        #[derive(Default)]
2840        struct Model {
2841            count: usize,
2842            events: Vec<usize>,
2843        }
2844
2845        impl Entity for Model {
2846            type Event = ();
2847        }
2848
2849        let handle_1 = cx.add_model(|_| Model::default());
2850        let handle_2 = cx.add_model(|_| Model::default());
2851        let handle_2b = handle_2.clone();
2852
2853        handle_1.update(cx, |_, c| {
2854            c.observe(&handle_2, move |model, observed, c| {
2855                model.events.push(observed.read(c).count);
2856                c.observe(&handle_2b, |model, observed, c| {
2857                    model.events.push(observed.read(c).count * 2);
2858                });
2859            });
2860        });
2861
2862        handle_2.update(cx, |model, c| {
2863            model.count = 7;
2864            c.notify()
2865        });
2866        assert_eq!(handle_1.read(cx).events, vec![7]);
2867
2868        handle_2.update(cx, |model, c| {
2869            model.count = 5;
2870            c.notify()
2871        });
2872        assert_eq!(handle_1.read(cx).events, vec![7, 10, 5])
2873    }
2874
2875    #[crate::test(self)]
2876    fn test_view_handles(cx: &mut MutableAppContext) {
2877        struct View {
2878            other: Option<ViewHandle<View>>,
2879            events: Vec<String>,
2880        }
2881
2882        impl Entity for View {
2883            type Event = usize;
2884        }
2885
2886        impl super::View for View {
2887            fn render<'a>(&self, _: &AppContext) -> ElementBox {
2888                Empty::new().boxed()
2889            }
2890
2891            fn ui_name() -> &'static str {
2892                "View"
2893            }
2894        }
2895
2896        impl View {
2897            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
2898                if let Some(other) = other.as_ref() {
2899                    cx.subscribe_to_view(other, |me, _, event, _| {
2900                        me.events.push(format!("observed event {}", event));
2901                    });
2902                }
2903                Self {
2904                    other,
2905                    events: Vec::new(),
2906                }
2907            }
2908        }
2909
2910        let (window_id, _) = cx.add_window(|cx| View::new(None, cx));
2911        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
2912        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
2913        assert_eq!(cx.cx.views.len(), 3);
2914
2915        handle_1.update(cx, |view, cx| {
2916            view.events.push("updated".into());
2917            cx.emit(1);
2918            cx.emit(2);
2919        });
2920        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
2921        assert_eq!(
2922            handle_2.read(cx).events,
2923            vec![
2924                "observed event 1".to_string(),
2925                "observed event 2".to_string(),
2926            ]
2927        );
2928
2929        handle_2.update(cx, |view, _| {
2930            drop(handle_1);
2931            view.other.take();
2932        });
2933
2934        assert_eq!(cx.cx.views.len(), 2);
2935        assert!(cx.subscriptions.is_empty());
2936        assert!(cx.model_observations.is_empty());
2937    }
2938
2939    #[crate::test(self)]
2940    fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) {
2941        #[derive(Default)]
2942        struct View {
2943            events: Vec<usize>,
2944        }
2945
2946        impl Entity for View {
2947            type Event = usize;
2948        }
2949
2950        impl super::View for View {
2951            fn render<'a>(&self, _: &AppContext) -> ElementBox {
2952                Empty::new().boxed()
2953            }
2954
2955            fn ui_name() -> &'static str {
2956                "View"
2957            }
2958        }
2959
2960        struct Model;
2961
2962        impl Entity for Model {
2963            type Event = usize;
2964        }
2965
2966        let (window_id, handle_1) = cx.add_window(|_| View::default());
2967        let handle_2 = cx.add_view(window_id, |_| View::default());
2968        let handle_2b = handle_2.clone();
2969        let handle_3 = cx.add_model(|_| Model);
2970
2971        handle_1.update(cx, |_, c| {
2972            c.subscribe_to_view(&handle_2, move |me, _, event, c| {
2973                me.events.push(*event);
2974
2975                c.subscribe_to_view(&handle_2b, |me, _, event, _| {
2976                    me.events.push(*event * 2);
2977                });
2978            });
2979
2980            c.subscribe_to_model(&handle_3, |me, _, event, _| {
2981                me.events.push(*event);
2982            })
2983        });
2984
2985        handle_2.update(cx, |_, c| c.emit(7));
2986        assert_eq!(handle_1.read(cx).events, vec![7]);
2987
2988        handle_2.update(cx, |_, c| c.emit(5));
2989        assert_eq!(handle_1.read(cx).events, vec![7, 10, 5]);
2990
2991        handle_3.update(cx, |_, c| c.emit(9));
2992        assert_eq!(handle_1.read(cx).events, vec![7, 10, 5, 9]);
2993    }
2994
2995    #[crate::test(self)]
2996    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
2997        struct View;
2998
2999        impl Entity for View {
3000            type Event = ();
3001        }
3002
3003        impl super::View for View {
3004            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3005                Empty::new().boxed()
3006            }
3007
3008            fn ui_name() -> &'static str {
3009                "View"
3010            }
3011        }
3012
3013        struct Model;
3014
3015        impl Entity for Model {
3016            type Event = ();
3017        }
3018
3019        let (window_id, _) = cx.add_window(|_| View);
3020        let observing_view = cx.add_view(window_id, |_| View);
3021        let emitting_view = cx.add_view(window_id, |_| View);
3022        let observing_model = cx.add_model(|_| Model);
3023        let observed_model = cx.add_model(|_| Model);
3024
3025        observing_view.update(cx, |_, cx| {
3026            cx.subscribe_to_view(&emitting_view, |_, _, _, _| {});
3027            cx.subscribe_to_model(&observed_model, |_, _, _, _| {});
3028        });
3029        observing_model.update(cx, |_, cx| {
3030            cx.subscribe(&observed_model, |_, _, _| {});
3031        });
3032
3033        cx.update(|| {
3034            drop(observing_view);
3035            drop(observing_model);
3036        });
3037
3038        emitting_view.update(cx, |_, cx| cx.emit(()));
3039        observed_model.update(cx, |_, cx| cx.emit(()));
3040    }
3041
3042    #[crate::test(self)]
3043    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
3044        #[derive(Default)]
3045        struct View {
3046            events: Vec<usize>,
3047        }
3048
3049        impl Entity for View {
3050            type Event = usize;
3051        }
3052
3053        impl super::View for View {
3054            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3055                Empty::new().boxed()
3056            }
3057
3058            fn ui_name() -> &'static str {
3059                "View"
3060            }
3061        }
3062
3063        #[derive(Default)]
3064        struct Model {
3065            count: usize,
3066        }
3067
3068        impl Entity for Model {
3069            type Event = ();
3070        }
3071
3072        let (_, view) = cx.add_window(|_| View::default());
3073        let model = cx.add_model(|_| Model::default());
3074
3075        view.update(cx, |_, c| {
3076            c.observe_model(&model, |me, observed, c| {
3077                me.events.push(observed.read(c).count)
3078            });
3079        });
3080
3081        model.update(cx, |model, c| {
3082            model.count = 11;
3083            c.notify();
3084        });
3085        assert_eq!(view.read(cx).events, vec![11]);
3086    }
3087
3088    #[crate::test(self)]
3089    fn test_dropping_observers(cx: &mut MutableAppContext) {
3090        struct View;
3091
3092        impl Entity for View {
3093            type Event = ();
3094        }
3095
3096        impl super::View for View {
3097            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3098                Empty::new().boxed()
3099            }
3100
3101            fn ui_name() -> &'static str {
3102                "View"
3103            }
3104        }
3105
3106        struct Model;
3107
3108        impl Entity for Model {
3109            type Event = ();
3110        }
3111
3112        let (window_id, _) = cx.add_window(|_| View);
3113        let observing_view = cx.add_view(window_id, |_| View);
3114        let observing_model = cx.add_model(|_| Model);
3115        let observed_model = cx.add_model(|_| Model);
3116
3117        observing_view.update(cx, |_, cx| {
3118            cx.observe_model(&observed_model, |_, _, _| {});
3119        });
3120        observing_model.update(cx, |_, cx| {
3121            cx.observe(&observed_model, |_, _, _| {});
3122        });
3123
3124        cx.update(|| {
3125            drop(observing_view);
3126            drop(observing_model);
3127        });
3128
3129        observed_model.update(cx, |_, cx| cx.notify());
3130    }
3131
3132    #[crate::test(self)]
3133    fn test_focus(cx: &mut MutableAppContext) {
3134        struct View {
3135            name: String,
3136            events: Arc<Mutex<Vec<String>>>,
3137        }
3138
3139        impl Entity for View {
3140            type Event = ();
3141        }
3142
3143        impl super::View for View {
3144            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3145                Empty::new().boxed()
3146            }
3147
3148            fn ui_name() -> &'static str {
3149                "View"
3150            }
3151
3152            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
3153                self.events.lock().push(format!("{} focused", &self.name));
3154            }
3155
3156            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
3157                self.events.lock().push(format!("{} blurred", &self.name));
3158            }
3159        }
3160
3161        let events: Arc<Mutex<Vec<String>>> = Default::default();
3162        let (window_id, view_1) = cx.add_window(|_| View {
3163            events: events.clone(),
3164            name: "view 1".to_string(),
3165        });
3166        let view_2 = cx.add_view(window_id, |_| View {
3167            events: events.clone(),
3168            name: "view 2".to_string(),
3169        });
3170
3171        view_1.update(cx, |_, cx| cx.focus(&view_2));
3172        view_1.update(cx, |_, cx| cx.focus(&view_1));
3173        view_1.update(cx, |_, cx| cx.focus(&view_2));
3174        view_1.update(cx, |_, _| drop(view_2));
3175
3176        assert_eq!(
3177            *events.lock(),
3178            [
3179                "view 1 focused".to_string(),
3180                "view 1 blurred".to_string(),
3181                "view 2 focused".to_string(),
3182                "view 2 blurred".to_string(),
3183                "view 1 focused".to_string(),
3184                "view 1 blurred".to_string(),
3185                "view 2 focused".to_string(),
3186                "view 1 focused".to_string(),
3187            ],
3188        );
3189    }
3190
3191    #[crate::test(self)]
3192    fn test_dispatch_action(cx: &mut MutableAppContext) {
3193        struct ViewA {
3194            id: usize,
3195        }
3196
3197        impl Entity for ViewA {
3198            type Event = ();
3199        }
3200
3201        impl View for ViewA {
3202            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3203                Empty::new().boxed()
3204            }
3205
3206            fn ui_name() -> &'static str {
3207                "View"
3208            }
3209        }
3210
3211        struct ViewB {
3212            id: usize,
3213        }
3214
3215        impl Entity for ViewB {
3216            type Event = ();
3217        }
3218
3219        impl View for ViewB {
3220            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3221                Empty::new().boxed()
3222            }
3223
3224            fn ui_name() -> &'static str {
3225                "View"
3226            }
3227        }
3228
3229        struct ActionArg {
3230            foo: String,
3231        }
3232
3233        let actions = Rc::new(RefCell::new(Vec::new()));
3234
3235        let actions_clone = actions.clone();
3236        cx.add_global_action("action", move |_: &ActionArg, _: &mut MutableAppContext| {
3237            actions_clone.borrow_mut().push("global a".to_string());
3238        });
3239
3240        let actions_clone = actions.clone();
3241        cx.add_global_action("action", move |_: &ActionArg, _: &mut MutableAppContext| {
3242            actions_clone.borrow_mut().push("global b".to_string());
3243        });
3244
3245        let actions_clone = actions.clone();
3246        cx.add_action("action", move |view: &mut ViewA, arg: &ActionArg, cx| {
3247            assert_eq!(arg.foo, "bar");
3248            cx.propagate_action();
3249            actions_clone.borrow_mut().push(format!("{} a", view.id));
3250        });
3251
3252        let actions_clone = actions.clone();
3253        cx.add_action("action", move |view: &mut ViewA, _: &ActionArg, cx| {
3254            if view.id != 1 {
3255                cx.propagate_action();
3256            }
3257            actions_clone.borrow_mut().push(format!("{} b", view.id));
3258        });
3259
3260        let actions_clone = actions.clone();
3261        cx.add_action("action", move |view: &mut ViewB, _: &ActionArg, cx| {
3262            cx.propagate_action();
3263            actions_clone.borrow_mut().push(format!("{} c", view.id));
3264        });
3265
3266        let actions_clone = actions.clone();
3267        cx.add_action("action", move |view: &mut ViewB, _: &ActionArg, cx| {
3268            cx.propagate_action();
3269            actions_clone.borrow_mut().push(format!("{} d", view.id));
3270        });
3271
3272        let (window_id, view_1) = cx.add_window(|_| ViewA { id: 1 });
3273        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
3274        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
3275        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
3276
3277        cx.dispatch_action(
3278            window_id,
3279            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
3280            "action",
3281            ActionArg { foo: "bar".into() },
3282        );
3283
3284        assert_eq!(
3285            *actions.borrow(),
3286            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "1 b"]
3287        );
3288
3289        // Remove view_1, which doesn't propagate the action
3290        actions.borrow_mut().clear();
3291        cx.dispatch_action(
3292            window_id,
3293            vec![view_2.id(), view_3.id(), view_4.id()],
3294            "action",
3295            ActionArg { foo: "bar".into() },
3296        );
3297
3298        assert_eq!(
3299            *actions.borrow(),
3300            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "global b", "global a"]
3301        );
3302    }
3303
3304    #[crate::test(self)]
3305    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
3306        use std::cell::Cell;
3307
3308        #[derive(Clone)]
3309        struct ActionArg {
3310            key: String,
3311        }
3312
3313        struct View {
3314            id: usize,
3315            keymap_context: keymap::Context,
3316        }
3317
3318        impl Entity for View {
3319            type Event = ();
3320        }
3321
3322        impl super::View for View {
3323            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3324                Empty::new().boxed()
3325            }
3326
3327            fn ui_name() -> &'static str {
3328                "View"
3329            }
3330
3331            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
3332                self.keymap_context.clone()
3333            }
3334        }
3335
3336        impl View {
3337            fn new(id: usize) -> Self {
3338                View {
3339                    id,
3340                    keymap_context: keymap::Context::default(),
3341                }
3342            }
3343        }
3344
3345        let mut view_1 = View::new(1);
3346        let mut view_2 = View::new(2);
3347        let mut view_3 = View::new(3);
3348        view_1.keymap_context.set.insert("a".into());
3349        view_2.keymap_context.set.insert("b".into());
3350        view_3.keymap_context.set.insert("c".into());
3351
3352        let (window_id, view_1) = cx.add_window(|_| view_1);
3353        let view_2 = cx.add_view(window_id, |_| view_2);
3354        let view_3 = cx.add_view(window_id, |_| view_3);
3355
3356        // This keymap's only binding dispatches an action on view 2 because that view will have
3357        // "a" and "b" in its context, but not "c".
3358        let binding = keymap::Binding::new("a", "action", Some("a && b && !c"))
3359            .with_arg(ActionArg { key: "a".into() });
3360        cx.add_bindings(vec![binding]);
3361
3362        let handled_action = Rc::new(Cell::new(false));
3363        let handled_action_clone = handled_action.clone();
3364        cx.add_action("action", move |view: &mut View, arg: &ActionArg, _| {
3365            handled_action_clone.set(true);
3366            assert_eq!(view.id, 2);
3367            assert_eq!(arg.key, "a");
3368        });
3369
3370        cx.dispatch_keystroke(
3371            window_id,
3372            vec![view_1.id(), view_2.id(), view_3.id()],
3373            &Keystroke::parse("a").unwrap(),
3374        )
3375        .unwrap();
3376
3377        assert!(handled_action.get());
3378    }
3379
3380    #[crate::test(self)]
3381    async fn test_model_condition(mut cx: TestAppContext) {
3382        struct Counter(usize);
3383
3384        impl super::Entity for Counter {
3385            type Event = ();
3386        }
3387
3388        impl Counter {
3389            fn inc(&mut self, cx: &mut ModelContext<Self>) {
3390                self.0 += 1;
3391                cx.notify();
3392            }
3393        }
3394
3395        let model = cx.add_model(|_| Counter(0));
3396
3397        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
3398        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
3399        smol::pin!(condition1, condition2);
3400
3401        model.update(&mut cx, |model, cx| model.inc(cx));
3402        assert_eq!(poll_once(&mut condition1).await, None);
3403        assert_eq!(poll_once(&mut condition2).await, None);
3404
3405        model.update(&mut cx, |model, cx| model.inc(cx));
3406        assert_eq!(poll_once(&mut condition1).await, Some(()));
3407        assert_eq!(poll_once(&mut condition2).await, None);
3408
3409        model.update(&mut cx, |model, cx| model.inc(cx));
3410        assert_eq!(poll_once(&mut condition2).await, Some(()));
3411
3412        model.update(&mut cx, |_, cx| cx.notify());
3413    }
3414
3415    #[crate::test(self)]
3416    #[should_panic]
3417    async fn test_model_condition_timeout(mut cx: TestAppContext) {
3418        struct Model;
3419
3420        impl super::Entity for Model {
3421            type Event = ();
3422        }
3423
3424        let model = cx.add_model(|_| Model);
3425        model.condition(&cx, |_, _| false).await;
3426    }
3427
3428    #[crate::test(self)]
3429    #[should_panic(expected = "model dropped with pending condition")]
3430    async fn test_model_condition_panic_on_drop(mut cx: TestAppContext) {
3431        struct Model;
3432
3433        impl super::Entity for Model {
3434            type Event = ();
3435        }
3436
3437        let model = cx.add_model(|_| Model);
3438        let condition = model.condition(&cx, |_, _| false);
3439        cx.update(|_| drop(model));
3440        condition.await;
3441    }
3442
3443    #[crate::test(self)]
3444    async fn test_view_condition(mut cx: TestAppContext) {
3445        struct Counter(usize);
3446
3447        impl super::Entity for Counter {
3448            type Event = ();
3449        }
3450
3451        impl super::View for Counter {
3452            fn ui_name() -> &'static str {
3453                "test view"
3454            }
3455
3456            fn render(&self, _: &AppContext) -> ElementBox {
3457                Empty::new().boxed()
3458            }
3459        }
3460
3461        impl Counter {
3462            fn inc(&mut self, cx: &mut ViewContext<Self>) {
3463                self.0 += 1;
3464                cx.notify();
3465            }
3466        }
3467
3468        let (_, view) = cx.add_window(|_| Counter(0));
3469
3470        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
3471        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
3472        smol::pin!(condition1, condition2);
3473
3474        view.update(&mut cx, |view, cx| view.inc(cx));
3475        assert_eq!(poll_once(&mut condition1).await, None);
3476        assert_eq!(poll_once(&mut condition2).await, None);
3477
3478        view.update(&mut cx, |view, cx| view.inc(cx));
3479        assert_eq!(poll_once(&mut condition1).await, Some(()));
3480        assert_eq!(poll_once(&mut condition2).await, None);
3481
3482        view.update(&mut cx, |view, cx| view.inc(cx));
3483        assert_eq!(poll_once(&mut condition2).await, Some(()));
3484        view.update(&mut cx, |_, cx| cx.notify());
3485    }
3486
3487    #[crate::test(self)]
3488    #[should_panic]
3489    async fn test_view_condition_timeout(mut cx: TestAppContext) {
3490        struct View;
3491
3492        impl super::Entity for View {
3493            type Event = ();
3494        }
3495
3496        impl super::View for View {
3497            fn ui_name() -> &'static str {
3498                "test view"
3499            }
3500
3501            fn render(&self, _: &AppContext) -> ElementBox {
3502                Empty::new().boxed()
3503            }
3504        }
3505
3506        let (_, view) = cx.add_window(|_| View);
3507        view.condition(&cx, |_, _| false).await;
3508    }
3509
3510    #[crate::test(self)]
3511    #[should_panic(expected = "view dropped with pending condition")]
3512    async fn test_view_condition_panic_on_drop(mut cx: TestAppContext) {
3513        struct View;
3514
3515        impl super::Entity for View {
3516            type Event = ();
3517        }
3518
3519        impl super::View for View {
3520            fn ui_name() -> &'static str {
3521                "test view"
3522            }
3523
3524            fn render(&self, _: &AppContext) -> ElementBox {
3525                Empty::new().boxed()
3526            }
3527        }
3528
3529        let window_id = cx.add_window(|_| View).0;
3530        let view = cx.add_view(window_id, |_| View);
3531
3532        let condition = view.condition(&cx, |_, _| false);
3533        cx.update(|_| drop(view));
3534        condition.await;
3535    }
3536}