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