app.rs

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