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