app.rs

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