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