app.rs

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