app.rs

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