app.rs

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