app.rs

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