app.rs

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