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