app.rs

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