app.rs

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