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