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, ClipboardItem, 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 write_to_clipboard(&self, item: ClipboardItem) {
1217        self.platform.write_to_clipboard(item);
1218    }
1219
1220    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1221        self.platform.read_from_clipboard()
1222    }
1223}
1224
1225impl ReadModel for MutableAppContext {
1226    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1227        if let Some(model) = self.ctx.models.get(&handle.model_id) {
1228            model
1229                .as_any()
1230                .downcast_ref()
1231                .expect("Downcast is type safe")
1232        } else {
1233            panic!("Circular model reference");
1234        }
1235    }
1236}
1237
1238impl UpdateModel for MutableAppContext {
1239    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
1240    where
1241        T: Entity,
1242        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
1243    {
1244        if let Some(mut model) = self.ctx.models.remove(&handle.model_id) {
1245            self.pending_flushes += 1;
1246            let mut ctx = ModelContext::new(self, handle.model_id);
1247            let result = update(
1248                model
1249                    .as_any_mut()
1250                    .downcast_mut()
1251                    .expect("Downcast is type safe"),
1252                &mut ctx,
1253            );
1254            self.ctx.models.insert(handle.model_id, model);
1255            self.flush_effects();
1256            result
1257        } else {
1258            panic!("Circular model update");
1259        }
1260    }
1261}
1262
1263impl ReadView for MutableAppContext {
1264    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1265        if let Some(window) = self.ctx.windows.get(&handle.window_id) {
1266            if let Some(view) = window.views.get(&handle.view_id) {
1267                view.as_any().downcast_ref().expect("Downcast is type safe")
1268            } else {
1269                panic!("Circular view reference");
1270            }
1271        } else {
1272            panic!("Window does not exist");
1273        }
1274    }
1275}
1276
1277impl UpdateView for MutableAppContext {
1278    fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
1279    where
1280        T: View,
1281        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
1282    {
1283        self.pending_flushes += 1;
1284        let mut view = if let Some(window) = self.ctx.windows.get_mut(&handle.window_id) {
1285            if let Some(view) = window.views.remove(&handle.view_id) {
1286                view
1287            } else {
1288                panic!("Circular view update");
1289            }
1290        } else {
1291            panic!("Window does not exist");
1292        };
1293
1294        let mut ctx = ViewContext::new(self, handle.window_id, handle.view_id);
1295        let result = update(
1296            view.as_any_mut()
1297                .downcast_mut()
1298                .expect("Downcast is type safe"),
1299            &mut ctx,
1300        );
1301        self.ctx
1302            .windows
1303            .get_mut(&handle.window_id)
1304            .unwrap()
1305            .views
1306            .insert(handle.view_id, view);
1307        self.flush_effects();
1308        result
1309    }
1310}
1311
1312impl AsRef<AppContext> for MutableAppContext {
1313    fn as_ref(&self) -> &AppContext {
1314        &self.ctx
1315    }
1316}
1317
1318pub struct AppContext {
1319    models: HashMap<usize, Box<dyn AnyModel>>,
1320    windows: HashMap<usize, Window>,
1321    background: Arc<executor::Background>,
1322    ref_counts: Arc<Mutex<RefCounts>>,
1323}
1324
1325impl AppContext {
1326    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
1327        self.windows
1328            .get(&window_id)
1329            .and_then(|window| window.root_view.as_ref().map(|v| v.id()))
1330    }
1331
1332    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
1333        self.windows
1334            .get(&window_id)
1335            .and_then(|window| window.focused_view)
1336    }
1337
1338    pub fn render_view(&self, window_id: usize, view_id: usize) -> Result<ElementBox> {
1339        self.windows
1340            .get(&window_id)
1341            .and_then(|w| w.views.get(&view_id))
1342            .map(|v| v.render(self))
1343            .ok_or(anyhow!("view not found"))
1344    }
1345
1346    pub fn render_views(&self, window_id: usize) -> Result<HashMap<usize, ElementBox>> {
1347        self.windows
1348            .get(&window_id)
1349            .map(|w| {
1350                w.views
1351                    .iter()
1352                    .map(|(id, view)| (*id, view.render(self)))
1353                    .collect::<HashMap<_, ElementBox>>()
1354            })
1355            .ok_or(anyhow!("window not found"))
1356    }
1357
1358    pub fn background_executor(&self) -> &Arc<executor::Background> {
1359        &self.background
1360    }
1361}
1362
1363impl ReadModel for AppContext {
1364    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1365        if let Some(model) = self.models.get(&handle.model_id) {
1366            model
1367                .as_any()
1368                .downcast_ref()
1369                .expect("downcast should be type safe")
1370        } else {
1371            panic!("circular model reference");
1372        }
1373    }
1374}
1375
1376impl ReadView for AppContext {
1377    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1378        if let Some(window) = self.windows.get(&handle.window_id) {
1379            if let Some(view) = window.views.get(&handle.view_id) {
1380                view.as_any()
1381                    .downcast_ref()
1382                    .expect("downcast should be type safe")
1383            } else {
1384                panic!("circular view reference");
1385            }
1386        } else {
1387            panic!("window does not exist");
1388        }
1389    }
1390}
1391
1392#[derive(Default)]
1393struct Window {
1394    views: HashMap<usize, Box<dyn AnyView>>,
1395    root_view: Option<AnyViewHandle>,
1396    focused_view: Option<usize>,
1397}
1398
1399#[derive(Default, Clone)]
1400pub struct WindowInvalidation {
1401    pub updated: HashSet<usize>,
1402    pub removed: Vec<usize>,
1403}
1404
1405pub enum Effect {
1406    Event {
1407        entity_id: usize,
1408        payload: Box<dyn Any>,
1409    },
1410    ModelNotification {
1411        model_id: usize,
1412    },
1413    ViewNotification {
1414        window_id: usize,
1415        view_id: usize,
1416    },
1417    Focus {
1418        window_id: usize,
1419        view_id: usize,
1420    },
1421}
1422
1423pub trait AnyModel: Send + Sync {
1424    fn as_any(&self) -> &dyn Any;
1425    fn as_any_mut(&mut self) -> &mut dyn Any;
1426}
1427
1428impl<T> AnyModel for T
1429where
1430    T: Entity,
1431{
1432    fn as_any(&self) -> &dyn Any {
1433        self
1434    }
1435
1436    fn as_any_mut(&mut self) -> &mut dyn Any {
1437        self
1438    }
1439}
1440
1441pub trait AnyView: Send + Sync {
1442    fn as_any(&self) -> &dyn Any;
1443    fn as_any_mut(&mut self) -> &mut dyn Any;
1444    fn ui_name(&self) -> &'static str;
1445    fn render<'a>(&self, app: &AppContext) -> ElementBox;
1446    fn on_focus(&mut self, app: &mut MutableAppContext, window_id: usize, view_id: usize);
1447    fn on_blur(&mut self, app: &mut MutableAppContext, window_id: usize, view_id: usize);
1448    fn keymap_context(&self, app: &AppContext) -> keymap::Context;
1449}
1450
1451impl<T> AnyView for T
1452where
1453    T: View,
1454{
1455    fn as_any(&self) -> &dyn Any {
1456        self
1457    }
1458
1459    fn as_any_mut(&mut self) -> &mut dyn Any {
1460        self
1461    }
1462
1463    fn ui_name(&self) -> &'static str {
1464        T::ui_name()
1465    }
1466
1467    fn render<'a>(&self, app: &AppContext) -> ElementBox {
1468        View::render(self, app)
1469    }
1470
1471    fn on_focus(&mut self, app: &mut MutableAppContext, window_id: usize, view_id: usize) {
1472        let mut ctx = ViewContext::new(app, window_id, view_id);
1473        View::on_focus(self, &mut ctx);
1474    }
1475
1476    fn on_blur(&mut self, app: &mut MutableAppContext, window_id: usize, view_id: usize) {
1477        let mut ctx = ViewContext::new(app, window_id, view_id);
1478        View::on_blur(self, &mut ctx);
1479    }
1480
1481    fn keymap_context(&self, app: &AppContext) -> keymap::Context {
1482        View::keymap_context(self, app)
1483    }
1484}
1485
1486pub struct ModelContext<'a, T: ?Sized> {
1487    app: &'a mut MutableAppContext,
1488    model_id: usize,
1489    model_type: PhantomData<T>,
1490    halt_stream: bool,
1491}
1492
1493impl<'a, T: Entity> ModelContext<'a, T> {
1494    fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
1495        Self {
1496            app,
1497            model_id,
1498            model_type: PhantomData,
1499            halt_stream: false,
1500        }
1501    }
1502
1503    pub fn background_executor(&self) -> &Arc<executor::Background> {
1504        &self.app.ctx.background
1505    }
1506
1507    pub fn halt_stream(&mut self) {
1508        self.halt_stream = true;
1509    }
1510
1511    pub fn model_id(&self) -> usize {
1512        self.model_id
1513    }
1514
1515    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
1516    where
1517        S: Entity,
1518        F: FnOnce(&mut ModelContext<S>) -> S,
1519    {
1520        self.app.add_model(build_model)
1521    }
1522
1523    pub fn subscribe<S: Entity, F>(&mut self, handle: &ModelHandle<S>, mut callback: F)
1524    where
1525        S::Event: 'static,
1526        F: 'static + FnMut(&mut T, &S::Event, &mut ModelContext<T>),
1527    {
1528        self.app
1529            .subscriptions
1530            .entry(handle.model_id)
1531            .or_default()
1532            .push(Subscription::FromModel {
1533                model_id: self.model_id,
1534                callback: Box::new(move |model, payload, app, model_id| {
1535                    let model = model.downcast_mut().expect("downcast is type safe");
1536                    let payload = payload.downcast_ref().expect("downcast is type safe");
1537                    let mut ctx = ModelContext::new(app, model_id);
1538                    callback(model, payload, &mut ctx);
1539                }),
1540            });
1541    }
1542
1543    pub fn emit(&mut self, payload: T::Event) {
1544        self.app.pending_effects.push_back(Effect::Event {
1545            entity_id: self.model_id,
1546            payload: Box::new(payload),
1547        });
1548    }
1549
1550    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F)
1551    where
1552        S: Entity,
1553        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
1554    {
1555        self.app
1556            .observations
1557            .entry(handle.model_id)
1558            .or_default()
1559            .push(Observation::FromModel {
1560                model_id: self.model_id,
1561                callback: Box::new(move |model, observed_id, app, model_id| {
1562                    let model = model.downcast_mut().expect("downcast is type safe");
1563                    let observed = ModelHandle::new(observed_id, &app.ctx.ref_counts);
1564                    let mut ctx = ModelContext::new(app, model_id);
1565                    callback(model, observed, &mut ctx);
1566                }),
1567            });
1568    }
1569
1570    pub fn notify(&mut self) {
1571        self.app
1572            .pending_effects
1573            .push_back(Effect::ModelNotification {
1574                model_id: self.model_id,
1575            });
1576    }
1577
1578    fn handle(&self) -> ModelHandle<T> {
1579        ModelHandle::new(self.model_id, &self.app.ctx.ref_counts)
1580    }
1581
1582    pub fn spawn<S, F, U>(&mut self, future: S, callback: F) -> EntityTask<U>
1583    where
1584        S: 'static + Future,
1585        F: 'static + FnOnce(&mut T, S::Output, &mut ModelContext<T>) -> U,
1586        U: 'static,
1587    {
1588        let handle = self.handle();
1589        let task = self.app.spawn::<S, U>(future);
1590
1591        self.app.future_handlers.borrow_mut().insert(
1592            task.id,
1593            Box::new(move |output, ctx| {
1594                let output = *output.downcast().unwrap();
1595                handle.update(ctx, |model, ctx| Box::new(callback(model, output, ctx)))
1596            }),
1597        );
1598
1599        task
1600    }
1601
1602    pub fn spawn_stream<S, F, G, U>(
1603        &mut self,
1604        stream: S,
1605        mut item_callback: F,
1606        done_callback: G,
1607    ) -> EntityTask<U>
1608    where
1609        S: 'static + Stream + Unpin,
1610        F: 'static + FnMut(&mut T, S::Item, &mut ModelContext<T>),
1611        G: 'static + FnOnce(&mut T, &mut ModelContext<T>) -> U,
1612        U: 'static + Any,
1613    {
1614        let handle = self.handle();
1615        let task = self.app.spawn_stream(stream);
1616
1617        self.app.stream_handlers.borrow_mut().insert(
1618            task.id,
1619            StreamHandler {
1620                item_callback: {
1621                    let handle = handle.clone();
1622                    Box::new(move |output, app| {
1623                        let output = *output.downcast().unwrap();
1624                        handle.update(app, |model, ctx| {
1625                            item_callback(model, output, ctx);
1626                            ctx.halt_stream
1627                        })
1628                    })
1629                },
1630                done_callback: Box::new(move |app| {
1631                    handle.update(app, |model, ctx| Box::new(done_callback(model, ctx)))
1632                }),
1633            },
1634        );
1635
1636        task
1637    }
1638}
1639
1640impl<M> AsRef<AppContext> for ModelContext<'_, M> {
1641    fn as_ref(&self) -> &AppContext {
1642        &self.app.ctx
1643    }
1644}
1645
1646impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
1647    fn as_mut(&mut self) -> &mut MutableAppContext {
1648        self.app
1649    }
1650}
1651
1652impl<M> ReadModel for ModelContext<'_, M> {
1653    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1654        self.app.read_model(handle)
1655    }
1656}
1657
1658impl<M> UpdateModel for ModelContext<'_, M> {
1659    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
1660    where
1661        T: Entity,
1662        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
1663    {
1664        self.app.update_model(handle, update)
1665    }
1666}
1667
1668pub struct ViewContext<'a, T: ?Sized> {
1669    app: &'a mut MutableAppContext,
1670    window_id: usize,
1671    view_id: usize,
1672    view_type: PhantomData<T>,
1673    halt_action_dispatch: bool,
1674    halt_stream: bool,
1675}
1676
1677impl<'a, T: View> ViewContext<'a, T> {
1678    fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
1679        Self {
1680            app,
1681            window_id,
1682            view_id,
1683            view_type: PhantomData,
1684            halt_action_dispatch: true,
1685            halt_stream: false,
1686        }
1687    }
1688
1689    pub fn handle(&self) -> ViewHandle<T> {
1690        ViewHandle::new(self.window_id, self.view_id, &self.app.ctx.ref_counts)
1691    }
1692
1693    pub fn window_id(&self) -> usize {
1694        self.window_id
1695    }
1696
1697    pub fn background_executor(&self) -> &Arc<executor::Background> {
1698        &self.app.ctx.background
1699    }
1700
1701    pub fn debug_elements(&self) -> crate::json::Value {
1702        self.app.debug_elements(self.window_id).unwrap()
1703    }
1704
1705    pub fn focus<S>(&mut self, handle: S)
1706    where
1707        S: Into<AnyViewHandle>,
1708    {
1709        let handle = handle.into();
1710        self.app.pending_effects.push_back(Effect::Focus {
1711            window_id: handle.window_id,
1712            view_id: handle.view_id,
1713        });
1714    }
1715
1716    pub fn focus_self(&mut self) {
1717        self.app.pending_effects.push_back(Effect::Focus {
1718            window_id: self.window_id,
1719            view_id: self.view_id,
1720        });
1721    }
1722
1723    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
1724    where
1725        S: Entity,
1726        F: FnOnce(&mut ModelContext<S>) -> S,
1727    {
1728        self.app.add_model(build_model)
1729    }
1730
1731    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
1732    where
1733        S: View,
1734        F: FnOnce(&mut ViewContext<S>) -> S,
1735    {
1736        self.app.add_view(self.window_id, build_view)
1737    }
1738
1739    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
1740    where
1741        S: View,
1742        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
1743    {
1744        self.app.add_option_view(self.window_id, build_view)
1745    }
1746
1747    pub fn subscribe_to_model<E, F>(&mut self, handle: &ModelHandle<E>, mut callback: F)
1748    where
1749        E: Entity,
1750        E::Event: 'static,
1751        F: 'static + FnMut(&mut T, ModelHandle<E>, &E::Event, &mut ViewContext<T>),
1752    {
1753        let emitter_handle = handle.downgrade();
1754        self.app
1755            .subscriptions
1756            .entry(handle.id())
1757            .or_default()
1758            .push(Subscription::FromView {
1759                window_id: self.window_id,
1760                view_id: self.view_id,
1761                callback: Box::new(move |view, payload, app, window_id, view_id| {
1762                    if let Some(emitter_handle) = emitter_handle.upgrade(app.as_ref()) {
1763                        let model = view.downcast_mut().expect("downcast is type safe");
1764                        let payload = payload.downcast_ref().expect("downcast is type safe");
1765                        let mut ctx = ViewContext::new(app, window_id, view_id);
1766                        callback(model, emitter_handle, payload, &mut ctx);
1767                    }
1768                }),
1769            });
1770    }
1771
1772    pub fn subscribe_to_view<V, F>(&mut self, handle: &ViewHandle<V>, mut callback: F)
1773    where
1774        V: View,
1775        V::Event: 'static,
1776        F: 'static + FnMut(&mut T, ViewHandle<V>, &V::Event, &mut ViewContext<T>),
1777    {
1778        let emitter_handle = handle.downgrade();
1779
1780        self.app
1781            .subscriptions
1782            .entry(handle.id())
1783            .or_default()
1784            .push(Subscription::FromView {
1785                window_id: self.window_id,
1786                view_id: self.view_id,
1787                callback: Box::new(move |view, payload, app, window_id, view_id| {
1788                    if let Some(emitter_handle) = emitter_handle.upgrade(app.as_ref()) {
1789                        let model = view.downcast_mut().expect("downcast is type safe");
1790                        let payload = payload.downcast_ref().expect("downcast is type safe");
1791                        let mut ctx = ViewContext::new(app, window_id, view_id);
1792                        callback(model, emitter_handle, payload, &mut ctx);
1793                    }
1794                }),
1795            });
1796    }
1797
1798    pub fn emit(&mut self, payload: T::Event) {
1799        self.app.pending_effects.push_back(Effect::Event {
1800            entity_id: self.view_id,
1801            payload: Box::new(payload),
1802        });
1803    }
1804
1805    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F)
1806    where
1807        S: Entity,
1808        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ViewContext<T>),
1809    {
1810        self.app
1811            .observations
1812            .entry(handle.id())
1813            .or_default()
1814            .push(Observation::FromView {
1815                window_id: self.window_id,
1816                view_id: self.view_id,
1817                callback: Box::new(move |view, observed_id, app, window_id, view_id| {
1818                    let view = view.downcast_mut().expect("downcast is type safe");
1819                    let observed = ModelHandle::new(observed_id, &app.ctx.ref_counts);
1820                    let mut ctx = ViewContext::new(app, window_id, view_id);
1821                    callback(view, observed, &mut ctx);
1822                }),
1823            });
1824    }
1825
1826    pub fn notify(&mut self) {
1827        self.app
1828            .pending_effects
1829            .push_back(Effect::ViewNotification {
1830                window_id: self.window_id,
1831                view_id: self.view_id,
1832            });
1833    }
1834
1835    pub fn propagate_action(&mut self) {
1836        self.halt_action_dispatch = false;
1837    }
1838
1839    pub fn halt_stream(&mut self) {
1840        self.halt_stream = true;
1841    }
1842
1843    pub fn spawn<S, F, U>(&mut self, future: S, callback: F) -> EntityTask<U>
1844    where
1845        S: 'static + Future,
1846        F: 'static + FnOnce(&mut T, S::Output, &mut ViewContext<T>) -> U,
1847        U: 'static,
1848    {
1849        let handle = self.handle();
1850        let task = self.app.spawn(future);
1851
1852        self.app.future_handlers.borrow_mut().insert(
1853            task.id,
1854            Box::new(move |output, app| {
1855                let output = *output.downcast().unwrap();
1856                handle.update(app, |view, ctx| Box::new(callback(view, output, ctx)))
1857            }),
1858        );
1859
1860        task
1861    }
1862
1863    pub fn spawn_stream<S, F, G, U>(
1864        &mut self,
1865        stream: S,
1866        mut item_callback: F,
1867        done_callback: G,
1868    ) -> EntityTask<U>
1869    where
1870        S: 'static + Stream + Unpin,
1871        F: 'static + FnMut(&mut T, S::Item, &mut ViewContext<T>),
1872        G: 'static + FnOnce(&mut T, &mut ViewContext<T>) -> U,
1873        U: 'static + Any,
1874    {
1875        let handle = self.handle();
1876        let task = self.app.spawn_stream(stream);
1877        self.app.stream_handlers.borrow_mut().insert(
1878            task.id,
1879            StreamHandler {
1880                item_callback: {
1881                    let handle = handle.clone();
1882                    Box::new(move |output, app| {
1883                        let output = *output.downcast().unwrap();
1884                        handle.update(app, |view, ctx| {
1885                            item_callback(view, output, ctx);
1886                            ctx.halt_stream
1887                        })
1888                    })
1889                },
1890                done_callback: Box::new(move |app| {
1891                    handle.update(app, |view, ctx| Box::new(done_callback(view, ctx)))
1892                }),
1893            },
1894        );
1895        task
1896    }
1897}
1898
1899impl<M> AsRef<AppContext> for ViewContext<'_, M> {
1900    fn as_ref(&self) -> &AppContext {
1901        &self.app.ctx
1902    }
1903}
1904
1905impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
1906    fn as_mut(&mut self) -> &mut MutableAppContext {
1907        self.app
1908    }
1909}
1910
1911impl<V> ReadModel for ViewContext<'_, V> {
1912    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1913        self.app.read_model(handle)
1914    }
1915}
1916
1917impl<V: View> UpdateModel for ViewContext<'_, V> {
1918    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
1919    where
1920        T: Entity,
1921        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
1922    {
1923        self.app.update_model(handle, update)
1924    }
1925}
1926
1927impl<V: View> ReadView for ViewContext<'_, V> {
1928    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1929        self.app.read_view(handle)
1930    }
1931}
1932
1933impl<V: View> UpdateView for ViewContext<'_, V> {
1934    fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
1935    where
1936        T: View,
1937        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
1938    {
1939        self.app.update_view(handle, update)
1940    }
1941}
1942
1943pub trait Handle<T> {
1944    fn id(&self) -> usize;
1945    fn location(&self) -> EntityLocation;
1946}
1947
1948#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
1949pub enum EntityLocation {
1950    Model(usize),
1951    View(usize, usize),
1952}
1953
1954pub struct ModelHandle<T> {
1955    model_id: usize,
1956    model_type: PhantomData<T>,
1957    ref_counts: Weak<Mutex<RefCounts>>,
1958}
1959
1960impl<T: Entity> ModelHandle<T> {
1961    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
1962        ref_counts.lock().inc(model_id);
1963        Self {
1964            model_id,
1965            model_type: PhantomData,
1966            ref_counts: Arc::downgrade(ref_counts),
1967        }
1968    }
1969
1970    fn downgrade(&self) -> WeakModelHandle<T> {
1971        WeakModelHandle::new(self.model_id)
1972    }
1973
1974    pub fn id(&self) -> usize {
1975        self.model_id
1976    }
1977
1978    pub fn read<'a, A: ReadModel>(&self, app: &'a A) -> &'a T {
1979        app.read_model(self)
1980    }
1981
1982    pub fn update<A, F, S>(&self, app: &mut A, update: F) -> S
1983    where
1984        A: UpdateModel,
1985        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
1986    {
1987        app.update_model(self, update)
1988    }
1989}
1990
1991impl<T> Clone for ModelHandle<T> {
1992    fn clone(&self) -> Self {
1993        if let Some(ref_counts) = self.ref_counts.upgrade() {
1994            ref_counts.lock().inc(self.model_id);
1995        }
1996
1997        Self {
1998            model_id: self.model_id,
1999            model_type: PhantomData,
2000            ref_counts: self.ref_counts.clone(),
2001        }
2002    }
2003}
2004
2005impl<T> PartialEq for ModelHandle<T> {
2006    fn eq(&self, other: &Self) -> bool {
2007        self.model_id == other.model_id
2008    }
2009}
2010
2011impl<T> Eq for ModelHandle<T> {}
2012
2013impl<T> Hash for ModelHandle<T> {
2014    fn hash<H: Hasher>(&self, state: &mut H) {
2015        self.model_id.hash(state);
2016    }
2017}
2018
2019impl<T> std::borrow::Borrow<usize> for ModelHandle<T> {
2020    fn borrow(&self) -> &usize {
2021        &self.model_id
2022    }
2023}
2024
2025impl<T> Debug for ModelHandle<T> {
2026    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2027        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
2028            .field(&self.model_id)
2029            .finish()
2030    }
2031}
2032
2033unsafe impl<T> Send for ModelHandle<T> {}
2034unsafe impl<T> Sync for ModelHandle<T> {}
2035
2036impl<T> Drop for ModelHandle<T> {
2037    fn drop(&mut self) {
2038        if let Some(ref_counts) = self.ref_counts.upgrade() {
2039            ref_counts.lock().dec_model(self.model_id);
2040        }
2041    }
2042}
2043
2044impl<T> Handle<T> for ModelHandle<T> {
2045    fn id(&self) -> usize {
2046        self.model_id
2047    }
2048
2049    fn location(&self) -> EntityLocation {
2050        EntityLocation::Model(self.model_id)
2051    }
2052}
2053
2054pub struct WeakModelHandle<T> {
2055    model_id: usize,
2056    model_type: PhantomData<T>,
2057}
2058
2059impl<T: Entity> WeakModelHandle<T> {
2060    fn new(model_id: usize) -> Self {
2061        Self {
2062            model_id,
2063            model_type: PhantomData,
2064        }
2065    }
2066
2067    pub fn upgrade(&self, app: &AppContext) -> Option<ModelHandle<T>> {
2068        if app.models.contains_key(&self.model_id) {
2069            Some(ModelHandle::new(self.model_id, &app.ref_counts))
2070        } else {
2071            None
2072        }
2073    }
2074}
2075
2076pub struct ViewHandle<T> {
2077    window_id: usize,
2078    view_id: usize,
2079    view_type: PhantomData<T>,
2080    ref_counts: Weak<Mutex<RefCounts>>,
2081}
2082
2083impl<T: View> ViewHandle<T> {
2084    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2085        ref_counts.lock().inc(view_id);
2086        Self {
2087            window_id,
2088            view_id,
2089            view_type: PhantomData,
2090            ref_counts: Arc::downgrade(ref_counts),
2091        }
2092    }
2093
2094    pub fn downgrade(&self) -> WeakViewHandle<T> {
2095        WeakViewHandle::new(self.window_id, self.view_id)
2096    }
2097
2098    pub fn window_id(&self) -> usize {
2099        self.window_id
2100    }
2101
2102    pub fn id(&self) -> usize {
2103        self.view_id
2104    }
2105
2106    pub fn read<'a, A: ReadView>(&self, app: &'a A) -> &'a T {
2107        app.read_view(self)
2108    }
2109
2110    pub fn update<A, F, S>(&self, app: &mut A, update: F) -> S
2111    where
2112        A: UpdateView,
2113        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2114    {
2115        app.update_view(self, update)
2116    }
2117
2118    pub fn is_focused(&self, app: &AppContext) -> bool {
2119        app.focused_view_id(self.window_id)
2120            .map_or(false, |focused_id| focused_id == self.view_id)
2121    }
2122}
2123
2124impl<T> Clone for ViewHandle<T> {
2125    fn clone(&self) -> Self {
2126        if let Some(ref_counts) = self.ref_counts.upgrade() {
2127            ref_counts.lock().inc(self.view_id);
2128        }
2129
2130        Self {
2131            window_id: self.window_id,
2132            view_id: self.view_id,
2133            view_type: PhantomData,
2134            ref_counts: self.ref_counts.clone(),
2135        }
2136    }
2137}
2138
2139impl<T> PartialEq for ViewHandle<T> {
2140    fn eq(&self, other: &Self) -> bool {
2141        self.window_id == other.window_id && self.view_id == other.view_id
2142    }
2143}
2144
2145impl<T> Eq for ViewHandle<T> {}
2146
2147impl<T> Debug for ViewHandle<T> {
2148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2149        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
2150            .field("window_id", &self.window_id)
2151            .field("view_id", &self.view_id)
2152            .finish()
2153    }
2154}
2155
2156impl<T> Drop for ViewHandle<T> {
2157    fn drop(&mut self) {
2158        if let Some(ref_counts) = self.ref_counts.upgrade() {
2159            ref_counts.lock().dec_view(self.window_id, self.view_id);
2160        }
2161    }
2162}
2163
2164impl<T> Handle<T> for ViewHandle<T> {
2165    fn id(&self) -> usize {
2166        self.view_id
2167    }
2168
2169    fn location(&self) -> EntityLocation {
2170        EntityLocation::View(self.window_id, self.view_id)
2171    }
2172}
2173
2174#[derive(Clone)]
2175pub struct AnyViewHandle {
2176    window_id: usize,
2177    view_id: usize,
2178    view_type: TypeId,
2179    ref_counts: Weak<Mutex<RefCounts>>,
2180}
2181
2182impl AnyViewHandle {
2183    pub fn id(&self) -> usize {
2184        self.view_id
2185    }
2186
2187    pub fn is<T: 'static>(&self) -> bool {
2188        TypeId::of::<T>() == self.view_type
2189    }
2190
2191    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
2192        if self.is::<T>() {
2193            if let Some(ref_counts) = self.ref_counts.upgrade() {
2194                return Some(ViewHandle::new(self.window_id, self.view_id, &ref_counts));
2195            }
2196        }
2197        None
2198    }
2199}
2200
2201impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
2202    fn from(handle: &ViewHandle<T>) -> Self {
2203        if let Some(ref_counts) = handle.ref_counts.upgrade() {
2204            ref_counts.lock().inc(handle.view_id);
2205        }
2206        AnyViewHandle {
2207            window_id: handle.window_id,
2208            view_id: handle.view_id,
2209            view_type: TypeId::of::<T>(),
2210            ref_counts: handle.ref_counts.clone(),
2211        }
2212    }
2213}
2214
2215impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
2216    fn from(handle: ViewHandle<T>) -> Self {
2217        (&handle).into()
2218    }
2219}
2220
2221pub struct WeakViewHandle<T> {
2222    window_id: usize,
2223    view_id: usize,
2224    view_type: PhantomData<T>,
2225}
2226
2227impl<T: View> WeakViewHandle<T> {
2228    fn new(window_id: usize, view_id: usize) -> Self {
2229        Self {
2230            window_id,
2231            view_id,
2232            view_type: PhantomData,
2233        }
2234    }
2235
2236    pub fn upgrade(&self, app: &AppContext) -> Option<ViewHandle<T>> {
2237        if app
2238            .windows
2239            .get(&self.window_id)
2240            .and_then(|w| w.views.get(&self.view_id))
2241            .is_some()
2242        {
2243            Some(ViewHandle::new(
2244                self.window_id,
2245                self.view_id,
2246                &app.ref_counts,
2247            ))
2248        } else {
2249            None
2250        }
2251    }
2252}
2253
2254impl<T> Clone for WeakViewHandle<T> {
2255    fn clone(&self) -> Self {
2256        Self {
2257            window_id: self.window_id,
2258            view_id: self.view_id,
2259            view_type: PhantomData,
2260        }
2261    }
2262}
2263
2264#[derive(Default)]
2265struct RefCounts {
2266    counts: HashMap<usize, usize>,
2267    dropped_models: HashSet<usize>,
2268    dropped_views: HashSet<(usize, usize)>,
2269}
2270
2271impl RefCounts {
2272    fn inc(&mut self, model_id: usize) {
2273        *self.counts.entry(model_id).or_insert(0) += 1;
2274    }
2275
2276    fn dec_model(&mut self, model_id: usize) {
2277        if let Some(count) = self.counts.get_mut(&model_id) {
2278            *count -= 1;
2279            if *count == 0 {
2280                self.counts.remove(&model_id);
2281                self.dropped_models.insert(model_id);
2282            }
2283        } else {
2284            panic!("Expected ref count to be positive")
2285        }
2286    }
2287
2288    fn dec_view(&mut self, window_id: usize, view_id: usize) {
2289        if let Some(count) = self.counts.get_mut(&view_id) {
2290            *count -= 1;
2291            if *count == 0 {
2292                self.counts.remove(&view_id);
2293                self.dropped_views.insert((window_id, view_id));
2294            }
2295        } else {
2296            panic!("Expected ref count to be positive")
2297        }
2298    }
2299
2300    fn take_dropped(&mut self) -> (HashSet<usize>, HashSet<(usize, usize)>) {
2301        let mut dropped_models = HashSet::new();
2302        let mut dropped_views = HashSet::new();
2303        std::mem::swap(&mut self.dropped_models, &mut dropped_models);
2304        std::mem::swap(&mut self.dropped_views, &mut dropped_views);
2305        (dropped_models, dropped_views)
2306    }
2307}
2308
2309enum Subscription {
2310    FromModel {
2311        model_id: usize,
2312        callback: Box<dyn FnMut(&mut dyn Any, &dyn Any, &mut MutableAppContext, usize)>,
2313    },
2314    FromView {
2315        window_id: usize,
2316        view_id: usize,
2317        callback: Box<dyn FnMut(&mut dyn Any, &dyn Any, &mut MutableAppContext, usize, usize)>,
2318    },
2319}
2320
2321enum Observation {
2322    FromModel {
2323        model_id: usize,
2324        callback: Box<dyn FnMut(&mut dyn Any, usize, &mut MutableAppContext, usize)>,
2325    },
2326    FromView {
2327        window_id: usize,
2328        view_id: usize,
2329        callback: Box<dyn FnMut(&mut dyn Any, usize, &mut MutableAppContext, usize, usize)>,
2330    },
2331}
2332
2333type FutureHandler = Box<dyn FnOnce(Box<dyn Any>, &mut MutableAppContext) -> Box<dyn Any>>;
2334
2335struct StreamHandler {
2336    item_callback: Box<dyn FnMut(Box<dyn Any>, &mut MutableAppContext) -> bool>,
2337    done_callback: Box<dyn FnOnce(&mut MutableAppContext) -> Box<dyn Any>>,
2338}
2339
2340#[must_use]
2341pub struct EntityTask<T> {
2342    id: usize,
2343    task: Option<executor::Task<T>>,
2344    handler_map: TaskHandlerMap,
2345    task_done: Arc<Condvar>,
2346}
2347
2348enum TaskHandlerMap {
2349    Detached,
2350    Future(Rc<RefCell<HashMap<usize, FutureHandler>>>),
2351    Stream(Rc<RefCell<HashMap<usize, StreamHandler>>>),
2352}
2353
2354impl<T> EntityTask<T> {
2355    fn new(
2356        id: usize,
2357        task: executor::Task<T>,
2358        handler_map: TaskHandlerMap,
2359        task_done: Arc<Condvar>,
2360    ) -> Self {
2361        Self {
2362            id,
2363            task: Some(task),
2364            handler_map,
2365            task_done,
2366        }
2367    }
2368
2369    pub fn detach(mut self) {
2370        self.handler_map = TaskHandlerMap::Detached;
2371        self.task.take().unwrap().detach();
2372    }
2373
2374    pub async fn cancel(mut self) -> Option<T> {
2375        let task = self.task.take().unwrap();
2376        task.cancel().await
2377    }
2378}
2379
2380impl<T> Future for EntityTask<T> {
2381    type Output = T;
2382
2383    fn poll(
2384        self: std::pin::Pin<&mut Self>,
2385        ctx: &mut std::task::Context<'_>,
2386    ) -> std::task::Poll<Self::Output> {
2387        let task = unsafe { self.map_unchecked_mut(|task| task.task.as_mut().unwrap()) };
2388        task.poll(ctx)
2389    }
2390}
2391
2392impl<T> Drop for EntityTask<T> {
2393    fn drop(self: &mut Self) {
2394        match &self.handler_map {
2395            TaskHandlerMap::Detached => {
2396                return;
2397            }
2398            TaskHandlerMap::Future(map) => {
2399                map.borrow_mut().remove(&self.id);
2400            }
2401            TaskHandlerMap::Stream(map) => {
2402                map.borrow_mut().remove(&self.id);
2403            }
2404        }
2405        self.task_done.notify_all();
2406    }
2407}
2408
2409#[cfg(test)]
2410mod tests {
2411    use super::*;
2412    use crate::elements::*;
2413
2414    #[test]
2415    fn test_model_handles() {
2416        struct Model {
2417            other: Option<ModelHandle<Model>>,
2418            events: Vec<String>,
2419        }
2420
2421        impl Entity for Model {
2422            type Event = usize;
2423        }
2424
2425        impl Model {
2426            fn new(other: Option<ModelHandle<Self>>, ctx: &mut ModelContext<Self>) -> Self {
2427                if let Some(other) = other.as_ref() {
2428                    ctx.observe(other, |me, _, _| {
2429                        me.events.push("notified".into());
2430                    });
2431                    ctx.subscribe(other, |me, event, _| {
2432                        me.events.push(format!("observed event {}", event));
2433                    });
2434                }
2435
2436                Self {
2437                    other,
2438                    events: Vec::new(),
2439                }
2440            }
2441        }
2442
2443        App::test((), |app| {
2444            let handle_1 = app.add_model(|ctx| Model::new(None, ctx));
2445            let handle_2 = app.add_model(|ctx| Model::new(Some(handle_1.clone()), ctx));
2446            assert_eq!(app.ctx.models.len(), 2);
2447
2448            handle_1.update(app, |model, ctx| {
2449                model.events.push("updated".into());
2450                ctx.emit(1);
2451                ctx.notify();
2452                ctx.emit(2);
2453            });
2454            assert_eq!(handle_1.read(app).events, vec!["updated".to_string()]);
2455            assert_eq!(
2456                handle_2.read(app).events,
2457                vec![
2458                    "observed event 1".to_string(),
2459                    "notified".to_string(),
2460                    "observed event 2".to_string(),
2461                ]
2462            );
2463
2464            handle_2.update(app, |model, _| {
2465                drop(handle_1);
2466                model.other.take();
2467            });
2468
2469            assert_eq!(app.ctx.models.len(), 1);
2470            assert!(app.subscriptions.is_empty());
2471            assert!(app.observations.is_empty());
2472        });
2473    }
2474
2475    #[test]
2476    fn test_subscribe_and_emit_from_model() {
2477        #[derive(Default)]
2478        struct Model {
2479            events: Vec<usize>,
2480        }
2481
2482        impl Entity for Model {
2483            type Event = usize;
2484        }
2485
2486        App::test((), |app| {
2487            let handle_1 = app.add_model(|_| Model::default());
2488            let handle_2 = app.add_model(|_| Model::default());
2489            let handle_2b = handle_2.clone();
2490
2491            handle_1.update(app, |_, c| {
2492                c.subscribe(&handle_2, move |model: &mut Model, event, c| {
2493                    model.events.push(*event);
2494
2495                    c.subscribe(&handle_2b, |model, event, _| {
2496                        model.events.push(*event * 2);
2497                    });
2498                });
2499            });
2500
2501            handle_2.update(app, |_, c| c.emit(7));
2502            assert_eq!(handle_1.read(app).events, vec![7]);
2503
2504            handle_2.update(app, |_, c| c.emit(5));
2505            assert_eq!(handle_1.read(app).events, vec![7, 10, 5]);
2506        })
2507    }
2508
2509    #[test]
2510    fn test_observe_and_notify_from_model() {
2511        #[derive(Default)]
2512        struct Model {
2513            count: usize,
2514            events: Vec<usize>,
2515        }
2516
2517        impl Entity for Model {
2518            type Event = ();
2519        }
2520
2521        App::test((), |app| {
2522            let handle_1 = app.add_model(|_| Model::default());
2523            let handle_2 = app.add_model(|_| Model::default());
2524            let handle_2b = handle_2.clone();
2525
2526            handle_1.update(app, |_, c| {
2527                c.observe(&handle_2, move |model, observed, c| {
2528                    model.events.push(observed.read(c).count);
2529                    c.observe(&handle_2b, |model, observed, c| {
2530                        model.events.push(observed.read(c).count * 2);
2531                    });
2532                });
2533            });
2534
2535            handle_2.update(app, |model, c| {
2536                model.count = 7;
2537                c.notify()
2538            });
2539            assert_eq!(handle_1.read(app).events, vec![7]);
2540
2541            handle_2.update(app, |model, c| {
2542                model.count = 5;
2543                c.notify()
2544            });
2545            assert_eq!(handle_1.read(app).events, vec![7, 10, 5])
2546        })
2547    }
2548
2549    #[test]
2550    fn test_spawn_from_model() {
2551        #[derive(Default)]
2552        struct Model {
2553            count: usize,
2554        }
2555
2556        impl Entity for Model {
2557            type Event = ();
2558        }
2559
2560        App::test_async((), |mut app| async move {
2561            let handle = app.add_model(|_| Model::default());
2562            handle
2563                .update(&mut app, |_, c| {
2564                    c.spawn(async { 7 }, |model, output, _| {
2565                        model.count = output;
2566                    })
2567                })
2568                .await;
2569            app.read(|ctx| assert_eq!(handle.read(ctx).count, 7));
2570
2571            handle
2572                .update(&mut app, |_, c| {
2573                    c.spawn(async { 14 }, |model, output, _| {
2574                        model.count = output;
2575                    })
2576                })
2577                .await;
2578            app.read(|ctx| assert_eq!(handle.read(ctx).count, 14));
2579        });
2580    }
2581
2582    #[test]
2583    fn test_spawn_stream_local_from_model() {
2584        #[derive(Default)]
2585        struct Model {
2586            events: Vec<Option<usize>>,
2587        }
2588
2589        impl Entity for Model {
2590            type Event = ();
2591        }
2592
2593        App::test_async((), |mut app| async move {
2594            let handle = app.add_model(|_| Model::default());
2595            handle
2596                .update(&mut app, |_, c| {
2597                    c.spawn_stream(
2598                        smol::stream::iter(vec![1, 2, 3]),
2599                        |model, output, _| {
2600                            model.events.push(Some(output));
2601                        },
2602                        |model, _| {
2603                            model.events.push(None);
2604                        },
2605                    )
2606                })
2607                .await;
2608            app.read(|ctx| assert_eq!(handle.read(ctx).events, [Some(1), Some(2), Some(3), None]));
2609        })
2610    }
2611
2612    #[test]
2613    fn test_view_handles() {
2614        struct View {
2615            other: Option<ViewHandle<View>>,
2616            events: Vec<String>,
2617        }
2618
2619        impl Entity for View {
2620            type Event = usize;
2621        }
2622
2623        impl super::View for View {
2624            fn render<'a>(&self, _: &AppContext) -> ElementBox {
2625                Empty::new().boxed()
2626            }
2627
2628            fn ui_name() -> &'static str {
2629                "View"
2630            }
2631        }
2632
2633        impl View {
2634            fn new(other: Option<ViewHandle<View>>, ctx: &mut ViewContext<Self>) -> Self {
2635                if let Some(other) = other.as_ref() {
2636                    ctx.subscribe_to_view(other, |me, _, event, _| {
2637                        me.events.push(format!("observed event {}", event));
2638                    });
2639                }
2640                Self {
2641                    other,
2642                    events: Vec::new(),
2643                }
2644            }
2645        }
2646
2647        App::test((), |app| {
2648            let (window_id, _) = app.add_window(|ctx| View::new(None, ctx));
2649            let handle_1 = app.add_view(window_id, |ctx| View::new(None, ctx));
2650            let handle_2 = app.add_view(window_id, |ctx| View::new(Some(handle_1.clone()), ctx));
2651            assert_eq!(app.ctx.windows[&window_id].views.len(), 3);
2652
2653            handle_1.update(app, |view, ctx| {
2654                view.events.push("updated".into());
2655                ctx.emit(1);
2656                ctx.emit(2);
2657            });
2658            assert_eq!(handle_1.read(app).events, vec!["updated".to_string()]);
2659            assert_eq!(
2660                handle_2.read(app).events,
2661                vec![
2662                    "observed event 1".to_string(),
2663                    "observed event 2".to_string(),
2664                ]
2665            );
2666
2667            handle_2.update(app, |view, _| {
2668                drop(handle_1);
2669                view.other.take();
2670            });
2671
2672            assert_eq!(app.ctx.windows[&window_id].views.len(), 2);
2673            assert!(app.subscriptions.is_empty());
2674            assert!(app.observations.is_empty());
2675        })
2676    }
2677
2678    #[test]
2679    fn test_subscribe_and_emit_from_view() {
2680        #[derive(Default)]
2681        struct View {
2682            events: Vec<usize>,
2683        }
2684
2685        impl Entity for View {
2686            type Event = usize;
2687        }
2688
2689        impl super::View for View {
2690            fn render<'a>(&self, _: &AppContext) -> ElementBox {
2691                Empty::new().boxed()
2692            }
2693
2694            fn ui_name() -> &'static str {
2695                "View"
2696            }
2697        }
2698
2699        struct Model;
2700
2701        impl Entity for Model {
2702            type Event = usize;
2703        }
2704
2705        App::test((), |app| {
2706            let (window_id, handle_1) = app.add_window(|_| View::default());
2707            let handle_2 = app.add_view(window_id, |_| View::default());
2708            let handle_2b = handle_2.clone();
2709            let handle_3 = app.add_model(|_| Model);
2710
2711            handle_1.update(app, |_, c| {
2712                c.subscribe_to_view(&handle_2, move |me, _, event, c| {
2713                    me.events.push(*event);
2714
2715                    c.subscribe_to_view(&handle_2b, |me, _, event, _| {
2716                        me.events.push(*event * 2);
2717                    });
2718                });
2719
2720                c.subscribe_to_model(&handle_3, |me, _, event, _| {
2721                    me.events.push(*event);
2722                })
2723            });
2724
2725            handle_2.update(app, |_, c| c.emit(7));
2726            assert_eq!(handle_1.read(app).events, vec![7]);
2727
2728            handle_2.update(app, |_, c| c.emit(5));
2729            assert_eq!(handle_1.read(app).events, vec![7, 10, 5]);
2730
2731            handle_3.update(app, |_, c| c.emit(9));
2732            assert_eq!(handle_1.read(app).events, vec![7, 10, 5, 9]);
2733        })
2734    }
2735
2736    #[test]
2737    fn test_dropping_subscribers() {
2738        struct View;
2739
2740        impl Entity for View {
2741            type Event = ();
2742        }
2743
2744        impl super::View for View {
2745            fn render<'a>(&self, _: &AppContext) -> ElementBox {
2746                Empty::new().boxed()
2747            }
2748
2749            fn ui_name() -> &'static str {
2750                "View"
2751            }
2752        }
2753
2754        struct Model;
2755
2756        impl Entity for Model {
2757            type Event = ();
2758        }
2759
2760        App::test((), |app| {
2761            let (window_id, _) = app.add_window(|_| View);
2762            let observing_view = app.add_view(window_id, |_| View);
2763            let emitting_view = app.add_view(window_id, |_| View);
2764            let observing_model = app.add_model(|_| Model);
2765            let observed_model = app.add_model(|_| Model);
2766
2767            observing_view.update(app, |_, ctx| {
2768                ctx.subscribe_to_view(&emitting_view, |_, _, _, _| {});
2769                ctx.subscribe_to_model(&observed_model, |_, _, _, _| {});
2770            });
2771            observing_model.update(app, |_, ctx| {
2772                ctx.subscribe(&observed_model, |_, _, _| {});
2773            });
2774
2775            app.update(|| {
2776                drop(observing_view);
2777                drop(observing_model);
2778            });
2779
2780            emitting_view.update(app, |_, ctx| ctx.emit(()));
2781            observed_model.update(app, |_, ctx| ctx.emit(()));
2782        })
2783    }
2784
2785    #[test]
2786    fn test_observe_and_notify_from_view() {
2787        #[derive(Default)]
2788        struct View {
2789            events: Vec<usize>,
2790        }
2791
2792        impl Entity for View {
2793            type Event = usize;
2794        }
2795
2796        impl super::View for View {
2797            fn render<'a>(&self, _: &AppContext) -> ElementBox {
2798                Empty::new().boxed()
2799            }
2800
2801            fn ui_name() -> &'static str {
2802                "View"
2803            }
2804        }
2805
2806        #[derive(Default)]
2807        struct Model {
2808            count: usize,
2809        }
2810
2811        impl Entity for Model {
2812            type Event = ();
2813        }
2814
2815        App::test((), |app| {
2816            let (_, view) = app.add_window(|_| View::default());
2817            let model = app.add_model(|_| Model::default());
2818
2819            view.update(app, |_, c| {
2820                c.observe(&model, |me, observed, c| {
2821                    me.events.push(observed.read(c).count)
2822                });
2823            });
2824
2825            model.update(app, |model, c| {
2826                model.count = 11;
2827                c.notify();
2828            });
2829            assert_eq!(view.read(app).events, vec![11]);
2830        })
2831    }
2832
2833    #[test]
2834    fn test_dropping_observers() {
2835        struct View;
2836
2837        impl Entity for View {
2838            type Event = ();
2839        }
2840
2841        impl super::View for View {
2842            fn render<'a>(&self, _: &AppContext) -> ElementBox {
2843                Empty::new().boxed()
2844            }
2845
2846            fn ui_name() -> &'static str {
2847                "View"
2848            }
2849        }
2850
2851        struct Model;
2852
2853        impl Entity for Model {
2854            type Event = ();
2855        }
2856
2857        App::test((), |app| {
2858            let (window_id, _) = app.add_window(|_| View);
2859            let observing_view = app.add_view(window_id, |_| View);
2860            let observing_model = app.add_model(|_| Model);
2861            let observed_model = app.add_model(|_| Model);
2862
2863            observing_view.update(app, |_, ctx| {
2864                ctx.observe(&observed_model, |_, _, _| {});
2865            });
2866            observing_model.update(app, |_, ctx| {
2867                ctx.observe(&observed_model, |_, _, _| {});
2868            });
2869
2870            app.update(|| {
2871                drop(observing_view);
2872                drop(observing_model);
2873            });
2874
2875            observed_model.update(app, |_, ctx| ctx.notify());
2876        })
2877    }
2878
2879    #[test]
2880    fn test_focus() {
2881        #[derive(Default)]
2882        struct View {
2883            events: Vec<String>,
2884        }
2885
2886        impl Entity for View {
2887            type Event = String;
2888        }
2889
2890        impl super::View for View {
2891            fn render<'a>(&self, _: &AppContext) -> ElementBox {
2892                Empty::new().boxed()
2893            }
2894
2895            fn ui_name() -> &'static str {
2896                "View"
2897            }
2898
2899            fn on_focus(&mut self, ctx: &mut ViewContext<Self>) {
2900                self.events.push("self focused".into());
2901                ctx.emit("focused".into());
2902            }
2903
2904            fn on_blur(&mut self, ctx: &mut ViewContext<Self>) {
2905                self.events.push("self blurred".into());
2906                ctx.emit("blurred".into());
2907            }
2908        }
2909
2910        App::test((), |app| {
2911            let (window_id, view_1) = app.add_window(|_| View::default());
2912            let view_2 = app.add_view(window_id, |_| View::default());
2913
2914            view_1.update(app, |_, ctx| {
2915                ctx.subscribe_to_view(&view_2, |view_1, _, event, _| {
2916                    view_1.events.push(format!("view 2 {}", event));
2917                });
2918                ctx.focus(&view_2);
2919            });
2920
2921            view_1.update(app, |_, ctx| {
2922                ctx.focus(&view_1);
2923            });
2924
2925            assert_eq!(
2926                view_1.read(app).events,
2927                [
2928                    "self focused".to_string(),
2929                    "self blurred".to_string(),
2930                    "view 2 focused".to_string(),
2931                    "self focused".to_string(),
2932                    "view 2 blurred".to_string(),
2933                ],
2934            );
2935        })
2936    }
2937
2938    #[test]
2939    fn test_spawn_from_view() {
2940        #[derive(Default)]
2941        struct View {
2942            count: usize,
2943        }
2944
2945        impl Entity for View {
2946            type Event = ();
2947        }
2948
2949        impl super::View for View {
2950            fn render<'a>(&self, _: &AppContext) -> ElementBox {
2951                Empty::new().boxed()
2952            }
2953
2954            fn ui_name() -> &'static str {
2955                "View"
2956            }
2957        }
2958
2959        App::test_async((), |mut app| async move {
2960            let handle = app.add_window(|_| View::default()).1;
2961            handle
2962                .update(&mut app, |_, c| {
2963                    c.spawn(async { 7 }, |me, output, _| {
2964                        me.count = output;
2965                    })
2966                })
2967                .await;
2968            app.read(|ctx| assert_eq!(handle.read(ctx).count, 7));
2969            handle
2970                .update(&mut app, |_, c| {
2971                    c.spawn(async { 14 }, |me, output, _| {
2972                        me.count = output;
2973                    })
2974                })
2975                .await;
2976            app.read(|ctx| assert_eq!(handle.read(ctx).count, 14));
2977        });
2978    }
2979
2980    #[test]
2981    fn test_spawn_stream_local_from_view() {
2982        #[derive(Default)]
2983        struct View {
2984            events: Vec<Option<usize>>,
2985        }
2986
2987        impl Entity for View {
2988            type Event = ();
2989        }
2990
2991        impl super::View for View {
2992            fn render<'a>(&self, _: &AppContext) -> ElementBox {
2993                Empty::new().boxed()
2994            }
2995
2996            fn ui_name() -> &'static str {
2997                "View"
2998            }
2999        }
3000
3001        App::test_async((), |mut app| async move {
3002            let (_, handle) = app.add_window(|_| View::default());
3003            handle
3004                .update(&mut app, |_, c| {
3005                    c.spawn_stream(
3006                        smol::stream::iter(vec![1_usize, 2, 3]),
3007                        |me, output, _| {
3008                            me.events.push(Some(output));
3009                        },
3010                        |me, _| {
3011                            me.events.push(None);
3012                        },
3013                    )
3014                })
3015                .await;
3016
3017            app.read(|ctx| assert_eq!(handle.read(ctx).events, [Some(1), Some(2), Some(3), None]))
3018        });
3019    }
3020
3021    #[test]
3022    fn test_dispatch_action() {
3023        struct ViewA {
3024            id: usize,
3025        }
3026
3027        impl Entity for ViewA {
3028            type Event = ();
3029        }
3030
3031        impl View for ViewA {
3032            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3033                Empty::new().boxed()
3034            }
3035
3036            fn ui_name() -> &'static str {
3037                "View"
3038            }
3039        }
3040
3041        struct ViewB {
3042            id: usize,
3043        }
3044
3045        impl Entity for ViewB {
3046            type Event = ();
3047        }
3048
3049        impl View for ViewB {
3050            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3051                Empty::new().boxed()
3052            }
3053
3054            fn ui_name() -> &'static str {
3055                "View"
3056            }
3057        }
3058
3059        struct ActionArg {
3060            foo: String,
3061        }
3062
3063        App::test((), |app| {
3064            let actions = Rc::new(RefCell::new(Vec::new()));
3065
3066            let actions_clone = actions.clone();
3067            app.add_global_action("action", move |_: &ActionArg, _: &mut MutableAppContext| {
3068                actions_clone.borrow_mut().push("global a".to_string());
3069            });
3070
3071            let actions_clone = actions.clone();
3072            app.add_global_action("action", move |_: &ActionArg, _: &mut MutableAppContext| {
3073                actions_clone.borrow_mut().push("global b".to_string());
3074            });
3075
3076            let actions_clone = actions.clone();
3077            app.add_action("action", move |view: &mut ViewA, arg: &ActionArg, ctx| {
3078                assert_eq!(arg.foo, "bar");
3079                ctx.propagate_action();
3080                actions_clone.borrow_mut().push(format!("{} a", view.id));
3081            });
3082
3083            let actions_clone = actions.clone();
3084            app.add_action("action", move |view: &mut ViewA, _: &ActionArg, ctx| {
3085                if view.id != 1 {
3086                    ctx.propagate_action();
3087                }
3088                actions_clone.borrow_mut().push(format!("{} b", view.id));
3089            });
3090
3091            let actions_clone = actions.clone();
3092            app.add_action("action", move |view: &mut ViewB, _: &ActionArg, ctx| {
3093                ctx.propagate_action();
3094                actions_clone.borrow_mut().push(format!("{} c", view.id));
3095            });
3096
3097            let actions_clone = actions.clone();
3098            app.add_action("action", move |view: &mut ViewB, _: &ActionArg, ctx| {
3099                ctx.propagate_action();
3100                actions_clone.borrow_mut().push(format!("{} d", view.id));
3101            });
3102
3103            let (window_id, view_1) = app.add_window(|_| ViewA { id: 1 });
3104            let view_2 = app.add_view(window_id, |_| ViewB { id: 2 });
3105            let view_3 = app.add_view(window_id, |_| ViewA { id: 3 });
3106            let view_4 = app.add_view(window_id, |_| ViewB { id: 4 });
3107
3108            app.dispatch_action(
3109                window_id,
3110                vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
3111                "action",
3112                ActionArg { foo: "bar".into() },
3113            );
3114
3115            assert_eq!(
3116                *actions.borrow(),
3117                vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "1 b"]
3118            );
3119
3120            // Remove view_1, which doesn't propagate the action
3121            actions.borrow_mut().clear();
3122            app.dispatch_action(
3123                window_id,
3124                vec![view_2.id(), view_3.id(), view_4.id()],
3125                "action",
3126                ActionArg { foo: "bar".into() },
3127            );
3128
3129            assert_eq!(
3130                *actions.borrow(),
3131                vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "global b", "global a"]
3132            );
3133        })
3134    }
3135
3136    #[test]
3137    fn test_dispatch_keystroke() {
3138        use std::cell::Cell;
3139
3140        #[derive(Clone)]
3141        struct ActionArg {
3142            key: String,
3143        }
3144
3145        struct View {
3146            id: usize,
3147            keymap_context: keymap::Context,
3148        }
3149
3150        impl Entity for View {
3151            type Event = ();
3152        }
3153
3154        impl super::View for View {
3155            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3156                Empty::new().boxed()
3157            }
3158
3159            fn ui_name() -> &'static str {
3160                "View"
3161            }
3162
3163            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
3164                self.keymap_context.clone()
3165            }
3166        }
3167
3168        impl View {
3169            fn new(id: usize) -> Self {
3170                View {
3171                    id,
3172                    keymap_context: keymap::Context::default(),
3173                }
3174            }
3175        }
3176
3177        App::test((), |app| {
3178            let mut view_1 = View::new(1);
3179            let mut view_2 = View::new(2);
3180            let mut view_3 = View::new(3);
3181            view_1.keymap_context.set.insert("a".into());
3182            view_2.keymap_context.set.insert("b".into());
3183            view_3.keymap_context.set.insert("c".into());
3184
3185            let (window_id, view_1) = app.add_window(|_| view_1);
3186            let view_2 = app.add_view(window_id, |_| view_2);
3187            let view_3 = app.add_view(window_id, |_| view_3);
3188
3189            // This keymap's only binding dispatches an action on view 2 because that view will have
3190            // "a" and "b" in its context, but not "c".
3191            let binding = keymap::Binding::new("a", "action", Some("a && b && !c"))
3192                .with_arg(ActionArg { key: "a".into() });
3193            app.add_bindings(vec![binding]);
3194
3195            let handled_action = Rc::new(Cell::new(false));
3196            let handled_action_clone = handled_action.clone();
3197            app.add_action("action", move |view: &mut View, arg: &ActionArg, _ctx| {
3198                handled_action_clone.set(true);
3199                assert_eq!(view.id, 2);
3200                assert_eq!(arg.key, "a");
3201            });
3202
3203            app.dispatch_keystroke(
3204                window_id,
3205                vec![view_1.id(), view_2.id(), view_3.id()],
3206                &Keystroke::parse("a").unwrap(),
3207            )
3208            .unwrap();
3209
3210            assert!(handled_action.get());
3211        });
3212    }
3213
3214    // #[test]
3215    // fn test_ui_and_window_updates() {
3216    //     struct View {
3217    //         count: usize,
3218    //     }
3219
3220    //     impl Entity for View {
3221    //         type Event = ();
3222    //     }
3223
3224    //     impl super::View for View {
3225    //         fn render<'a>(&self, _: &AppContext) -> ElementBox {
3226    //             Empty::new().boxed()
3227    //         }
3228
3229    //         fn ui_name() -> &'static str {
3230    //             "View"
3231    //         }
3232    //     }
3233
3234    //     App::test(|app| async move {
3235    //         let (window_id, _) = app.add_window(|_| View { count: 3 });
3236    //         let view_1 = app.add_view(window_id, |_| View { count: 1 });
3237    //         let view_2 = app.add_view(window_id, |_| View { count: 2 });
3238
3239    //         // Ensure that registering for UI updates after mutating the app still gives us all the
3240    //         // updates.
3241    //         let ui_updates = Rc::new(RefCell::new(Vec::new()));
3242    //         let ui_updates_ = ui_updates.clone();
3243    //         app.on_ui_update(move |update, _| ui_updates_.borrow_mut().push(update));
3244
3245    //         assert_eq!(
3246    //             ui_updates.borrow_mut().drain(..).collect::<Vec<_>>(),
3247    //             vec![UiUpdate::OpenWindow {
3248    //                 window_id,
3249    //                 width: 1024.0,
3250    //                 height: 768.0,
3251    //             }]
3252    //         );
3253
3254    //         let window_invalidations = Rc::new(RefCell::new(Vec::new()));
3255    //         let window_invalidations_ = window_invalidations.clone();
3256    //         app.on_window_invalidated(window_id, move |update, _| {
3257    //             window_invalidations_.borrow_mut().push(update)
3258    //         });
3259
3260    //         let view_2_id = view_2.id();
3261    //         view_1.update(app, |view, ctx| {
3262    //             view.count = 7;
3263    //             ctx.notify();
3264    //             drop(view_2);
3265    //         });
3266
3267    //         let invalidation = window_invalidations.borrow_mut().drain(..).next().unwrap();
3268    //         assert_eq!(invalidation.updated.len(), 1);
3269    //         assert!(invalidation.updated.contains(&view_1.id()));
3270    //         assert_eq!(invalidation.removed, vec![view_2_id]);
3271
3272    //         let view_3 = view_1.update(app, |_, ctx| ctx.add_view(|_| View { count: 8 }));
3273
3274    //         let invalidation = window_invalidations.borrow_mut().drain(..).next().unwrap();
3275    //         assert_eq!(invalidation.updated.len(), 1);
3276    //         assert!(invalidation.updated.contains(&view_3.id()));
3277    //         assert!(invalidation.removed.is_empty());
3278
3279    //         view_3
3280    //             .update(app, |_, ctx| {
3281    //                 ctx.spawn_local(async { 9 }, |me, output, ctx| {
3282    //                     me.count = output;
3283    //                     ctx.notify();
3284    //                 })
3285    //             })
3286    //             .await;
3287
3288    //         let invalidation = window_invalidations.borrow_mut().drain(..).next().unwrap();
3289    //         assert_eq!(invalidation.updated.len(), 1);
3290    //         assert!(invalidation.updated.contains(&view_3.id()));
3291    //         assert!(invalidation.removed.is_empty());
3292    //     });
3293    // }
3294
3295    #[test]
3296    fn test_finish_pending_tasks() {
3297        struct View;
3298
3299        impl Entity for View {
3300            type Event = ();
3301        }
3302
3303        impl super::View for View {
3304            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3305                Empty::new().boxed()
3306            }
3307
3308            fn ui_name() -> &'static str {
3309                "View"
3310            }
3311        }
3312
3313        struct Model;
3314
3315        impl Entity for Model {
3316            type Event = ();
3317        }
3318
3319        App::test_async((), |mut app| async move {
3320            let model = app.add_model(|_| Model);
3321            let (_, view) = app.add_window(|_| View);
3322
3323            model.update(&mut app, |_, ctx| {
3324                ctx.spawn(async {}, |_, _, _| {}).detach();
3325                // Cancel this task
3326                drop(ctx.spawn(async {}, |_, _, _| {}));
3327            });
3328
3329            view.update(&mut app, |_, ctx| {
3330                ctx.spawn(async {}, |_, _, _| {}).detach();
3331                // Cancel this task
3332                drop(ctx.spawn(async {}, |_, _, _| {}));
3333            });
3334
3335            assert!(!app.0.borrow().future_handlers.borrow().is_empty());
3336            app.finish_pending_tasks().await;
3337            assert!(app.0.borrow().future_handlers.borrow().is_empty());
3338            app.finish_pending_tasks().await; // Don't block if there are no tasks
3339
3340            model.update(&mut app, |_, ctx| {
3341                ctx.spawn_stream(smol::stream::iter(vec![1, 2, 3]), |_, _, _| {}, |_, _| {})
3342                    .detach();
3343                // Cancel this task
3344                drop(ctx.spawn_stream(smol::stream::iter(vec![1, 2, 3]), |_, _, _| {}, |_, _| {}));
3345            });
3346
3347            view.update(&mut app, |_, ctx| {
3348                ctx.spawn_stream(smol::stream::iter(vec![1, 2, 3]), |_, _, _| {}, |_, _| {})
3349                    .detach();
3350                // Cancel this task
3351                drop(ctx.spawn_stream(smol::stream::iter(vec![1, 2, 3]), |_, _, _| {}, |_, _| {}));
3352            });
3353
3354            assert!(!app.0.borrow().stream_handlers.borrow().is_empty());
3355            app.finish_pending_tasks().await;
3356            assert!(app.0.borrow().stream_handlers.borrow().is_empty());
3357            app.finish_pending_tasks().await; // Don't block if there are no tasks
3358
3359            // Tasks are considered finished when we drop handles
3360            let mut tasks = Vec::new();
3361            model.update(&mut app, |_, ctx| {
3362                tasks.push(Box::new(ctx.spawn(async {}, |_, _, _| {})));
3363                tasks.push(Box::new(ctx.spawn_stream(
3364                    smol::stream::iter(vec![1, 2, 3]),
3365                    |_, _, _| {},
3366                    |_, _| {},
3367                )));
3368            });
3369
3370            view.update(&mut app, |_, ctx| {
3371                tasks.push(Box::new(ctx.spawn(async {}, |_, _, _| {})));
3372                tasks.push(Box::new(ctx.spawn_stream(
3373                    smol::stream::iter(vec![1, 2, 3]),
3374                    |_, _, _| {},
3375                    |_, _| {},
3376                )));
3377            });
3378
3379            assert!(!app.0.borrow().stream_handlers.borrow().is_empty());
3380
3381            let finish_pending_tasks = app.finish_pending_tasks();
3382            drop(tasks);
3383            finish_pending_tasks.await;
3384            assert!(app.0.borrow().stream_handlers.borrow().is_empty());
3385            app.finish_pending_tasks().await; // Don't block if there are no tasks
3386        });
3387    }
3388}