app.rs

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