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