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