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(2)
2135        } else {
2136            Duration::from_millis(500)
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> Clone for WeakModelHandle<T> {
2249    fn clone(&self) -> Self {
2250        Self {
2251            model_id: self.model_id,
2252            model_type: PhantomData,
2253        }
2254    }
2255}
2256
2257pub struct ViewHandle<T> {
2258    window_id: usize,
2259    view_id: usize,
2260    view_type: PhantomData<T>,
2261    ref_counts: Arc<Mutex<RefCounts>>,
2262}
2263
2264impl<T: View> ViewHandle<T> {
2265    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2266        ref_counts.lock().inc_view(window_id, view_id);
2267        Self {
2268            window_id,
2269            view_id,
2270            view_type: PhantomData,
2271            ref_counts: ref_counts.clone(),
2272        }
2273    }
2274
2275    pub fn downgrade(&self) -> WeakViewHandle<T> {
2276        WeakViewHandle::new(self.window_id, self.view_id)
2277    }
2278
2279    pub fn window_id(&self) -> usize {
2280        self.window_id
2281    }
2282
2283    pub fn id(&self) -> usize {
2284        self.view_id
2285    }
2286
2287    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
2288        cx.read_view(self)
2289    }
2290
2291    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
2292    where
2293        C: ReadViewWith,
2294        F: FnOnce(&T, &AppContext) -> S,
2295    {
2296        cx.read_view_with(self, read)
2297    }
2298
2299    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2300    where
2301        C: UpdateView,
2302        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2303    {
2304        cx.update_view(self, update)
2305    }
2306
2307    pub fn is_focused(&self, cx: &AppContext) -> bool {
2308        cx.focused_view_id(self.window_id)
2309            .map_or(false, |focused_id| focused_id == self.view_id)
2310    }
2311
2312    pub fn condition(
2313        &self,
2314        cx: &TestAppContext,
2315        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2316    ) -> impl Future<Output = ()> {
2317        let (tx, mut rx) = mpsc::channel(1024);
2318
2319        let mut cx = cx.cx.borrow_mut();
2320        self.update(&mut *cx, |_, cx| {
2321            cx.observe_view(self, {
2322                let mut tx = tx.clone();
2323                move |_, _, _| {
2324                    tx.blocking_send(()).ok();
2325                }
2326            });
2327
2328            cx.subscribe(self, {
2329                let mut tx = tx.clone();
2330                move |_, _, _| {
2331                    tx.blocking_send(()).ok();
2332                }
2333            })
2334        });
2335
2336        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2337        let handle = self.downgrade();
2338        let duration = if std::env::var("CI").is_ok() {
2339            Duration::from_secs(2)
2340        } else {
2341            Duration::from_millis(500)
2342        };
2343
2344        async move {
2345            timeout(duration, async move {
2346                loop {
2347                    {
2348                        let cx = cx.borrow();
2349                        let cx = cx.as_ref();
2350                        if predicate(
2351                            handle
2352                                .upgrade(cx)
2353                                .expect("view dropped with pending condition")
2354                                .read(cx),
2355                            cx,
2356                        ) {
2357                            break;
2358                        }
2359                    }
2360
2361                    rx.recv()
2362                        .await
2363                        .expect("view dropped with pending condition");
2364                }
2365            })
2366            .await
2367            .expect("condition timed out");
2368        }
2369    }
2370}
2371
2372impl<T> Clone for ViewHandle<T> {
2373    fn clone(&self) -> Self {
2374        self.ref_counts
2375            .lock()
2376            .inc_view(self.window_id, self.view_id);
2377        Self {
2378            window_id: self.window_id,
2379            view_id: self.view_id,
2380            view_type: PhantomData,
2381            ref_counts: self.ref_counts.clone(),
2382        }
2383    }
2384}
2385
2386impl<T> PartialEq for ViewHandle<T> {
2387    fn eq(&self, other: &Self) -> bool {
2388        self.window_id == other.window_id && self.view_id == other.view_id
2389    }
2390}
2391
2392impl<T> Eq for ViewHandle<T> {}
2393
2394impl<T> Debug for ViewHandle<T> {
2395    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2396        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
2397            .field("window_id", &self.window_id)
2398            .field("view_id", &self.view_id)
2399            .finish()
2400    }
2401}
2402
2403impl<T> Drop for ViewHandle<T> {
2404    fn drop(&mut self) {
2405        self.ref_counts
2406            .lock()
2407            .dec_view(self.window_id, self.view_id);
2408    }
2409}
2410
2411impl<T> Handle<T> for ViewHandle<T> {
2412    fn id(&self) -> usize {
2413        self.view_id
2414    }
2415
2416    fn location(&self) -> EntityLocation {
2417        EntityLocation::View(self.window_id, self.view_id)
2418    }
2419}
2420
2421pub struct AnyViewHandle {
2422    window_id: usize,
2423    view_id: usize,
2424    view_type: TypeId,
2425    ref_counts: Arc<Mutex<RefCounts>>,
2426}
2427
2428impl AnyViewHandle {
2429    pub fn id(&self) -> usize {
2430        self.view_id
2431    }
2432
2433    pub fn is<T: 'static>(&self) -> bool {
2434        TypeId::of::<T>() == self.view_type
2435    }
2436
2437    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
2438        if self.is::<T>() {
2439            let result = Some(ViewHandle {
2440                window_id: self.window_id,
2441                view_id: self.view_id,
2442                ref_counts: self.ref_counts.clone(),
2443                view_type: PhantomData,
2444            });
2445            unsafe {
2446                Arc::decrement_strong_count(&self.ref_counts);
2447            }
2448            std::mem::forget(self);
2449            result
2450        } else {
2451            None
2452        }
2453    }
2454}
2455
2456impl Clone for AnyViewHandle {
2457    fn clone(&self) -> Self {
2458        self.ref_counts
2459            .lock()
2460            .inc_view(self.window_id, self.view_id);
2461        Self {
2462            window_id: self.window_id,
2463            view_id: self.view_id,
2464            view_type: self.view_type,
2465            ref_counts: self.ref_counts.clone(),
2466        }
2467    }
2468}
2469
2470impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
2471    fn from(handle: &ViewHandle<T>) -> Self {
2472        handle
2473            .ref_counts
2474            .lock()
2475            .inc_view(handle.window_id, handle.view_id);
2476        AnyViewHandle {
2477            window_id: handle.window_id,
2478            view_id: handle.view_id,
2479            view_type: TypeId::of::<T>(),
2480            ref_counts: handle.ref_counts.clone(),
2481        }
2482    }
2483}
2484
2485impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
2486    fn from(handle: ViewHandle<T>) -> Self {
2487        let any_handle = AnyViewHandle {
2488            window_id: handle.window_id,
2489            view_id: handle.view_id,
2490            view_type: TypeId::of::<T>(),
2491            ref_counts: handle.ref_counts.clone(),
2492        };
2493        unsafe {
2494            Arc::decrement_strong_count(&handle.ref_counts);
2495        }
2496        std::mem::forget(handle);
2497        any_handle
2498    }
2499}
2500
2501impl Drop for AnyViewHandle {
2502    fn drop(&mut self) {
2503        self.ref_counts
2504            .lock()
2505            .dec_view(self.window_id, self.view_id);
2506    }
2507}
2508
2509pub struct AnyModelHandle {
2510    model_id: usize,
2511    ref_counts: Arc<Mutex<RefCounts>>,
2512}
2513
2514impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
2515    fn from(handle: ModelHandle<T>) -> Self {
2516        handle.ref_counts.lock().inc_model(handle.model_id);
2517        Self {
2518            model_id: handle.model_id,
2519            ref_counts: handle.ref_counts.clone(),
2520        }
2521    }
2522}
2523
2524impl Drop for AnyModelHandle {
2525    fn drop(&mut self) {
2526        self.ref_counts.lock().dec_model(self.model_id);
2527    }
2528}
2529pub struct WeakViewHandle<T> {
2530    window_id: usize,
2531    view_id: usize,
2532    view_type: PhantomData<T>,
2533}
2534
2535impl<T: View> WeakViewHandle<T> {
2536    fn new(window_id: usize, view_id: usize) -> Self {
2537        Self {
2538            window_id,
2539            view_id,
2540            view_type: PhantomData,
2541        }
2542    }
2543
2544    pub fn upgrade(&self, cx: impl AsRef<AppContext>) -> Option<ViewHandle<T>> {
2545        let cx = cx.as_ref();
2546        if cx.ref_counts.lock().is_entity_alive(self.view_id) {
2547            Some(ViewHandle::new(
2548                self.window_id,
2549                self.view_id,
2550                &cx.ref_counts,
2551            ))
2552        } else {
2553            None
2554        }
2555    }
2556}
2557
2558impl<T> Clone for WeakViewHandle<T> {
2559    fn clone(&self) -> Self {
2560        Self {
2561            window_id: self.window_id,
2562            view_id: self.view_id,
2563            view_type: PhantomData,
2564        }
2565    }
2566}
2567
2568pub struct ValueHandle<T> {
2569    value_type: PhantomData<T>,
2570    tag_type_id: TypeId,
2571    id: usize,
2572    ref_counts: Weak<Mutex<RefCounts>>,
2573}
2574
2575impl<T: 'static> ValueHandle<T> {
2576    fn new(tag_type_id: TypeId, id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2577        ref_counts.lock().inc_value(tag_type_id, id);
2578        Self {
2579            value_type: PhantomData,
2580            tag_type_id,
2581            id,
2582            ref_counts: Arc::downgrade(ref_counts),
2583        }
2584    }
2585
2586    pub fn read<R>(&self, cx: &AppContext, f: impl FnOnce(&T) -> R) -> R {
2587        f(cx.values
2588            .read()
2589            .get(&(self.tag_type_id, self.id))
2590            .unwrap()
2591            .downcast_ref()
2592            .unwrap())
2593    }
2594
2595    pub fn update<R>(&self, cx: &AppContext, f: impl FnOnce(&mut T) -> R) -> R {
2596        f(cx.values
2597            .write()
2598            .get_mut(&(self.tag_type_id, self.id))
2599            .unwrap()
2600            .downcast_mut()
2601            .unwrap())
2602    }
2603}
2604
2605impl<T> Drop for ValueHandle<T> {
2606    fn drop(&mut self) {
2607        if let Some(ref_counts) = self.ref_counts.upgrade() {
2608            ref_counts.lock().dec_value(self.tag_type_id, self.id);
2609        }
2610    }
2611}
2612
2613#[derive(Default)]
2614struct RefCounts {
2615    entity_counts: HashMap<usize, usize>,
2616    value_counts: HashMap<(TypeId, usize), usize>,
2617    dropped_models: HashSet<usize>,
2618    dropped_views: HashSet<(usize, usize)>,
2619    dropped_values: HashSet<(TypeId, usize)>,
2620}
2621
2622impl RefCounts {
2623    fn inc_model(&mut self, model_id: usize) {
2624        match self.entity_counts.entry(model_id) {
2625            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
2626            Entry::Vacant(entry) => {
2627                entry.insert(1);
2628                self.dropped_models.remove(&model_id);
2629            }
2630        }
2631    }
2632
2633    fn inc_view(&mut self, window_id: usize, view_id: usize) {
2634        match self.entity_counts.entry(view_id) {
2635            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
2636            Entry::Vacant(entry) => {
2637                entry.insert(1);
2638                self.dropped_views.remove(&(window_id, view_id));
2639            }
2640        }
2641    }
2642
2643    fn inc_value(&mut self, tag_type_id: TypeId, id: usize) {
2644        *self.value_counts.entry((tag_type_id, id)).or_insert(0) += 1;
2645    }
2646
2647    fn dec_model(&mut self, model_id: usize) {
2648        let count = self.entity_counts.get_mut(&model_id).unwrap();
2649        *count -= 1;
2650        if *count == 0 {
2651            self.entity_counts.remove(&model_id);
2652            self.dropped_models.insert(model_id);
2653        }
2654    }
2655
2656    fn dec_view(&mut self, window_id: usize, view_id: usize) {
2657        let count = self.entity_counts.get_mut(&view_id).unwrap();
2658        *count -= 1;
2659        if *count == 0 {
2660            self.entity_counts.remove(&view_id);
2661            self.dropped_views.insert((window_id, view_id));
2662        }
2663    }
2664
2665    fn dec_value(&mut self, tag_type_id: TypeId, id: usize) {
2666        let key = (tag_type_id, id);
2667        let count = self.value_counts.get_mut(&key).unwrap();
2668        *count -= 1;
2669        if *count == 0 {
2670            self.value_counts.remove(&key);
2671            self.dropped_values.insert(key);
2672        }
2673    }
2674
2675    fn is_entity_alive(&self, entity_id: usize) -> bool {
2676        self.entity_counts.contains_key(&entity_id)
2677    }
2678
2679    fn take_dropped(
2680        &mut self,
2681    ) -> (
2682        HashSet<usize>,
2683        HashSet<(usize, usize)>,
2684        HashSet<(TypeId, usize)>,
2685    ) {
2686        let mut dropped_models = HashSet::new();
2687        let mut dropped_views = HashSet::new();
2688        let mut dropped_values = HashSet::new();
2689        std::mem::swap(&mut self.dropped_models, &mut dropped_models);
2690        std::mem::swap(&mut self.dropped_views, &mut dropped_views);
2691        std::mem::swap(&mut self.dropped_values, &mut dropped_values);
2692        (dropped_models, dropped_views, dropped_values)
2693    }
2694}
2695
2696enum Subscription {
2697    FromModel {
2698        model_id: usize,
2699        callback: Box<dyn FnMut(&mut dyn Any, &dyn Any, &mut MutableAppContext, usize)>,
2700    },
2701    FromView {
2702        window_id: usize,
2703        view_id: usize,
2704        callback: Box<dyn FnMut(&mut dyn Any, &dyn Any, &mut MutableAppContext, usize, usize)>,
2705    },
2706}
2707
2708enum ModelObservation {
2709    FromModel {
2710        model_id: usize,
2711        callback: Box<dyn FnMut(&mut dyn Any, usize, &mut MutableAppContext, usize)>,
2712    },
2713    FromView {
2714        window_id: usize,
2715        view_id: usize,
2716        callback: Box<dyn FnMut(&mut dyn Any, usize, &mut MutableAppContext, usize, usize)>,
2717    },
2718}
2719
2720struct ViewObservation {
2721    window_id: usize,
2722    view_id: usize,
2723    callback: Box<dyn FnMut(&mut dyn Any, usize, usize, &mut MutableAppContext, usize, usize)>,
2724}
2725
2726#[cfg(test)]
2727mod tests {
2728    use super::*;
2729    use crate::elements::*;
2730    use smol::future::poll_once;
2731
2732    #[crate::test(self)]
2733    fn test_model_handles(cx: &mut MutableAppContext) {
2734        struct Model {
2735            other: Option<ModelHandle<Model>>,
2736            events: Vec<String>,
2737        }
2738
2739        impl Entity for Model {
2740            type Event = usize;
2741        }
2742
2743        impl Model {
2744            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
2745                if let Some(other) = other.as_ref() {
2746                    cx.observe(other, |me, _, _| {
2747                        me.events.push("notified".into());
2748                    });
2749                    cx.subscribe(other, |me, event, _| {
2750                        me.events.push(format!("observed event {}", event));
2751                    });
2752                }
2753
2754                Self {
2755                    other,
2756                    events: Vec::new(),
2757                }
2758            }
2759        }
2760
2761        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
2762        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
2763        assert_eq!(cx.cx.models.len(), 2);
2764
2765        handle_1.update(cx, |model, cx| {
2766            model.events.push("updated".into());
2767            cx.emit(1);
2768            cx.notify();
2769            cx.emit(2);
2770        });
2771        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
2772        assert_eq!(
2773            handle_2.read(cx).events,
2774            vec![
2775                "observed event 1".to_string(),
2776                "notified".to_string(),
2777                "observed event 2".to_string(),
2778            ]
2779        );
2780
2781        handle_2.update(cx, |model, _| {
2782            drop(handle_1);
2783            model.other.take();
2784        });
2785
2786        assert_eq!(cx.cx.models.len(), 1);
2787        assert!(cx.subscriptions.is_empty());
2788        assert!(cx.model_observations.is_empty());
2789    }
2790
2791    #[crate::test(self)]
2792    fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) {
2793        #[derive(Default)]
2794        struct Model {
2795            events: Vec<usize>,
2796        }
2797
2798        impl Entity for Model {
2799            type Event = usize;
2800        }
2801
2802        let handle_1 = cx.add_model(|_| Model::default());
2803        let handle_2 = cx.add_model(|_| Model::default());
2804        let handle_2b = handle_2.clone();
2805
2806        handle_1.update(cx, |_, c| {
2807            c.subscribe(&handle_2, move |model: &mut Model, event, c| {
2808                model.events.push(*event);
2809
2810                c.subscribe(&handle_2b, |model, event, _| {
2811                    model.events.push(*event * 2);
2812                });
2813            });
2814        });
2815
2816        handle_2.update(cx, |_, c| c.emit(7));
2817        assert_eq!(handle_1.read(cx).events, vec![7]);
2818
2819        handle_2.update(cx, |_, c| c.emit(5));
2820        assert_eq!(handle_1.read(cx).events, vec![7, 10, 5]);
2821    }
2822
2823    #[crate::test(self)]
2824    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
2825        #[derive(Default)]
2826        struct Model {
2827            count: usize,
2828            events: Vec<usize>,
2829        }
2830
2831        impl Entity for Model {
2832            type Event = ();
2833        }
2834
2835        let handle_1 = cx.add_model(|_| Model::default());
2836        let handle_2 = cx.add_model(|_| Model::default());
2837        let handle_2b = handle_2.clone();
2838
2839        handle_1.update(cx, |_, c| {
2840            c.observe(&handle_2, move |model, observed, c| {
2841                model.events.push(observed.read(c).count);
2842                c.observe(&handle_2b, |model, observed, c| {
2843                    model.events.push(observed.read(c).count * 2);
2844                });
2845            });
2846        });
2847
2848        handle_2.update(cx, |model, c| {
2849            model.count = 7;
2850            c.notify()
2851        });
2852        assert_eq!(handle_1.read(cx).events, vec![7]);
2853
2854        handle_2.update(cx, |model, c| {
2855            model.count = 5;
2856            c.notify()
2857        });
2858        assert_eq!(handle_1.read(cx).events, vec![7, 10, 5])
2859    }
2860
2861    #[crate::test(self)]
2862    fn test_view_handles(cx: &mut MutableAppContext) {
2863        struct View {
2864            other: Option<ViewHandle<View>>,
2865            events: Vec<String>,
2866        }
2867
2868        impl Entity for View {
2869            type Event = usize;
2870        }
2871
2872        impl super::View for View {
2873            fn render<'a>(&self, _: &AppContext) -> ElementBox {
2874                Empty::new().boxed()
2875            }
2876
2877            fn ui_name() -> &'static str {
2878                "View"
2879            }
2880        }
2881
2882        impl View {
2883            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
2884                if let Some(other) = other.as_ref() {
2885                    cx.subscribe_to_view(other, |me, _, event, _| {
2886                        me.events.push(format!("observed event {}", event));
2887                    });
2888                }
2889                Self {
2890                    other,
2891                    events: Vec::new(),
2892                }
2893            }
2894        }
2895
2896        let (window_id, _) = cx.add_window(|cx| View::new(None, cx));
2897        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
2898        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
2899        assert_eq!(cx.cx.views.len(), 3);
2900
2901        handle_1.update(cx, |view, cx| {
2902            view.events.push("updated".into());
2903            cx.emit(1);
2904            cx.emit(2);
2905        });
2906        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
2907        assert_eq!(
2908            handle_2.read(cx).events,
2909            vec![
2910                "observed event 1".to_string(),
2911                "observed event 2".to_string(),
2912            ]
2913        );
2914
2915        handle_2.update(cx, |view, _| {
2916            drop(handle_1);
2917            view.other.take();
2918        });
2919
2920        assert_eq!(cx.cx.views.len(), 2);
2921        assert!(cx.subscriptions.is_empty());
2922        assert!(cx.model_observations.is_empty());
2923    }
2924
2925    #[crate::test(self)]
2926    fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) {
2927        #[derive(Default)]
2928        struct View {
2929            events: Vec<usize>,
2930        }
2931
2932        impl Entity for View {
2933            type Event = usize;
2934        }
2935
2936        impl super::View for View {
2937            fn render<'a>(&self, _: &AppContext) -> ElementBox {
2938                Empty::new().boxed()
2939            }
2940
2941            fn ui_name() -> &'static str {
2942                "View"
2943            }
2944        }
2945
2946        struct Model;
2947
2948        impl Entity for Model {
2949            type Event = usize;
2950        }
2951
2952        let (window_id, handle_1) = cx.add_window(|_| View::default());
2953        let handle_2 = cx.add_view(window_id, |_| View::default());
2954        let handle_2b = handle_2.clone();
2955        let handle_3 = cx.add_model(|_| Model);
2956
2957        handle_1.update(cx, |_, c| {
2958            c.subscribe_to_view(&handle_2, move |me, _, event, c| {
2959                me.events.push(*event);
2960
2961                c.subscribe_to_view(&handle_2b, |me, _, event, _| {
2962                    me.events.push(*event * 2);
2963                });
2964            });
2965
2966            c.subscribe_to_model(&handle_3, |me, _, event, _| {
2967                me.events.push(*event);
2968            })
2969        });
2970
2971        handle_2.update(cx, |_, c| c.emit(7));
2972        assert_eq!(handle_1.read(cx).events, vec![7]);
2973
2974        handle_2.update(cx, |_, c| c.emit(5));
2975        assert_eq!(handle_1.read(cx).events, vec![7, 10, 5]);
2976
2977        handle_3.update(cx, |_, c| c.emit(9));
2978        assert_eq!(handle_1.read(cx).events, vec![7, 10, 5, 9]);
2979    }
2980
2981    #[crate::test(self)]
2982    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
2983        struct View;
2984
2985        impl Entity for View {
2986            type Event = ();
2987        }
2988
2989        impl super::View for View {
2990            fn render<'a>(&self, _: &AppContext) -> ElementBox {
2991                Empty::new().boxed()
2992            }
2993
2994            fn ui_name() -> &'static str {
2995                "View"
2996            }
2997        }
2998
2999        struct Model;
3000
3001        impl Entity for Model {
3002            type Event = ();
3003        }
3004
3005        let (window_id, _) = cx.add_window(|_| View);
3006        let observing_view = cx.add_view(window_id, |_| View);
3007        let emitting_view = cx.add_view(window_id, |_| View);
3008        let observing_model = cx.add_model(|_| Model);
3009        let observed_model = cx.add_model(|_| Model);
3010
3011        observing_view.update(cx, |_, cx| {
3012            cx.subscribe_to_view(&emitting_view, |_, _, _, _| {});
3013            cx.subscribe_to_model(&observed_model, |_, _, _, _| {});
3014        });
3015        observing_model.update(cx, |_, cx| {
3016            cx.subscribe(&observed_model, |_, _, _| {});
3017        });
3018
3019        cx.update(|| {
3020            drop(observing_view);
3021            drop(observing_model);
3022        });
3023
3024        emitting_view.update(cx, |_, cx| cx.emit(()));
3025        observed_model.update(cx, |_, cx| cx.emit(()));
3026    }
3027
3028    #[crate::test(self)]
3029    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
3030        #[derive(Default)]
3031        struct View {
3032            events: Vec<usize>,
3033        }
3034
3035        impl Entity for View {
3036            type Event = usize;
3037        }
3038
3039        impl super::View for View {
3040            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3041                Empty::new().boxed()
3042            }
3043
3044            fn ui_name() -> &'static str {
3045                "View"
3046            }
3047        }
3048
3049        #[derive(Default)]
3050        struct Model {
3051            count: usize,
3052        }
3053
3054        impl Entity for Model {
3055            type Event = ();
3056        }
3057
3058        let (_, view) = cx.add_window(|_| View::default());
3059        let model = cx.add_model(|_| Model::default());
3060
3061        view.update(cx, |_, c| {
3062            c.observe_model(&model, |me, observed, c| {
3063                me.events.push(observed.read(c).count)
3064            });
3065        });
3066
3067        model.update(cx, |model, c| {
3068            model.count = 11;
3069            c.notify();
3070        });
3071        assert_eq!(view.read(cx).events, vec![11]);
3072    }
3073
3074    #[crate::test(self)]
3075    fn test_dropping_observers(cx: &mut MutableAppContext) {
3076        struct View;
3077
3078        impl Entity for View {
3079            type Event = ();
3080        }
3081
3082        impl super::View for View {
3083            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3084                Empty::new().boxed()
3085            }
3086
3087            fn ui_name() -> &'static str {
3088                "View"
3089            }
3090        }
3091
3092        struct Model;
3093
3094        impl Entity for Model {
3095            type Event = ();
3096        }
3097
3098        let (window_id, _) = cx.add_window(|_| View);
3099        let observing_view = cx.add_view(window_id, |_| View);
3100        let observing_model = cx.add_model(|_| Model);
3101        let observed_model = cx.add_model(|_| Model);
3102
3103        observing_view.update(cx, |_, cx| {
3104            cx.observe_model(&observed_model, |_, _, _| {});
3105        });
3106        observing_model.update(cx, |_, cx| {
3107            cx.observe(&observed_model, |_, _, _| {});
3108        });
3109
3110        cx.update(|| {
3111            drop(observing_view);
3112            drop(observing_model);
3113        });
3114
3115        observed_model.update(cx, |_, cx| cx.notify());
3116    }
3117
3118    #[crate::test(self)]
3119    fn test_focus(cx: &mut MutableAppContext) {
3120        struct View {
3121            name: String,
3122            events: Arc<Mutex<Vec<String>>>,
3123        }
3124
3125        impl Entity for View {
3126            type Event = ();
3127        }
3128
3129        impl super::View for View {
3130            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3131                Empty::new().boxed()
3132            }
3133
3134            fn ui_name() -> &'static str {
3135                "View"
3136            }
3137
3138            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
3139                self.events.lock().push(format!("{} focused", &self.name));
3140            }
3141
3142            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
3143                self.events.lock().push(format!("{} blurred", &self.name));
3144            }
3145        }
3146
3147        let events: Arc<Mutex<Vec<String>>> = Default::default();
3148        let (window_id, view_1) = cx.add_window(|_| View {
3149            events: events.clone(),
3150            name: "view 1".to_string(),
3151        });
3152        let view_2 = cx.add_view(window_id, |_| View {
3153            events: events.clone(),
3154            name: "view 2".to_string(),
3155        });
3156
3157        view_1.update(cx, |_, cx| cx.focus(&view_2));
3158        view_1.update(cx, |_, cx| cx.focus(&view_1));
3159        view_1.update(cx, |_, cx| cx.focus(&view_2));
3160        view_1.update(cx, |_, _| drop(view_2));
3161
3162        assert_eq!(
3163            *events.lock(),
3164            [
3165                "view 1 focused".to_string(),
3166                "view 1 blurred".to_string(),
3167                "view 2 focused".to_string(),
3168                "view 2 blurred".to_string(),
3169                "view 1 focused".to_string(),
3170                "view 1 blurred".to_string(),
3171                "view 2 focused".to_string(),
3172                "view 1 focused".to_string(),
3173            ],
3174        );
3175    }
3176
3177    #[crate::test(self)]
3178    fn test_dispatch_action(cx: &mut MutableAppContext) {
3179        struct ViewA {
3180            id: usize,
3181        }
3182
3183        impl Entity for ViewA {
3184            type Event = ();
3185        }
3186
3187        impl View for ViewA {
3188            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3189                Empty::new().boxed()
3190            }
3191
3192            fn ui_name() -> &'static str {
3193                "View"
3194            }
3195        }
3196
3197        struct ViewB {
3198            id: usize,
3199        }
3200
3201        impl Entity for ViewB {
3202            type Event = ();
3203        }
3204
3205        impl View for ViewB {
3206            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3207                Empty::new().boxed()
3208            }
3209
3210            fn ui_name() -> &'static str {
3211                "View"
3212            }
3213        }
3214
3215        struct ActionArg {
3216            foo: String,
3217        }
3218
3219        let actions = Rc::new(RefCell::new(Vec::new()));
3220
3221        let actions_clone = actions.clone();
3222        cx.add_global_action("action", move |_: &ActionArg, _: &mut MutableAppContext| {
3223            actions_clone.borrow_mut().push("global a".to_string());
3224        });
3225
3226        let actions_clone = actions.clone();
3227        cx.add_global_action("action", move |_: &ActionArg, _: &mut MutableAppContext| {
3228            actions_clone.borrow_mut().push("global b".to_string());
3229        });
3230
3231        let actions_clone = actions.clone();
3232        cx.add_action("action", move |view: &mut ViewA, arg: &ActionArg, cx| {
3233            assert_eq!(arg.foo, "bar");
3234            cx.propagate_action();
3235            actions_clone.borrow_mut().push(format!("{} a", view.id));
3236        });
3237
3238        let actions_clone = actions.clone();
3239        cx.add_action("action", move |view: &mut ViewA, _: &ActionArg, cx| {
3240            if view.id != 1 {
3241                cx.propagate_action();
3242            }
3243            actions_clone.borrow_mut().push(format!("{} b", view.id));
3244        });
3245
3246        let actions_clone = actions.clone();
3247        cx.add_action("action", move |view: &mut ViewB, _: &ActionArg, cx| {
3248            cx.propagate_action();
3249            actions_clone.borrow_mut().push(format!("{} c", view.id));
3250        });
3251
3252        let actions_clone = actions.clone();
3253        cx.add_action("action", move |view: &mut ViewB, _: &ActionArg, cx| {
3254            cx.propagate_action();
3255            actions_clone.borrow_mut().push(format!("{} d", view.id));
3256        });
3257
3258        let (window_id, view_1) = cx.add_window(|_| ViewA { id: 1 });
3259        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
3260        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
3261        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
3262
3263        cx.dispatch_action(
3264            window_id,
3265            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
3266            "action",
3267            ActionArg { foo: "bar".into() },
3268        );
3269
3270        assert_eq!(
3271            *actions.borrow(),
3272            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "1 b"]
3273        );
3274
3275        // Remove view_1, which doesn't propagate the action
3276        actions.borrow_mut().clear();
3277        cx.dispatch_action(
3278            window_id,
3279            vec![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", "global b", "global a"]
3287        );
3288    }
3289
3290    #[crate::test(self)]
3291    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
3292        use std::cell::Cell;
3293
3294        #[derive(Clone)]
3295        struct ActionArg {
3296            key: String,
3297        }
3298
3299        struct View {
3300            id: usize,
3301            keymap_context: keymap::Context,
3302        }
3303
3304        impl Entity for View {
3305            type Event = ();
3306        }
3307
3308        impl super::View for View {
3309            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3310                Empty::new().boxed()
3311            }
3312
3313            fn ui_name() -> &'static str {
3314                "View"
3315            }
3316
3317            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
3318                self.keymap_context.clone()
3319            }
3320        }
3321
3322        impl View {
3323            fn new(id: usize) -> Self {
3324                View {
3325                    id,
3326                    keymap_context: keymap::Context::default(),
3327                }
3328            }
3329        }
3330
3331        let mut view_1 = View::new(1);
3332        let mut view_2 = View::new(2);
3333        let mut view_3 = View::new(3);
3334        view_1.keymap_context.set.insert("a".into());
3335        view_2.keymap_context.set.insert("b".into());
3336        view_3.keymap_context.set.insert("c".into());
3337
3338        let (window_id, view_1) = cx.add_window(|_| view_1);
3339        let view_2 = cx.add_view(window_id, |_| view_2);
3340        let view_3 = cx.add_view(window_id, |_| view_3);
3341
3342        // This keymap's only binding dispatches an action on view 2 because that view will have
3343        // "a" and "b" in its context, but not "c".
3344        let binding = keymap::Binding::new("a", "action", Some("a && b && !c"))
3345            .with_arg(ActionArg { key: "a".into() });
3346        cx.add_bindings(vec![binding]);
3347
3348        let handled_action = Rc::new(Cell::new(false));
3349        let handled_action_clone = handled_action.clone();
3350        cx.add_action("action", move |view: &mut View, arg: &ActionArg, _| {
3351            handled_action_clone.set(true);
3352            assert_eq!(view.id, 2);
3353            assert_eq!(arg.key, "a");
3354        });
3355
3356        cx.dispatch_keystroke(
3357            window_id,
3358            vec![view_1.id(), view_2.id(), view_3.id()],
3359            &Keystroke::parse("a").unwrap(),
3360        )
3361        .unwrap();
3362
3363        assert!(handled_action.get());
3364    }
3365
3366    #[crate::test(self)]
3367    async fn test_model_condition(mut cx: TestAppContext) {
3368        struct Counter(usize);
3369
3370        impl super::Entity for Counter {
3371            type Event = ();
3372        }
3373
3374        impl Counter {
3375            fn inc(&mut self, cx: &mut ModelContext<Self>) {
3376                self.0 += 1;
3377                cx.notify();
3378            }
3379        }
3380
3381        let model = cx.add_model(|_| Counter(0));
3382
3383        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
3384        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
3385        smol::pin!(condition1, condition2);
3386
3387        model.update(&mut cx, |model, cx| model.inc(cx));
3388        assert_eq!(poll_once(&mut condition1).await, None);
3389        assert_eq!(poll_once(&mut condition2).await, None);
3390
3391        model.update(&mut cx, |model, cx| model.inc(cx));
3392        assert_eq!(poll_once(&mut condition1).await, Some(()));
3393        assert_eq!(poll_once(&mut condition2).await, None);
3394
3395        model.update(&mut cx, |model, cx| model.inc(cx));
3396        assert_eq!(poll_once(&mut condition2).await, Some(()));
3397
3398        model.update(&mut cx, |_, cx| cx.notify());
3399    }
3400
3401    #[crate::test(self)]
3402    #[should_panic]
3403    async fn test_model_condition_timeout(mut cx: TestAppContext) {
3404        struct Model;
3405
3406        impl super::Entity for Model {
3407            type Event = ();
3408        }
3409
3410        let model = cx.add_model(|_| Model);
3411        model.condition(&cx, |_, _| false).await;
3412    }
3413
3414    #[crate::test(self)]
3415    #[should_panic(expected = "model dropped with pending condition")]
3416    async fn test_model_condition_panic_on_drop(mut cx: TestAppContext) {
3417        struct Model;
3418
3419        impl super::Entity for Model {
3420            type Event = ();
3421        }
3422
3423        let model = cx.add_model(|_| Model);
3424        let condition = model.condition(&cx, |_, _| false);
3425        cx.update(|_| drop(model));
3426        condition.await;
3427    }
3428
3429    #[crate::test(self)]
3430    async fn test_view_condition(mut cx: TestAppContext) {
3431        struct Counter(usize);
3432
3433        impl super::Entity for Counter {
3434            type Event = ();
3435        }
3436
3437        impl super::View for Counter {
3438            fn ui_name() -> &'static str {
3439                "test view"
3440            }
3441
3442            fn render(&self, _: &AppContext) -> ElementBox {
3443                Empty::new().boxed()
3444            }
3445        }
3446
3447        impl Counter {
3448            fn inc(&mut self, cx: &mut ViewContext<Self>) {
3449                self.0 += 1;
3450                cx.notify();
3451            }
3452        }
3453
3454        let (_, view) = cx.add_window(|_| Counter(0));
3455
3456        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
3457        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
3458        smol::pin!(condition1, condition2);
3459
3460        view.update(&mut cx, |view, cx| view.inc(cx));
3461        assert_eq!(poll_once(&mut condition1).await, None);
3462        assert_eq!(poll_once(&mut condition2).await, None);
3463
3464        view.update(&mut cx, |view, cx| view.inc(cx));
3465        assert_eq!(poll_once(&mut condition1).await, Some(()));
3466        assert_eq!(poll_once(&mut condition2).await, None);
3467
3468        view.update(&mut cx, |view, cx| view.inc(cx));
3469        assert_eq!(poll_once(&mut condition2).await, Some(()));
3470        view.update(&mut cx, |_, cx| cx.notify());
3471    }
3472
3473    #[crate::test(self)]
3474    #[should_panic]
3475    async fn test_view_condition_timeout(mut cx: TestAppContext) {
3476        struct View;
3477
3478        impl super::Entity for View {
3479            type Event = ();
3480        }
3481
3482        impl super::View for View {
3483            fn ui_name() -> &'static str {
3484                "test view"
3485            }
3486
3487            fn render(&self, _: &AppContext) -> ElementBox {
3488                Empty::new().boxed()
3489            }
3490        }
3491
3492        let (_, view) = cx.add_window(|_| View);
3493        view.condition(&cx, |_, _| false).await;
3494    }
3495
3496    #[crate::test(self)]
3497    #[should_panic(expected = "view dropped with pending condition")]
3498    async fn test_view_condition_panic_on_drop(mut cx: TestAppContext) {
3499        struct View;
3500
3501        impl super::Entity for View {
3502            type Event = ();
3503        }
3504
3505        impl super::View for View {
3506            fn ui_name() -> &'static str {
3507                "test view"
3508            }
3509
3510            fn render(&self, _: &AppContext) -> ElementBox {
3511                Empty::new().boxed()
3512            }
3513        }
3514
3515        let window_id = cx.add_window(|_| View).0;
3516        let view = cx.add_view(window_id, |_| View);
3517
3518        let condition = view.condition(&cx, |_, _| false);
3519        cx.update(|_| drop(view));
3520        condition.await;
3521    }
3522}