app.rs

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