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        predicate: impl FnMut(&T, &AppContext) -> bool,
2007    ) -> impl Future<Output = ()> {
2008        self.condition_with_duration(Duration::from_millis(100), ctx, predicate)
2009    }
2010
2011    pub fn condition_with_duration(
2012        &self,
2013        duration: Duration,
2014        ctx: &TestAppContext,
2015        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2016    ) -> impl Future<Output = ()> {
2017        let mut ctx = ctx.0.borrow_mut();
2018        let tx = ctx
2019            .async_observations
2020            .entry(self.id())
2021            .or_insert_with(|| postage::broadcast::channel(128).0);
2022        let mut rx = tx.subscribe();
2023        let ctx = ctx.weak_self.as_ref().unwrap().upgrade().unwrap();
2024        let handle = self.downgrade();
2025
2026        async move {
2027            timeout(duration, async move {
2028                loop {
2029                    {
2030                        let ctx = ctx.borrow();
2031                        let ctx = ctx.as_ref();
2032                        if predicate(
2033                            handle
2034                                .upgrade(ctx)
2035                                .expect("model dropped with pending condition")
2036                                .read(ctx),
2037                            ctx,
2038                        ) {
2039                            break;
2040                        }
2041                    }
2042
2043                    rx.recv()
2044                        .await
2045                        .expect("model dropped with pending condition");
2046                }
2047            })
2048            .await
2049            .expect("condition timed out");
2050        }
2051    }
2052}
2053
2054impl<T> Clone for ModelHandle<T> {
2055    fn clone(&self) -> Self {
2056        if let Some(ref_counts) = self.ref_counts.upgrade() {
2057            ref_counts.lock().inc_entity(self.model_id);
2058        }
2059
2060        Self {
2061            model_id: self.model_id,
2062            model_type: PhantomData,
2063            ref_counts: self.ref_counts.clone(),
2064        }
2065    }
2066}
2067
2068impl<T> PartialEq for ModelHandle<T> {
2069    fn eq(&self, other: &Self) -> bool {
2070        self.model_id == other.model_id
2071    }
2072}
2073
2074impl<T> Eq for ModelHandle<T> {}
2075
2076impl<T> Hash for ModelHandle<T> {
2077    fn hash<H: Hasher>(&self, state: &mut H) {
2078        self.model_id.hash(state);
2079    }
2080}
2081
2082impl<T> std::borrow::Borrow<usize> for ModelHandle<T> {
2083    fn borrow(&self) -> &usize {
2084        &self.model_id
2085    }
2086}
2087
2088impl<T> Debug for ModelHandle<T> {
2089    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2090        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
2091            .field(&self.model_id)
2092            .finish()
2093    }
2094}
2095
2096unsafe impl<T> Send for ModelHandle<T> {}
2097unsafe impl<T> Sync for ModelHandle<T> {}
2098
2099impl<T> Drop for ModelHandle<T> {
2100    fn drop(&mut self) {
2101        if let Some(ref_counts) = self.ref_counts.upgrade() {
2102            ref_counts.lock().dec_model(self.model_id);
2103        }
2104    }
2105}
2106
2107impl<T> Handle<T> for ModelHandle<T> {
2108    fn id(&self) -> usize {
2109        self.model_id
2110    }
2111
2112    fn location(&self) -> EntityLocation {
2113        EntityLocation::Model(self.model_id)
2114    }
2115}
2116
2117pub struct WeakModelHandle<T> {
2118    model_id: usize,
2119    model_type: PhantomData<T>,
2120}
2121
2122impl<T: Entity> WeakModelHandle<T> {
2123    fn new(model_id: usize) -> Self {
2124        Self {
2125            model_id,
2126            model_type: PhantomData,
2127        }
2128    }
2129
2130    pub fn upgrade(&self, app: &AppContext) -> Option<ModelHandle<T>> {
2131        if app.models.contains_key(&self.model_id) {
2132            Some(ModelHandle::new(self.model_id, &app.ref_counts))
2133        } else {
2134            None
2135        }
2136    }
2137}
2138
2139pub struct ViewHandle<T> {
2140    window_id: usize,
2141    view_id: usize,
2142    view_type: PhantomData<T>,
2143    ref_counts: Weak<Mutex<RefCounts>>,
2144}
2145
2146impl<T: View> ViewHandle<T> {
2147    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2148        ref_counts.lock().inc_entity(view_id);
2149        Self {
2150            window_id,
2151            view_id,
2152            view_type: PhantomData,
2153            ref_counts: Arc::downgrade(ref_counts),
2154        }
2155    }
2156
2157    pub fn downgrade(&self) -> WeakViewHandle<T> {
2158        WeakViewHandle::new(self.window_id, self.view_id)
2159    }
2160
2161    pub fn window_id(&self) -> usize {
2162        self.window_id
2163    }
2164
2165    pub fn id(&self) -> usize {
2166        self.view_id
2167    }
2168
2169    pub fn read<'a, A: ReadView>(&self, app: &'a A) -> &'a T {
2170        app.read_view(self)
2171    }
2172
2173    pub fn update<A, F, S>(&self, app: &mut A, update: F) -> S
2174    where
2175        A: UpdateView,
2176        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2177    {
2178        app.update_view(self, update)
2179    }
2180
2181    pub fn is_focused(&self, app: &AppContext) -> bool {
2182        app.focused_view_id(self.window_id)
2183            .map_or(false, |focused_id| focused_id == self.view_id)
2184    }
2185
2186    pub fn condition(
2187        &self,
2188        ctx: &TestAppContext,
2189        mut predicate: impl 'static + FnMut(&T, &AppContext) -> bool,
2190    ) -> impl 'static + Future<Output = ()> {
2191        let mut ctx = ctx.0.borrow_mut();
2192        let tx = ctx
2193            .async_observations
2194            .entry(self.id())
2195            .or_insert_with(|| postage::broadcast::channel(128).0);
2196        let mut rx = tx.subscribe();
2197        let ctx = ctx.weak_self.as_ref().unwrap().upgrade().unwrap();
2198        let handle = self.downgrade();
2199
2200        async move {
2201            timeout(Duration::from_millis(200), async move {
2202                loop {
2203                    {
2204                        let ctx = ctx.borrow();
2205                        let ctx = ctx.as_ref();
2206                        if predicate(
2207                            handle
2208                                .upgrade(ctx)
2209                                .expect("model dropped with pending condition")
2210                                .read(ctx),
2211                            ctx,
2212                        ) {
2213                            break;
2214                        }
2215                    }
2216
2217                    rx.recv()
2218                        .await
2219                        .expect("model dropped with pending condition");
2220                }
2221            })
2222            .await
2223            .expect("condition timed out");
2224        }
2225    }
2226}
2227
2228impl<T> Clone for ViewHandle<T> {
2229    fn clone(&self) -> Self {
2230        if let Some(ref_counts) = self.ref_counts.upgrade() {
2231            ref_counts.lock().inc_entity(self.view_id);
2232        }
2233
2234        Self {
2235            window_id: self.window_id,
2236            view_id: self.view_id,
2237            view_type: PhantomData,
2238            ref_counts: self.ref_counts.clone(),
2239        }
2240    }
2241}
2242
2243impl<T> PartialEq for ViewHandle<T> {
2244    fn eq(&self, other: &Self) -> bool {
2245        self.window_id == other.window_id && self.view_id == other.view_id
2246    }
2247}
2248
2249impl<T> Eq for ViewHandle<T> {}
2250
2251impl<T> Debug for ViewHandle<T> {
2252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2253        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
2254            .field("window_id", &self.window_id)
2255            .field("view_id", &self.view_id)
2256            .finish()
2257    }
2258}
2259
2260impl<T> Drop for ViewHandle<T> {
2261    fn drop(&mut self) {
2262        if let Some(ref_counts) = self.ref_counts.upgrade() {
2263            ref_counts.lock().dec_view(self.window_id, self.view_id);
2264        }
2265    }
2266}
2267
2268impl<T> Handle<T> for ViewHandle<T> {
2269    fn id(&self) -> usize {
2270        self.view_id
2271    }
2272
2273    fn location(&self) -> EntityLocation {
2274        EntityLocation::View(self.window_id, self.view_id)
2275    }
2276}
2277
2278#[derive(Clone)]
2279pub struct AnyViewHandle {
2280    window_id: usize,
2281    view_id: usize,
2282    view_type: TypeId,
2283    ref_counts: Weak<Mutex<RefCounts>>,
2284}
2285
2286impl AnyViewHandle {
2287    pub fn id(&self) -> usize {
2288        self.view_id
2289    }
2290
2291    pub fn is<T: 'static>(&self) -> bool {
2292        TypeId::of::<T>() == self.view_type
2293    }
2294
2295    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
2296        if self.is::<T>() {
2297            if let Some(ref_counts) = self.ref_counts.upgrade() {
2298                return Some(ViewHandle::new(self.window_id, self.view_id, &ref_counts));
2299            }
2300        }
2301        None
2302    }
2303}
2304
2305impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
2306    fn from(handle: &ViewHandle<T>) -> Self {
2307        if let Some(ref_counts) = handle.ref_counts.upgrade() {
2308            ref_counts.lock().inc_entity(handle.view_id);
2309        }
2310        AnyViewHandle {
2311            window_id: handle.window_id,
2312            view_id: handle.view_id,
2313            view_type: TypeId::of::<T>(),
2314            ref_counts: handle.ref_counts.clone(),
2315        }
2316    }
2317}
2318
2319impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
2320    fn from(handle: ViewHandle<T>) -> Self {
2321        (&handle).into()
2322    }
2323}
2324
2325pub struct WeakViewHandle<T> {
2326    window_id: usize,
2327    view_id: usize,
2328    view_type: PhantomData<T>,
2329}
2330
2331impl<T: View> WeakViewHandle<T> {
2332    fn new(window_id: usize, view_id: usize) -> Self {
2333        Self {
2334            window_id,
2335            view_id,
2336            view_type: PhantomData,
2337        }
2338    }
2339
2340    pub fn upgrade(&self, app: &AppContext) -> Option<ViewHandle<T>> {
2341        if app
2342            .windows
2343            .get(&self.window_id)
2344            .and_then(|w| w.views.get(&self.view_id))
2345            .is_some()
2346        {
2347            Some(ViewHandle::new(
2348                self.window_id,
2349                self.view_id,
2350                &app.ref_counts,
2351            ))
2352        } else {
2353            None
2354        }
2355    }
2356}
2357
2358impl<T> Clone for WeakViewHandle<T> {
2359    fn clone(&self) -> Self {
2360        Self {
2361            window_id: self.window_id,
2362            view_id: self.view_id,
2363            view_type: PhantomData,
2364        }
2365    }
2366}
2367
2368pub struct ValueHandle<T> {
2369    value_type: PhantomData<T>,
2370    tag_type_id: TypeId,
2371    id: usize,
2372    ref_counts: Weak<Mutex<RefCounts>>,
2373}
2374
2375impl<T: 'static> ValueHandle<T> {
2376    fn new(tag_type_id: TypeId, id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2377        ref_counts.lock().inc_value(tag_type_id, id);
2378        Self {
2379            value_type: PhantomData,
2380            tag_type_id,
2381            id,
2382            ref_counts: Arc::downgrade(ref_counts),
2383        }
2384    }
2385
2386    pub fn read<R>(&self, ctx: &AppContext, f: impl FnOnce(&T) -> R) -> R {
2387        f(ctx
2388            .values
2389            .read()
2390            .get(&(self.tag_type_id, self.id))
2391            .unwrap()
2392            .downcast_ref()
2393            .unwrap())
2394    }
2395
2396    pub fn update<R>(&self, ctx: &AppContext, f: impl FnOnce(&mut T) -> R) -> R {
2397        f(ctx
2398            .values
2399            .write()
2400            .get_mut(&(self.tag_type_id, self.id))
2401            .unwrap()
2402            .downcast_mut()
2403            .unwrap())
2404    }
2405}
2406
2407impl<T> Drop for ValueHandle<T> {
2408    fn drop(&mut self) {
2409        if let Some(ref_counts) = self.ref_counts.upgrade() {
2410            ref_counts.lock().dec_value(self.tag_type_id, self.id);
2411        }
2412    }
2413}
2414
2415#[derive(Default)]
2416struct RefCounts {
2417    entity_counts: HashMap<usize, usize>,
2418    value_counts: HashMap<(TypeId, usize), usize>,
2419    dropped_models: HashSet<usize>,
2420    dropped_views: HashSet<(usize, usize)>,
2421    dropped_values: HashSet<(TypeId, usize)>,
2422}
2423
2424impl RefCounts {
2425    fn inc_entity(&mut self, model_id: usize) {
2426        *self.entity_counts.entry(model_id).or_insert(0) += 1;
2427    }
2428
2429    fn inc_value(&mut self, tag_type_id: TypeId, id: usize) {
2430        *self.value_counts.entry((tag_type_id, id)).or_insert(0) += 1;
2431    }
2432
2433    fn dec_model(&mut self, model_id: usize) {
2434        let count = self.entity_counts.get_mut(&model_id).unwrap();
2435        *count -= 1;
2436        if *count == 0 {
2437            self.entity_counts.remove(&model_id);
2438            self.dropped_models.insert(model_id);
2439        }
2440    }
2441
2442    fn dec_view(&mut self, window_id: usize, view_id: usize) {
2443        let count = self.entity_counts.get_mut(&view_id).unwrap();
2444        *count -= 1;
2445        if *count == 0 {
2446            self.entity_counts.remove(&view_id);
2447            self.dropped_views.insert((window_id, view_id));
2448        }
2449    }
2450
2451    fn dec_value(&mut self, tag_type_id: TypeId, id: usize) {
2452        let key = (tag_type_id, id);
2453        let count = self.value_counts.get_mut(&key).unwrap();
2454        *count -= 1;
2455        if *count == 0 {
2456            self.value_counts.remove(&key);
2457            self.dropped_values.insert(key);
2458        }
2459    }
2460
2461    fn take_dropped(
2462        &mut self,
2463    ) -> (
2464        HashSet<usize>,
2465        HashSet<(usize, usize)>,
2466        HashSet<(TypeId, usize)>,
2467    ) {
2468        let mut dropped_models = HashSet::new();
2469        let mut dropped_views = HashSet::new();
2470        let mut dropped_values = HashSet::new();
2471        std::mem::swap(&mut self.dropped_models, &mut dropped_models);
2472        std::mem::swap(&mut self.dropped_views, &mut dropped_views);
2473        std::mem::swap(&mut self.dropped_values, &mut dropped_values);
2474        (dropped_models, dropped_views, dropped_values)
2475    }
2476}
2477
2478enum Subscription {
2479    FromModel {
2480        model_id: usize,
2481        callback: Box<dyn FnMut(&mut dyn Any, &dyn Any, &mut MutableAppContext, usize)>,
2482    },
2483    FromView {
2484        window_id: usize,
2485        view_id: usize,
2486        callback: Box<dyn FnMut(&mut dyn Any, &dyn Any, &mut MutableAppContext, usize, usize)>,
2487    },
2488}
2489
2490enum Observation {
2491    FromModel {
2492        model_id: usize,
2493        callback: Box<dyn FnMut(&mut dyn Any, usize, &mut MutableAppContext, usize)>,
2494    },
2495    FromView {
2496        window_id: usize,
2497        view_id: usize,
2498        callback: Box<dyn FnMut(&mut dyn Any, usize, &mut MutableAppContext, usize, usize)>,
2499    },
2500}
2501
2502type FutureHandler = Box<dyn FnOnce(Box<dyn Any>, &mut MutableAppContext) -> Box<dyn Any>>;
2503
2504struct StreamHandler {
2505    item_callback: Box<dyn FnMut(Box<dyn Any>, &mut MutableAppContext) -> bool>,
2506    done_callback: Box<dyn FnOnce(&mut MutableAppContext) -> Box<dyn Any>>,
2507}
2508
2509#[must_use]
2510pub struct EntityTask<T> {
2511    id: usize,
2512    task: Option<executor::Task<T>>,
2513    handler_map: TaskHandlerMap,
2514}
2515
2516enum TaskHandlerMap {
2517    Detached,
2518    Future(Rc<RefCell<HashMap<usize, FutureHandler>>>),
2519    Stream(Rc<RefCell<HashMap<usize, StreamHandler>>>),
2520}
2521
2522impl<T> EntityTask<T> {
2523    fn new(id: usize, task: executor::Task<T>, handler_map: TaskHandlerMap) -> Self {
2524        Self {
2525            id,
2526            task: Some(task),
2527            handler_map,
2528        }
2529    }
2530
2531    pub fn detach(mut self) {
2532        self.handler_map = TaskHandlerMap::Detached;
2533        self.task.take().unwrap().detach();
2534    }
2535
2536    pub async fn cancel(mut self) -> Option<T> {
2537        let task = self.task.take().unwrap();
2538        task.cancel().await
2539    }
2540}
2541
2542impl<T> Future for EntityTask<T> {
2543    type Output = T;
2544
2545    fn poll(
2546        self: std::pin::Pin<&mut Self>,
2547        ctx: &mut std::task::Context<'_>,
2548    ) -> std::task::Poll<Self::Output> {
2549        let task = unsafe { self.map_unchecked_mut(|task| task.task.as_mut().unwrap()) };
2550        task.poll(ctx)
2551    }
2552}
2553
2554impl<T> Drop for EntityTask<T> {
2555    fn drop(self: &mut Self) {
2556        match &self.handler_map {
2557            TaskHandlerMap::Detached => {
2558                return;
2559            }
2560            TaskHandlerMap::Future(map) => {
2561                map.borrow_mut().remove(&self.id);
2562            }
2563            TaskHandlerMap::Stream(map) => {
2564                map.borrow_mut().remove(&self.id);
2565            }
2566        }
2567    }
2568}
2569
2570#[cfg(test)]
2571mod tests {
2572    use super::*;
2573    use crate::elements::*;
2574    use smol::future::poll_once;
2575
2576    #[test]
2577    fn test_model_handles() {
2578        struct Model {
2579            other: Option<ModelHandle<Model>>,
2580            events: Vec<String>,
2581        }
2582
2583        impl Entity for Model {
2584            type Event = usize;
2585        }
2586
2587        impl Model {
2588            fn new(other: Option<ModelHandle<Self>>, ctx: &mut ModelContext<Self>) -> Self {
2589                if let Some(other) = other.as_ref() {
2590                    ctx.observe(other, |me, _, _| {
2591                        me.events.push("notified".into());
2592                    });
2593                    ctx.subscribe(other, |me, event, _| {
2594                        me.events.push(format!("observed event {}", event));
2595                    });
2596                }
2597
2598                Self {
2599                    other,
2600                    events: Vec::new(),
2601                }
2602            }
2603        }
2604
2605        App::test((), |app| {
2606            let handle_1 = app.add_model(|ctx| Model::new(None, ctx));
2607            let handle_2 = app.add_model(|ctx| Model::new(Some(handle_1.clone()), ctx));
2608            assert_eq!(app.ctx.models.len(), 2);
2609
2610            handle_1.update(app, |model, ctx| {
2611                model.events.push("updated".into());
2612                ctx.emit(1);
2613                ctx.notify();
2614                ctx.emit(2);
2615            });
2616            assert_eq!(handle_1.read(app).events, vec!["updated".to_string()]);
2617            assert_eq!(
2618                handle_2.read(app).events,
2619                vec![
2620                    "observed event 1".to_string(),
2621                    "notified".to_string(),
2622                    "observed event 2".to_string(),
2623                ]
2624            );
2625
2626            handle_2.update(app, |model, _| {
2627                drop(handle_1);
2628                model.other.take();
2629            });
2630
2631            assert_eq!(app.ctx.models.len(), 1);
2632            assert!(app.subscriptions.is_empty());
2633            assert!(app.observations.is_empty());
2634        });
2635    }
2636
2637    #[test]
2638    fn test_subscribe_and_emit_from_model() {
2639        #[derive(Default)]
2640        struct Model {
2641            events: Vec<usize>,
2642        }
2643
2644        impl Entity for Model {
2645            type Event = usize;
2646        }
2647
2648        App::test((), |app| {
2649            let handle_1 = app.add_model(|_| Model::default());
2650            let handle_2 = app.add_model(|_| Model::default());
2651            let handle_2b = handle_2.clone();
2652
2653            handle_1.update(app, |_, c| {
2654                c.subscribe(&handle_2, move |model: &mut Model, event, c| {
2655                    model.events.push(*event);
2656
2657                    c.subscribe(&handle_2b, |model, event, _| {
2658                        model.events.push(*event * 2);
2659                    });
2660                });
2661            });
2662
2663            handle_2.update(app, |_, c| c.emit(7));
2664            assert_eq!(handle_1.read(app).events, vec![7]);
2665
2666            handle_2.update(app, |_, c| c.emit(5));
2667            assert_eq!(handle_1.read(app).events, vec![7, 10, 5]);
2668        })
2669    }
2670
2671    #[test]
2672    fn test_observe_and_notify_from_model() {
2673        #[derive(Default)]
2674        struct Model {
2675            count: usize,
2676            events: Vec<usize>,
2677        }
2678
2679        impl Entity for Model {
2680            type Event = ();
2681        }
2682
2683        App::test((), |app| {
2684            let handle_1 = app.add_model(|_| Model::default());
2685            let handle_2 = app.add_model(|_| Model::default());
2686            let handle_2b = handle_2.clone();
2687
2688            handle_1.update(app, |_, c| {
2689                c.observe(&handle_2, move |model, observed, c| {
2690                    model.events.push(observed.read(c).count);
2691                    c.observe(&handle_2b, |model, observed, c| {
2692                        model.events.push(observed.read(c).count * 2);
2693                    });
2694                });
2695            });
2696
2697            handle_2.update(app, |model, c| {
2698                model.count = 7;
2699                c.notify()
2700            });
2701            assert_eq!(handle_1.read(app).events, vec![7]);
2702
2703            handle_2.update(app, |model, c| {
2704                model.count = 5;
2705                c.notify()
2706            });
2707            assert_eq!(handle_1.read(app).events, vec![7, 10, 5])
2708        })
2709    }
2710
2711    #[test]
2712    fn test_spawn_from_model() {
2713        #[derive(Default)]
2714        struct Model {
2715            count: usize,
2716        }
2717
2718        impl Entity for Model {
2719            type Event = ();
2720        }
2721
2722        App::test_async((), |mut app| async move {
2723            let handle = app.add_model(|_| Model::default());
2724            handle
2725                .update(&mut app, |_, c| {
2726                    c.spawn(async { 7 }, |model, output, _| {
2727                        model.count = output;
2728                    })
2729                })
2730                .await;
2731            app.read(|ctx| assert_eq!(handle.read(ctx).count, 7));
2732
2733            handle
2734                .update(&mut app, |_, c| {
2735                    c.spawn(async { 14 }, |model, output, _| {
2736                        model.count = output;
2737                    })
2738                })
2739                .await;
2740            app.read(|ctx| assert_eq!(handle.read(ctx).count, 14));
2741        });
2742    }
2743
2744    #[test]
2745    fn test_spawn_stream_local_from_model() {
2746        #[derive(Default)]
2747        struct Model {
2748            events: Vec<Option<usize>>,
2749        }
2750
2751        impl Entity for Model {
2752            type Event = ();
2753        }
2754
2755        App::test_async((), |mut app| async move {
2756            let handle = app.add_model(|_| Model::default());
2757            handle
2758                .update(&mut app, |_, c| {
2759                    c.spawn_stream(
2760                        smol::stream::iter(vec![1, 2, 3]),
2761                        |model, output, _| {
2762                            model.events.push(Some(output));
2763                        },
2764                        |model, _| {
2765                            model.events.push(None);
2766                        },
2767                    )
2768                })
2769                .await;
2770            app.read(|ctx| assert_eq!(handle.read(ctx).events, [Some(1), Some(2), Some(3), None]));
2771        })
2772    }
2773
2774    #[test]
2775    fn test_view_handles() {
2776        struct View {
2777            other: Option<ViewHandle<View>>,
2778            events: Vec<String>,
2779        }
2780
2781        impl Entity for View {
2782            type Event = usize;
2783        }
2784
2785        impl super::View for View {
2786            fn render<'a>(&self, _: &AppContext) -> ElementBox {
2787                Empty::new().boxed()
2788            }
2789
2790            fn ui_name() -> &'static str {
2791                "View"
2792            }
2793        }
2794
2795        impl View {
2796            fn new(other: Option<ViewHandle<View>>, ctx: &mut ViewContext<Self>) -> Self {
2797                if let Some(other) = other.as_ref() {
2798                    ctx.subscribe_to_view(other, |me, _, event, _| {
2799                        me.events.push(format!("observed event {}", event));
2800                    });
2801                }
2802                Self {
2803                    other,
2804                    events: Vec::new(),
2805                }
2806            }
2807        }
2808
2809        App::test((), |app| {
2810            let (window_id, _) = app.add_window(|ctx| View::new(None, ctx));
2811            let handle_1 = app.add_view(window_id, |ctx| View::new(None, ctx));
2812            let handle_2 = app.add_view(window_id, |ctx| View::new(Some(handle_1.clone()), ctx));
2813            assert_eq!(app.ctx.windows[&window_id].views.len(), 3);
2814
2815            handle_1.update(app, |view, ctx| {
2816                view.events.push("updated".into());
2817                ctx.emit(1);
2818                ctx.emit(2);
2819            });
2820            assert_eq!(handle_1.read(app).events, vec!["updated".to_string()]);
2821            assert_eq!(
2822                handle_2.read(app).events,
2823                vec![
2824                    "observed event 1".to_string(),
2825                    "observed event 2".to_string(),
2826                ]
2827            );
2828
2829            handle_2.update(app, |view, _| {
2830                drop(handle_1);
2831                view.other.take();
2832            });
2833
2834            assert_eq!(app.ctx.windows[&window_id].views.len(), 2);
2835            assert!(app.subscriptions.is_empty());
2836            assert!(app.observations.is_empty());
2837        })
2838    }
2839
2840    #[test]
2841    fn test_subscribe_and_emit_from_view() {
2842        #[derive(Default)]
2843        struct View {
2844            events: Vec<usize>,
2845        }
2846
2847        impl Entity for View {
2848            type Event = usize;
2849        }
2850
2851        impl super::View for View {
2852            fn render<'a>(&self, _: &AppContext) -> ElementBox {
2853                Empty::new().boxed()
2854            }
2855
2856            fn ui_name() -> &'static str {
2857                "View"
2858            }
2859        }
2860
2861        struct Model;
2862
2863        impl Entity for Model {
2864            type Event = usize;
2865        }
2866
2867        App::test((), |app| {
2868            let (window_id, handle_1) = app.add_window(|_| View::default());
2869            let handle_2 = app.add_view(window_id, |_| View::default());
2870            let handle_2b = handle_2.clone();
2871            let handle_3 = app.add_model(|_| Model);
2872
2873            handle_1.update(app, |_, c| {
2874                c.subscribe_to_view(&handle_2, move |me, _, event, c| {
2875                    me.events.push(*event);
2876
2877                    c.subscribe_to_view(&handle_2b, |me, _, event, _| {
2878                        me.events.push(*event * 2);
2879                    });
2880                });
2881
2882                c.subscribe_to_model(&handle_3, |me, _, event, _| {
2883                    me.events.push(*event);
2884                })
2885            });
2886
2887            handle_2.update(app, |_, c| c.emit(7));
2888            assert_eq!(handle_1.read(app).events, vec![7]);
2889
2890            handle_2.update(app, |_, c| c.emit(5));
2891            assert_eq!(handle_1.read(app).events, vec![7, 10, 5]);
2892
2893            handle_3.update(app, |_, c| c.emit(9));
2894            assert_eq!(handle_1.read(app).events, vec![7, 10, 5, 9]);
2895        })
2896    }
2897
2898    #[test]
2899    fn test_dropping_subscribers() {
2900        struct View;
2901
2902        impl Entity for View {
2903            type Event = ();
2904        }
2905
2906        impl super::View for View {
2907            fn render<'a>(&self, _: &AppContext) -> ElementBox {
2908                Empty::new().boxed()
2909            }
2910
2911            fn ui_name() -> &'static str {
2912                "View"
2913            }
2914        }
2915
2916        struct Model;
2917
2918        impl Entity for Model {
2919            type Event = ();
2920        }
2921
2922        App::test((), |app| {
2923            let (window_id, _) = app.add_window(|_| View);
2924            let observing_view = app.add_view(window_id, |_| View);
2925            let emitting_view = app.add_view(window_id, |_| View);
2926            let observing_model = app.add_model(|_| Model);
2927            let observed_model = app.add_model(|_| Model);
2928
2929            observing_view.update(app, |_, ctx| {
2930                ctx.subscribe_to_view(&emitting_view, |_, _, _, _| {});
2931                ctx.subscribe_to_model(&observed_model, |_, _, _, _| {});
2932            });
2933            observing_model.update(app, |_, ctx| {
2934                ctx.subscribe(&observed_model, |_, _, _| {});
2935            });
2936
2937            app.update(|| {
2938                drop(observing_view);
2939                drop(observing_model);
2940            });
2941
2942            emitting_view.update(app, |_, ctx| ctx.emit(()));
2943            observed_model.update(app, |_, ctx| ctx.emit(()));
2944        })
2945    }
2946
2947    #[test]
2948    fn test_observe_and_notify_from_view() {
2949        #[derive(Default)]
2950        struct View {
2951            events: Vec<usize>,
2952        }
2953
2954        impl Entity for View {
2955            type Event = usize;
2956        }
2957
2958        impl super::View for View {
2959            fn render<'a>(&self, _: &AppContext) -> ElementBox {
2960                Empty::new().boxed()
2961            }
2962
2963            fn ui_name() -> &'static str {
2964                "View"
2965            }
2966        }
2967
2968        #[derive(Default)]
2969        struct Model {
2970            count: usize,
2971        }
2972
2973        impl Entity for Model {
2974            type Event = ();
2975        }
2976
2977        App::test((), |app| {
2978            let (_, view) = app.add_window(|_| View::default());
2979            let model = app.add_model(|_| Model::default());
2980
2981            view.update(app, |_, c| {
2982                c.observe(&model, |me, observed, c| {
2983                    me.events.push(observed.read(c).count)
2984                });
2985            });
2986
2987            model.update(app, |model, c| {
2988                model.count = 11;
2989                c.notify();
2990            });
2991            assert_eq!(view.read(app).events, vec![11]);
2992        })
2993    }
2994
2995    #[test]
2996    fn test_dropping_observers() {
2997        struct View;
2998
2999        impl Entity for View {
3000            type Event = ();
3001        }
3002
3003        impl super::View for View {
3004            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3005                Empty::new().boxed()
3006            }
3007
3008            fn ui_name() -> &'static str {
3009                "View"
3010            }
3011        }
3012
3013        struct Model;
3014
3015        impl Entity for Model {
3016            type Event = ();
3017        }
3018
3019        App::test((), |app| {
3020            let (window_id, _) = app.add_window(|_| View);
3021            let observing_view = app.add_view(window_id, |_| View);
3022            let observing_model = app.add_model(|_| Model);
3023            let observed_model = app.add_model(|_| Model);
3024
3025            observing_view.update(app, |_, ctx| {
3026                ctx.observe(&observed_model, |_, _, _| {});
3027            });
3028            observing_model.update(app, |_, ctx| {
3029                ctx.observe(&observed_model, |_, _, _| {});
3030            });
3031
3032            app.update(|| {
3033                drop(observing_view);
3034                drop(observing_model);
3035            });
3036
3037            observed_model.update(app, |_, ctx| ctx.notify());
3038        })
3039    }
3040
3041    #[test]
3042    fn test_focus() {
3043        #[derive(Default)]
3044        struct View {
3045            events: Vec<String>,
3046        }
3047
3048        impl Entity for View {
3049            type Event = String;
3050        }
3051
3052        impl super::View for View {
3053            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3054                Empty::new().boxed()
3055            }
3056
3057            fn ui_name() -> &'static str {
3058                "View"
3059            }
3060
3061            fn on_focus(&mut self, ctx: &mut ViewContext<Self>) {
3062                self.events.push("self focused".into());
3063                ctx.emit("focused".into());
3064            }
3065
3066            fn on_blur(&mut self, ctx: &mut ViewContext<Self>) {
3067                self.events.push("self blurred".into());
3068                ctx.emit("blurred".into());
3069            }
3070        }
3071
3072        App::test((), |app| {
3073            let (window_id, view_1) = app.add_window(|_| View::default());
3074            let view_2 = app.add_view(window_id, |_| View::default());
3075
3076            view_1.update(app, |_, ctx| {
3077                ctx.subscribe_to_view(&view_2, |view_1, _, event, _| {
3078                    view_1.events.push(format!("view 2 {}", event));
3079                });
3080                ctx.focus(&view_2);
3081            });
3082
3083            view_1.update(app, |_, ctx| {
3084                ctx.focus(&view_1);
3085            });
3086
3087            assert_eq!(
3088                view_1.read(app).events,
3089                [
3090                    "self focused".to_string(),
3091                    "self blurred".to_string(),
3092                    "view 2 focused".to_string(),
3093                    "self focused".to_string(),
3094                    "view 2 blurred".to_string(),
3095                ],
3096            );
3097        })
3098    }
3099
3100    #[test]
3101    fn test_spawn_from_view() {
3102        #[derive(Default)]
3103        struct View {
3104            count: usize,
3105        }
3106
3107        impl Entity for View {
3108            type Event = ();
3109        }
3110
3111        impl super::View for View {
3112            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3113                Empty::new().boxed()
3114            }
3115
3116            fn ui_name() -> &'static str {
3117                "View"
3118            }
3119        }
3120
3121        App::test_async((), |mut app| async move {
3122            let handle = app.add_window(|_| View::default()).1;
3123            handle
3124                .update(&mut app, |_, c| {
3125                    c.spawn(async { 7 }, |me, output, _| {
3126                        me.count = output;
3127                    })
3128                })
3129                .await;
3130            app.read(|ctx| assert_eq!(handle.read(ctx).count, 7));
3131            handle
3132                .update(&mut app, |_, c| {
3133                    c.spawn(async { 14 }, |me, output, _| {
3134                        me.count = output;
3135                    })
3136                })
3137                .await;
3138            app.read(|ctx| assert_eq!(handle.read(ctx).count, 14));
3139        });
3140    }
3141
3142    #[test]
3143    fn test_spawn_stream_local_from_view() {
3144        #[derive(Default)]
3145        struct View {
3146            events: Vec<Option<usize>>,
3147        }
3148
3149        impl Entity for View {
3150            type Event = ();
3151        }
3152
3153        impl super::View for View {
3154            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3155                Empty::new().boxed()
3156            }
3157
3158            fn ui_name() -> &'static str {
3159                "View"
3160            }
3161        }
3162
3163        App::test_async((), |mut app| async move {
3164            let (_, handle) = app.add_window(|_| View::default());
3165            handle
3166                .update(&mut app, |_, c| {
3167                    c.spawn_stream(
3168                        smol::stream::iter(vec![1_usize, 2, 3]),
3169                        |me, output, _| {
3170                            me.events.push(Some(output));
3171                        },
3172                        |me, _| {
3173                            me.events.push(None);
3174                        },
3175                    )
3176                })
3177                .await;
3178
3179            app.read(|ctx| assert_eq!(handle.read(ctx).events, [Some(1), Some(2), Some(3), None]))
3180        });
3181    }
3182
3183    #[test]
3184    fn test_dispatch_action() {
3185        struct ViewA {
3186            id: usize,
3187        }
3188
3189        impl Entity for ViewA {
3190            type Event = ();
3191        }
3192
3193        impl View for ViewA {
3194            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3195                Empty::new().boxed()
3196            }
3197
3198            fn ui_name() -> &'static str {
3199                "View"
3200            }
3201        }
3202
3203        struct ViewB {
3204            id: usize,
3205        }
3206
3207        impl Entity for ViewB {
3208            type Event = ();
3209        }
3210
3211        impl View for ViewB {
3212            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3213                Empty::new().boxed()
3214            }
3215
3216            fn ui_name() -> &'static str {
3217                "View"
3218            }
3219        }
3220
3221        struct ActionArg {
3222            foo: String,
3223        }
3224
3225        App::test((), |app| {
3226            let actions = Rc::new(RefCell::new(Vec::new()));
3227
3228            let actions_clone = actions.clone();
3229            app.add_global_action("action", move |_: &ActionArg, _: &mut MutableAppContext| {
3230                actions_clone.borrow_mut().push("global a".to_string());
3231            });
3232
3233            let actions_clone = actions.clone();
3234            app.add_global_action("action", move |_: &ActionArg, _: &mut MutableAppContext| {
3235                actions_clone.borrow_mut().push("global b".to_string());
3236            });
3237
3238            let actions_clone = actions.clone();
3239            app.add_action("action", move |view: &mut ViewA, arg: &ActionArg, ctx| {
3240                assert_eq!(arg.foo, "bar");
3241                ctx.propagate_action();
3242                actions_clone.borrow_mut().push(format!("{} a", view.id));
3243            });
3244
3245            let actions_clone = actions.clone();
3246            app.add_action("action", move |view: &mut ViewA, _: &ActionArg, ctx| {
3247                if view.id != 1 {
3248                    ctx.propagate_action();
3249                }
3250                actions_clone.borrow_mut().push(format!("{} b", view.id));
3251            });
3252
3253            let actions_clone = actions.clone();
3254            app.add_action("action", move |view: &mut ViewB, _: &ActionArg, ctx| {
3255                ctx.propagate_action();
3256                actions_clone.borrow_mut().push(format!("{} c", view.id));
3257            });
3258
3259            let actions_clone = actions.clone();
3260            app.add_action("action", move |view: &mut ViewB, _: &ActionArg, ctx| {
3261                ctx.propagate_action();
3262                actions_clone.borrow_mut().push(format!("{} d", view.id));
3263            });
3264
3265            let (window_id, view_1) = app.add_window(|_| ViewA { id: 1 });
3266            let view_2 = app.add_view(window_id, |_| ViewB { id: 2 });
3267            let view_3 = app.add_view(window_id, |_| ViewA { id: 3 });
3268            let view_4 = app.add_view(window_id, |_| ViewB { id: 4 });
3269
3270            app.dispatch_action(
3271                window_id,
3272                vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
3273                "action",
3274                ActionArg { foo: "bar".into() },
3275            );
3276
3277            assert_eq!(
3278                *actions.borrow(),
3279                vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "1 b"]
3280            );
3281
3282            // Remove view_1, which doesn't propagate the action
3283            actions.borrow_mut().clear();
3284            app.dispatch_action(
3285                window_id,
3286                vec![view_2.id(), view_3.id(), view_4.id()],
3287                "action",
3288                ActionArg { foo: "bar".into() },
3289            );
3290
3291            assert_eq!(
3292                *actions.borrow(),
3293                vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "global b", "global a"]
3294            );
3295        })
3296    }
3297
3298    #[test]
3299    fn test_dispatch_keystroke() {
3300        use std::cell::Cell;
3301
3302        #[derive(Clone)]
3303        struct ActionArg {
3304            key: String,
3305        }
3306
3307        struct View {
3308            id: usize,
3309            keymap_context: keymap::Context,
3310        }
3311
3312        impl Entity for View {
3313            type Event = ();
3314        }
3315
3316        impl super::View for View {
3317            fn render<'a>(&self, _: &AppContext) -> ElementBox {
3318                Empty::new().boxed()
3319            }
3320
3321            fn ui_name() -> &'static str {
3322                "View"
3323            }
3324
3325            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
3326                self.keymap_context.clone()
3327            }
3328        }
3329
3330        impl View {
3331            fn new(id: usize) -> Self {
3332                View {
3333                    id,
3334                    keymap_context: keymap::Context::default(),
3335                }
3336            }
3337        }
3338
3339        App::test((), |app| {
3340            let mut view_1 = View::new(1);
3341            let mut view_2 = View::new(2);
3342            let mut view_3 = View::new(3);
3343            view_1.keymap_context.set.insert("a".into());
3344            view_2.keymap_context.set.insert("b".into());
3345            view_3.keymap_context.set.insert("c".into());
3346
3347            let (window_id, view_1) = app.add_window(|_| view_1);
3348            let view_2 = app.add_view(window_id, |_| view_2);
3349            let view_3 = app.add_view(window_id, |_| view_3);
3350
3351            // This keymap's only binding dispatches an action on view 2 because that view will have
3352            // "a" and "b" in its context, but not "c".
3353            let binding = keymap::Binding::new("a", "action", Some("a && b && !c"))
3354                .with_arg(ActionArg { key: "a".into() });
3355            app.add_bindings(vec![binding]);
3356
3357            let handled_action = Rc::new(Cell::new(false));
3358            let handled_action_clone = handled_action.clone();
3359            app.add_action("action", move |view: &mut View, arg: &ActionArg, _ctx| {
3360                handled_action_clone.set(true);
3361                assert_eq!(view.id, 2);
3362                assert_eq!(arg.key, "a");
3363            });
3364
3365            app.dispatch_keystroke(
3366                window_id,
3367                vec![view_1.id(), view_2.id(), view_3.id()],
3368                &Keystroke::parse("a").unwrap(),
3369            )
3370            .unwrap();
3371
3372            assert!(handled_action.get());
3373        });
3374    }
3375
3376    #[test]
3377    fn test_model_condition() {
3378        struct Counter(usize);
3379
3380        impl super::Entity for Counter {
3381            type Event = ();
3382        }
3383
3384        impl Counter {
3385            fn inc(&mut self, ctx: &mut ModelContext<Self>) {
3386                self.0 += 1;
3387                ctx.notify();
3388            }
3389        }
3390
3391        App::test_async((), |mut app| async move {
3392            let model = app.add_model(|_| Counter(0));
3393
3394            let condition1 = model.condition(&app, |model, _| model.0 == 2);
3395            let condition2 = model.condition(&app, |model, _| model.0 == 3);
3396            smol::pin!(condition1, condition2);
3397
3398            model.update(&mut app, |model, ctx| model.inc(ctx));
3399            assert_eq!(poll_once(&mut condition1).await, None);
3400            assert_eq!(poll_once(&mut condition2).await, None);
3401
3402            model.update(&mut app, |model, ctx| model.inc(ctx));
3403            assert_eq!(poll_once(&mut condition1).await, Some(()));
3404            assert_eq!(poll_once(&mut condition2).await, None);
3405
3406            model.update(&mut app, |model, ctx| model.inc(ctx));
3407            assert_eq!(poll_once(&mut condition2).await, Some(()));
3408
3409            // Broadcast channel should be removed if no conditions remain on next notification.
3410            model.update(&mut app, |_, ctx| ctx.notify());
3411            app.update(|ctx| assert!(ctx.async_observations.get(&model.id()).is_none()));
3412        });
3413    }
3414
3415    #[test]
3416    #[should_panic]
3417    fn test_model_condition_timeout() {
3418        struct Model;
3419
3420        impl super::Entity for Model {
3421            type Event = ();
3422        }
3423
3424        App::test_async((), |mut app| async move {
3425            let model = app.add_model(|_| Model);
3426            model.condition(&app, |_, _| false).await;
3427        });
3428    }
3429
3430    #[test]
3431    #[should_panic(expected = "model dropped with pending condition")]
3432    fn test_model_condition_panic_on_drop() {
3433        struct Model;
3434
3435        impl super::Entity for Model {
3436            type Event = ();
3437        }
3438
3439        App::test_async((), |mut app| async move {
3440            let model = app.add_model(|_| Model);
3441            let condition = model.condition(&app, |_, _| false);
3442            app.update(|_| drop(model));
3443            condition.await;
3444        });
3445    }
3446
3447    #[test]
3448    fn test_view_condition() {
3449        struct Counter(usize);
3450
3451        impl super::Entity for Counter {
3452            type Event = ();
3453        }
3454
3455        impl super::View for Counter {
3456            fn ui_name() -> &'static str {
3457                "test view"
3458            }
3459
3460            fn render(&self, _: &AppContext) -> ElementBox {
3461                Empty::new().boxed()
3462            }
3463        }
3464
3465        impl Counter {
3466            fn inc(&mut self, ctx: &mut ViewContext<Self>) {
3467                self.0 += 1;
3468                ctx.notify();
3469            }
3470        }
3471
3472        App::test_async((), |mut app| async move {
3473            let (_, view) = app.add_window(|_| Counter(0));
3474
3475            let condition1 = view.condition(&app, |view, _| view.0 == 2);
3476            let condition2 = view.condition(&app, |view, _| view.0 == 3);
3477            smol::pin!(condition1, condition2);
3478
3479            view.update(&mut app, |view, ctx| view.inc(ctx));
3480            assert_eq!(poll_once(&mut condition1).await, None);
3481            assert_eq!(poll_once(&mut condition2).await, None);
3482
3483            view.update(&mut app, |view, ctx| view.inc(ctx));
3484            assert_eq!(poll_once(&mut condition1).await, Some(()));
3485            assert_eq!(poll_once(&mut condition2).await, None);
3486
3487            view.update(&mut app, |view, ctx| view.inc(ctx));
3488            assert_eq!(poll_once(&mut condition2).await, Some(()));
3489
3490            // Broadcast channel should be removed if no conditions remain on next notification.
3491            view.update(&mut app, |_, ctx| ctx.notify());
3492            app.update(|ctx| assert!(ctx.async_observations.get(&view.id()).is_none()));
3493        });
3494    }
3495
3496    #[test]
3497    #[should_panic]
3498    fn test_view_condition_timeout() {
3499        struct View;
3500
3501        impl super::Entity for View {
3502            type Event = ();
3503        }
3504
3505        impl super::View for View {
3506            fn ui_name() -> &'static str {
3507                "test view"
3508            }
3509
3510            fn render(&self, _: &AppContext) -> ElementBox {
3511                Empty::new().boxed()
3512            }
3513        }
3514
3515        App::test_async((), |mut app| async move {
3516            let (_, view) = app.add_window(|_| View);
3517            view.condition(&app, |_, _| false).await;
3518        });
3519    }
3520
3521    #[test]
3522    #[should_panic(expected = "model dropped with pending condition")]
3523    fn test_view_condition_panic_on_drop() {
3524        struct View;
3525
3526        impl super::Entity for View {
3527            type Event = ();
3528        }
3529
3530        impl super::View for View {
3531            fn ui_name() -> &'static str {
3532                "test view"
3533            }
3534
3535            fn render(&self, _: &AppContext) -> ElementBox {
3536                Empty::new().boxed()
3537            }
3538        }
3539
3540        App::test_async((), |mut app| async move {
3541            let window_id = app.add_window(|_| View).0;
3542            let view = app.add_view(window_id, |_| View);
3543
3544            let condition = view.condition(&app, |_, _| false);
3545            app.update(|_| drop(view));
3546            condition.await;
3547        });
3548    }
3549
3550    // #[test]
3551    // fn test_ui_and_window_updates() {
3552    //     struct View {
3553    //         count: usize,
3554    //     }
3555
3556    //     impl Entity for View {
3557    //         type Event = ();
3558    //     }
3559
3560    //     impl super::View for View {
3561    //         fn render<'a>(&self, _: &AppContext) -> ElementBox {
3562    //             Empty::new().boxed()
3563    //         }
3564
3565    //         fn ui_name() -> &'static str {
3566    //             "View"
3567    //         }
3568    //     }
3569
3570    //     App::test(|app| async move {
3571    //         let (window_id, _) = app.add_window(|_| View { count: 3 });
3572    //         let view_1 = app.add_view(window_id, |_| View { count: 1 });
3573    //         let view_2 = app.add_view(window_id, |_| View { count: 2 });
3574
3575    //         // Ensure that registering for UI updates after mutating the app still gives us all the
3576    //         // updates.
3577    //         let ui_updates = Rc::new(RefCell::new(Vec::new()));
3578    //         let ui_updates_ = ui_updates.clone();
3579    //         app.on_ui_update(move |update, _| ui_updates_.borrow_mut().push(update));
3580
3581    //         assert_eq!(
3582    //             ui_updates.borrow_mut().drain(..).collect::<Vec<_>>(),
3583    //             vec![UiUpdate::OpenWindow {
3584    //                 window_id,
3585    //                 width: 1024.0,
3586    //                 height: 768.0,
3587    //             }]
3588    //         );
3589
3590    //         let window_invalidations = Rc::new(RefCell::new(Vec::new()));
3591    //         let window_invalidations_ = window_invalidations.clone();
3592    //         app.on_window_invalidated(window_id, move |update, _| {
3593    //             window_invalidations_.borrow_mut().push(update)
3594    //         });
3595
3596    //         let view_2_id = view_2.id();
3597    //         view_1.update(app, |view, ctx| {
3598    //             view.count = 7;
3599    //             ctx.notify();
3600    //             drop(view_2);
3601    //         });
3602
3603    //         let invalidation = window_invalidations.borrow_mut().drain(..).next().unwrap();
3604    //         assert_eq!(invalidation.updated.len(), 1);
3605    //         assert!(invalidation.updated.contains(&view_1.id()));
3606    //         assert_eq!(invalidation.removed, vec![view_2_id]);
3607
3608    //         let view_3 = view_1.update(app, |_, ctx| ctx.add_view(|_| View { count: 8 }));
3609
3610    //         let invalidation = window_invalidations.borrow_mut().drain(..).next().unwrap();
3611    //         assert_eq!(invalidation.updated.len(), 1);
3612    //         assert!(invalidation.updated.contains(&view_3.id()));
3613    //         assert!(invalidation.removed.is_empty());
3614
3615    //         view_3
3616    //             .update(app, |_, ctx| {
3617    //                 ctx.spawn_local(async { 9 }, |me, output, ctx| {
3618    //                     me.count = output;
3619    //                     ctx.notify();
3620    //                 })
3621    //             })
3622    //             .await;
3623
3624    //         let invalidation = window_invalidations.borrow_mut().drain(..).next().unwrap();
3625    //         assert_eq!(invalidation.updated.len(), 1);
3626    //         assert!(invalidation.updated.contains(&view_3.id()));
3627    //         assert!(invalidation.removed.is_empty());
3628    //     });
3629    // }
3630}