app.rs

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