app.rs

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