app.rs

   1pub mod action;
   2mod callback_collection;
   3
   4use crate::{
   5    elements::ElementBox,
   6    executor::{self, Task},
   7    geometry::rect::RectF,
   8    keymap::{self, Binding, Keystroke},
   9    platform::{self, KeyDownEvent, Platform, PromptLevel, WindowOptions},
  10    presenter::Presenter,
  11    util::post_inc,
  12    AssetCache, AssetSource, ClipboardItem, FontCache, InputHandler, MouseRegionId,
  13    PathPromptOptions, TextLayoutCache,
  14};
  15pub use action::*;
  16use anyhow::{anyhow, Context, Result};
  17use callback_collection::CallbackCollection;
  18use collections::{btree_map, hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque};
  19use keymap::MatchResult;
  20use lazy_static::lazy_static;
  21use parking_lot::Mutex;
  22use platform::Event;
  23use postage::oneshot;
  24use smallvec::SmallVec;
  25use smol::prelude::*;
  26use std::{
  27    any::{type_name, Any, TypeId},
  28    cell::RefCell,
  29    fmt::{self, Debug},
  30    hash::{Hash, Hasher},
  31    marker::PhantomData,
  32    mem,
  33    ops::{Deref, DerefMut, Range},
  34    path::{Path, PathBuf},
  35    pin::Pin,
  36    rc::{self, Rc},
  37    sync::{Arc, Weak},
  38    time::Duration,
  39};
  40
  41use self::callback_collection::Mapping;
  42
  43pub trait Entity: 'static {
  44    type Event;
  45
  46    fn release(&mut self, _: &mut MutableAppContext) {}
  47    fn app_will_quit(
  48        &mut self,
  49        _: &mut MutableAppContext,
  50    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
  51        None
  52    }
  53}
  54
  55pub trait View: Entity + Sized {
  56    fn ui_name() -> &'static str;
  57    fn render(&mut self, cx: &mut RenderContext<'_, Self>) -> ElementBox;
  58    fn on_focus(&mut self, _: &mut ViewContext<Self>) {}
  59    fn on_blur(&mut self, _: &mut ViewContext<Self>) {}
  60    fn keymap_context(&self, _: &AppContext) -> keymap::Context {
  61        Self::default_keymap_context()
  62    }
  63    fn default_keymap_context() -> keymap::Context {
  64        let mut cx = keymap::Context::default();
  65        cx.set.insert(Self::ui_name().into());
  66        cx
  67    }
  68    fn debug_json(&self, _: &AppContext) -> serde_json::Value {
  69        serde_json::Value::Null
  70    }
  71
  72    fn text_for_range(&self, _: Range<usize>, _: &AppContext) -> Option<String> {
  73        None
  74    }
  75    fn selected_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
  76        None
  77    }
  78    fn marked_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
  79        None
  80    }
  81    fn unmark_text(&mut self, _: &mut ViewContext<Self>) {}
  82    fn replace_text_in_range(
  83        &mut self,
  84        _: Option<Range<usize>>,
  85        _: &str,
  86        _: &mut ViewContext<Self>,
  87    ) {
  88    }
  89    fn replace_and_mark_text_in_range(
  90        &mut self,
  91        _: Option<Range<usize>>,
  92        _: &str,
  93        _: Option<Range<usize>>,
  94        _: &mut ViewContext<Self>,
  95    ) {
  96    }
  97}
  98
  99pub trait ReadModel {
 100    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T;
 101}
 102
 103pub trait ReadModelWith {
 104    fn read_model_with<E: Entity, T>(
 105        &self,
 106        handle: &ModelHandle<E>,
 107        read: &mut dyn FnMut(&E, &AppContext) -> T,
 108    ) -> T;
 109}
 110
 111pub trait UpdateModel {
 112    fn update_model<T: Entity, O>(
 113        &mut self,
 114        handle: &ModelHandle<T>,
 115        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
 116    ) -> O;
 117}
 118
 119pub trait UpgradeModelHandle {
 120    fn upgrade_model_handle<T: Entity>(
 121        &self,
 122        handle: &WeakModelHandle<T>,
 123    ) -> Option<ModelHandle<T>>;
 124
 125    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool;
 126
 127    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle>;
 128}
 129
 130pub trait UpgradeViewHandle {
 131    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>>;
 132
 133    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle>;
 134}
 135
 136pub trait ReadView {
 137    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T;
 138}
 139
 140pub trait ReadViewWith {
 141    fn read_view_with<V, T>(
 142        &self,
 143        handle: &ViewHandle<V>,
 144        read: &mut dyn FnMut(&V, &AppContext) -> T,
 145    ) -> T
 146    where
 147        V: View;
 148}
 149
 150pub trait UpdateView {
 151    fn update_view<T, S>(
 152        &mut self,
 153        handle: &ViewHandle<T>,
 154        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 155    ) -> S
 156    where
 157        T: View;
 158}
 159
 160pub struct Menu<'a> {
 161    pub name: &'a str,
 162    pub items: Vec<MenuItem<'a>>,
 163}
 164
 165pub enum MenuItem<'a> {
 166    Separator,
 167    Submenu(Menu<'a>),
 168    Action {
 169        name: &'a str,
 170        action: Box<dyn Action>,
 171    },
 172}
 173
 174#[derive(Clone)]
 175pub struct App(Rc<RefCell<MutableAppContext>>);
 176
 177#[derive(Clone)]
 178pub struct AsyncAppContext(Rc<RefCell<MutableAppContext>>);
 179
 180#[cfg(any(test, feature = "test-support"))]
 181pub struct TestAppContext {
 182    cx: Rc<RefCell<MutableAppContext>>,
 183    foreground_platform: Rc<platform::test::ForegroundPlatform>,
 184    condition_duration: Option<Duration>,
 185}
 186
 187pub struct WindowInputHandler {
 188    app: Rc<RefCell<MutableAppContext>>,
 189    window_id: usize,
 190}
 191
 192impl App {
 193    pub fn new(asset_source: impl AssetSource) -> Result<Self> {
 194        let platform = platform::current::platform();
 195        let foreground_platform = platform::current::foreground_platform();
 196        let foreground = Rc::new(executor::Foreground::platform(platform.dispatcher())?);
 197        let app = Self(Rc::new(RefCell::new(MutableAppContext::new(
 198            foreground,
 199            Arc::new(executor::Background::new()),
 200            platform.clone(),
 201            foreground_platform.clone(),
 202            Arc::new(FontCache::new(platform.fonts())),
 203            Default::default(),
 204            asset_source,
 205        ))));
 206
 207        foreground_platform.on_quit(Box::new({
 208            let cx = app.0.clone();
 209            move || {
 210                cx.borrow_mut().quit();
 211            }
 212        }));
 213        foreground_platform.on_will_open_menu(Box::new({
 214            let cx = app.0.clone();
 215            move || {
 216                let mut cx = cx.borrow_mut();
 217                cx.keystroke_matcher.clear_pending();
 218            }
 219        }));
 220        foreground_platform.on_validate_menu_command(Box::new({
 221            let cx = app.0.clone();
 222            move |action| {
 223                let cx = cx.borrow_mut();
 224                !cx.keystroke_matcher.has_pending_keystrokes() && cx.is_action_available(action)
 225            }
 226        }));
 227        foreground_platform.on_menu_command(Box::new({
 228            let cx = app.0.clone();
 229            move |action| {
 230                let mut cx = cx.borrow_mut();
 231                if let Some(key_window_id) = cx.cx.platform.key_window_id() {
 232                    if let Some((presenter, _)) =
 233                        cx.presenters_and_platform_windows.get(&key_window_id)
 234                    {
 235                        let presenter = presenter.clone();
 236                        let path = presenter.borrow().dispatch_path(cx.as_ref());
 237                        cx.dispatch_action_any(key_window_id, &path, action);
 238                    } else {
 239                        cx.dispatch_global_action_any(action);
 240                    }
 241                } else {
 242                    cx.dispatch_global_action_any(action);
 243                }
 244            }
 245        }));
 246
 247        app.0.borrow_mut().weak_self = Some(Rc::downgrade(&app.0));
 248        Ok(app)
 249    }
 250
 251    pub fn background(&self) -> Arc<executor::Background> {
 252        self.0.borrow().background().clone()
 253    }
 254
 255    pub fn on_become_active<F>(self, mut callback: F) -> Self
 256    where
 257        F: 'static + FnMut(&mut MutableAppContext),
 258    {
 259        let cx = self.0.clone();
 260        self.0
 261            .borrow_mut()
 262            .foreground_platform
 263            .on_become_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 264        self
 265    }
 266
 267    pub fn on_resign_active<F>(self, mut callback: F) -> Self
 268    where
 269        F: 'static + FnMut(&mut MutableAppContext),
 270    {
 271        let cx = self.0.clone();
 272        self.0
 273            .borrow_mut()
 274            .foreground_platform
 275            .on_resign_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 276        self
 277    }
 278
 279    pub fn on_quit<F>(&mut self, mut callback: F) -> &mut Self
 280    where
 281        F: 'static + FnMut(&mut MutableAppContext),
 282    {
 283        let cx = self.0.clone();
 284        self.0
 285            .borrow_mut()
 286            .foreground_platform
 287            .on_quit(Box::new(move || callback(&mut *cx.borrow_mut())));
 288        self
 289    }
 290
 291    pub fn on_event<F>(&mut self, mut callback: F) -> &mut Self
 292    where
 293        F: 'static + FnMut(Event, &mut MutableAppContext) -> bool,
 294    {
 295        let cx = self.0.clone();
 296        self.0
 297            .borrow_mut()
 298            .foreground_platform
 299            .on_event(Box::new(move |event| {
 300                callback(event, &mut *cx.borrow_mut())
 301            }));
 302        self
 303    }
 304
 305    pub fn on_open_urls<F>(&mut self, mut callback: F) -> &mut Self
 306    where
 307        F: 'static + FnMut(Vec<String>, &mut MutableAppContext),
 308    {
 309        let cx = self.0.clone();
 310        self.0
 311            .borrow_mut()
 312            .foreground_platform
 313            .on_open_urls(Box::new(move |paths| {
 314                callback(paths, &mut *cx.borrow_mut())
 315            }));
 316        self
 317    }
 318
 319    pub fn run<F>(self, on_finish_launching: F)
 320    where
 321        F: 'static + FnOnce(&mut MutableAppContext),
 322    {
 323        let platform = self.0.borrow().foreground_platform.clone();
 324        platform.run(Box::new(move || {
 325            let mut cx = self.0.borrow_mut();
 326            let cx = &mut *cx;
 327            crate::views::init(cx);
 328            on_finish_launching(cx);
 329        }))
 330    }
 331
 332    pub fn platform(&self) -> Arc<dyn Platform> {
 333        self.0.borrow().platform()
 334    }
 335
 336    pub fn font_cache(&self) -> Arc<FontCache> {
 337        self.0.borrow().cx.font_cache.clone()
 338    }
 339
 340    fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 341        let mut state = self.0.borrow_mut();
 342        let result = state.update(callback);
 343        state.pending_notifications.clear();
 344        result
 345    }
 346}
 347
 348impl WindowInputHandler {
 349    fn read_focused_view<T, F>(&self, f: F) -> Option<T>
 350    where
 351        F: FnOnce(&dyn AnyView, &AppContext) -> T,
 352    {
 353        let app = self.app.borrow();
 354        let view_id = app.focused_view_id(self.window_id)?;
 355        let view = app.cx.views.get(&(self.window_id, view_id))?;
 356        let result = f(view.as_ref(), &app);
 357        Some(result)
 358    }
 359
 360    fn update_focused_view<T, F>(&mut self, f: F) -> Option<T>
 361    where
 362        F: FnOnce(usize, usize, &mut dyn AnyView, &mut MutableAppContext) -> T,
 363    {
 364        let mut app = self.app.borrow_mut();
 365        app.update(|app| {
 366            let view_id = app.focused_view_id(self.window_id)?;
 367            let mut view = app.cx.views.remove(&(self.window_id, view_id))?;
 368            let result = f(self.window_id, view_id, view.as_mut(), &mut *app);
 369            app.cx.views.insert((self.window_id, view_id), view);
 370            Some(result)
 371        })
 372    }
 373}
 374
 375impl InputHandler for WindowInputHandler {
 376    fn text_for_range(&self, range: Range<usize>) -> Option<String> {
 377        self.read_focused_view(|view, cx| view.text_for_range(range.clone(), cx))
 378            .flatten()
 379    }
 380
 381    fn selected_text_range(&self) -> Option<Range<usize>> {
 382        self.read_focused_view(|view, cx| view.selected_text_range(cx))
 383            .flatten()
 384    }
 385
 386    fn replace_text_in_range(&mut self, range: Option<Range<usize>>, text: &str) {
 387        self.update_focused_view(|window_id, view_id, view, cx| {
 388            view.replace_text_in_range(range, text, cx, window_id, view_id);
 389        });
 390    }
 391
 392    fn marked_text_range(&self) -> Option<Range<usize>> {
 393        self.read_focused_view(|view, cx| view.marked_text_range(cx))
 394            .flatten()
 395    }
 396
 397    fn unmark_text(&mut self) {
 398        self.update_focused_view(|window_id, view_id, view, cx| {
 399            view.unmark_text(cx, window_id, view_id);
 400        });
 401    }
 402
 403    fn replace_and_mark_text_in_range(
 404        &mut self,
 405        range: Option<Range<usize>>,
 406        new_text: &str,
 407        new_selected_range: Option<Range<usize>>,
 408    ) {
 409        self.update_focused_view(|window_id, view_id, view, cx| {
 410            view.replace_and_mark_text_in_range(
 411                range,
 412                new_text,
 413                new_selected_range,
 414                cx,
 415                window_id,
 416                view_id,
 417            );
 418        });
 419    }
 420
 421    fn rect_for_range(&self, range_utf16: Range<usize>) -> Option<RectF> {
 422        let app = self.app.borrow();
 423        let (presenter, _) = app.presenters_and_platform_windows.get(&self.window_id)?;
 424        let presenter = presenter.borrow();
 425        presenter.rect_for_text_range(range_utf16, &app)
 426    }
 427}
 428
 429#[cfg(any(test, feature = "test-support"))]
 430impl TestAppContext {
 431    pub fn new(
 432        foreground_platform: Rc<platform::test::ForegroundPlatform>,
 433        platform: Arc<dyn Platform>,
 434        foreground: Rc<executor::Foreground>,
 435        background: Arc<executor::Background>,
 436        font_cache: Arc<FontCache>,
 437        leak_detector: Arc<Mutex<LeakDetector>>,
 438        first_entity_id: usize,
 439    ) -> Self {
 440        let mut cx = MutableAppContext::new(
 441            foreground.clone(),
 442            background,
 443            platform,
 444            foreground_platform.clone(),
 445            font_cache,
 446            RefCounts {
 447                #[cfg(any(test, feature = "test-support"))]
 448                leak_detector,
 449                ..Default::default()
 450            },
 451            (),
 452        );
 453        cx.next_entity_id = first_entity_id;
 454        let cx = TestAppContext {
 455            cx: Rc::new(RefCell::new(cx)),
 456            foreground_platform,
 457            condition_duration: None,
 458        };
 459        cx.cx.borrow_mut().weak_self = Some(Rc::downgrade(&cx.cx));
 460        cx
 461    }
 462
 463    pub fn dispatch_action<A: Action>(&self, window_id: usize, action: A) {
 464        let mut cx = self.cx.borrow_mut();
 465        let dispatch_path = cx
 466            .presenters_and_platform_windows
 467            .get(&window_id)
 468            .unwrap()
 469            .0
 470            .borrow()
 471            .dispatch_path(cx.as_ref());
 472
 473        cx.dispatch_action_any(window_id, &dispatch_path, &action);
 474    }
 475
 476    pub fn dispatch_global_action<A: Action>(&self, action: A) {
 477        self.cx.borrow_mut().dispatch_global_action(action);
 478    }
 479
 480    pub fn dispatch_keystroke(&mut self, window_id: usize, keystroke: Keystroke, is_held: bool) {
 481        let handled = self.cx.borrow_mut().update(|cx| {
 482            let presenter = cx
 483                .presenters_and_platform_windows
 484                .get(&window_id)
 485                .unwrap()
 486                .0
 487                .clone();
 488            let dispatch_path = presenter.borrow().dispatch_path(cx.as_ref());
 489
 490            if cx.dispatch_keystroke(window_id, dispatch_path, &keystroke) {
 491                return true;
 492            }
 493            if presenter.borrow_mut().dispatch_event(
 494                Event::KeyDown(KeyDownEvent {
 495                    keystroke: keystroke.clone(),
 496                    is_held,
 497                }),
 498                cx,
 499            ) {
 500                return true;
 501            }
 502
 503            false
 504        });
 505
 506        if !handled && !keystroke.cmd && !keystroke.ctrl {
 507            WindowInputHandler {
 508                app: self.cx.clone(),
 509                window_id,
 510            }
 511            .replace_text_in_range(None, &keystroke.key)
 512        }
 513    }
 514
 515    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 516    where
 517        T: Entity,
 518        F: FnOnce(&mut ModelContext<T>) -> T,
 519    {
 520        self.cx.borrow_mut().add_model(build_model)
 521    }
 522
 523    pub fn add_window<T, F>(&mut self, build_root_view: F) -> (usize, ViewHandle<T>)
 524    where
 525        T: View,
 526        F: FnOnce(&mut ViewContext<T>) -> T,
 527    {
 528        let (window_id, view) = self
 529            .cx
 530            .borrow_mut()
 531            .add_window(Default::default(), build_root_view);
 532        self.simulate_window_activation(Some(window_id));
 533        (window_id, view)
 534    }
 535
 536    pub fn window_ids(&self) -> Vec<usize> {
 537        self.cx.borrow().window_ids().collect()
 538    }
 539
 540    pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
 541        self.cx.borrow().root_view(window_id)
 542    }
 543
 544    pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
 545    where
 546        T: View,
 547        F: FnOnce(&mut ViewContext<T>) -> T,
 548    {
 549        self.cx.borrow_mut().add_view(window_id, build_view)
 550    }
 551
 552    pub fn add_option_view<T, F>(
 553        &mut self,
 554        window_id: usize,
 555        build_view: F,
 556    ) -> Option<ViewHandle<T>>
 557    where
 558        T: View,
 559        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
 560    {
 561        self.cx.borrow_mut().add_option_view(window_id, build_view)
 562    }
 563
 564    pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
 565        callback(self.cx.borrow().as_ref())
 566    }
 567
 568    pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 569        let mut state = self.cx.borrow_mut();
 570        // Don't increment pending flushes in order for effects to be flushed before the callback
 571        // completes, which is helpful in tests.
 572        let result = callback(&mut *state);
 573        // Flush effects after the callback just in case there are any. This can happen in edge
 574        // cases such as the closure dropping handles.
 575        state.flush_effects();
 576        result
 577    }
 578
 579    pub fn render<F, V, T>(&mut self, handle: &ViewHandle<V>, f: F) -> T
 580    where
 581        F: FnOnce(&mut V, &mut RenderContext<V>) -> T,
 582        V: View,
 583    {
 584        handle.update(&mut *self.cx.borrow_mut(), |view, cx| {
 585            let mut render_cx = RenderContext {
 586                app: cx,
 587                window_id: handle.window_id(),
 588                view_id: handle.id(),
 589                view_type: PhantomData,
 590                titlebar_height: 0.,
 591                hovered_region_ids: Default::default(),
 592                clicked_region_id: None,
 593                right_clicked_region_id: None,
 594                refreshing: false,
 595            };
 596            f(view, &mut render_cx)
 597        })
 598    }
 599
 600    pub fn to_async(&self) -> AsyncAppContext {
 601        AsyncAppContext(self.cx.clone())
 602    }
 603
 604    pub fn font_cache(&self) -> Arc<FontCache> {
 605        self.cx.borrow().cx.font_cache.clone()
 606    }
 607
 608    pub fn foreground_platform(&self) -> Rc<platform::test::ForegroundPlatform> {
 609        self.foreground_platform.clone()
 610    }
 611
 612    pub fn platform(&self) -> Arc<dyn platform::Platform> {
 613        self.cx.borrow().cx.platform.clone()
 614    }
 615
 616    pub fn foreground(&self) -> Rc<executor::Foreground> {
 617        self.cx.borrow().foreground().clone()
 618    }
 619
 620    pub fn background(&self) -> Arc<executor::Background> {
 621        self.cx.borrow().background().clone()
 622    }
 623
 624    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
 625    where
 626        F: FnOnce(AsyncAppContext) -> Fut,
 627        Fut: 'static + Future<Output = T>,
 628        T: 'static,
 629    {
 630        let foreground = self.foreground();
 631        let future = f(self.to_async());
 632        let cx = self.to_async();
 633        foreground.spawn(async move {
 634            let result = future.await;
 635            cx.0.borrow_mut().flush_effects();
 636            result
 637        })
 638    }
 639
 640    pub fn simulate_new_path_selection(&self, result: impl FnOnce(PathBuf) -> Option<PathBuf>) {
 641        self.foreground_platform.simulate_new_path_selection(result);
 642    }
 643
 644    pub fn did_prompt_for_new_path(&self) -> bool {
 645        self.foreground_platform.as_ref().did_prompt_for_new_path()
 646    }
 647
 648    pub fn simulate_prompt_answer(&self, window_id: usize, answer: usize) {
 649        use postage::prelude::Sink as _;
 650
 651        let mut done_tx = self
 652            .window_mut(window_id)
 653            .pending_prompts
 654            .borrow_mut()
 655            .pop_front()
 656            .expect("prompt was not called");
 657        let _ = done_tx.try_send(answer);
 658    }
 659
 660    pub fn has_pending_prompt(&self, window_id: usize) -> bool {
 661        let window = self.window_mut(window_id);
 662        let prompts = window.pending_prompts.borrow_mut();
 663        !prompts.is_empty()
 664    }
 665
 666    pub fn current_window_title(&self, window_id: usize) -> Option<String> {
 667        self.window_mut(window_id).title.clone()
 668    }
 669
 670    pub fn simulate_window_close(&self, window_id: usize) -> bool {
 671        let handler = self.window_mut(window_id).should_close_handler.take();
 672        if let Some(mut handler) = handler {
 673            let should_close = handler();
 674            self.window_mut(window_id).should_close_handler = Some(handler);
 675            should_close
 676        } else {
 677            false
 678        }
 679    }
 680
 681    pub fn simulate_window_activation(&self, to_activate: Option<usize>) {
 682        let mut handlers = BTreeMap::new();
 683        {
 684            let mut cx = self.cx.borrow_mut();
 685            for (window_id, (_, window)) in &mut cx.presenters_and_platform_windows {
 686                let window = window
 687                    .as_any_mut()
 688                    .downcast_mut::<platform::test::Window>()
 689                    .unwrap();
 690                handlers.insert(
 691                    *window_id,
 692                    mem::take(&mut window.active_status_change_handlers),
 693                );
 694            }
 695        };
 696        let mut handlers = handlers.into_iter().collect::<Vec<_>>();
 697        handlers.sort_unstable_by_key(|(window_id, _)| Some(*window_id) == to_activate);
 698
 699        for (window_id, mut window_handlers) in handlers {
 700            for window_handler in &mut window_handlers {
 701                window_handler(Some(window_id) == to_activate);
 702            }
 703
 704            self.window_mut(window_id)
 705                .active_status_change_handlers
 706                .extend(window_handlers);
 707        }
 708    }
 709
 710    pub fn is_window_edited(&self, window_id: usize) -> bool {
 711        self.window_mut(window_id).edited
 712    }
 713
 714    pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
 715        self.cx.borrow().leak_detector()
 716    }
 717
 718    pub fn assert_dropped(&self, handle: impl WeakHandle) {
 719        self.cx
 720            .borrow()
 721            .leak_detector()
 722            .lock()
 723            .assert_dropped(handle.id())
 724    }
 725
 726    fn window_mut(&self, window_id: usize) -> std::cell::RefMut<platform::test::Window> {
 727        std::cell::RefMut::map(self.cx.borrow_mut(), |state| {
 728            let (_, window) = state
 729                .presenters_and_platform_windows
 730                .get_mut(&window_id)
 731                .unwrap();
 732            let test_window = window
 733                .as_any_mut()
 734                .downcast_mut::<platform::test::Window>()
 735                .unwrap();
 736            test_window
 737        })
 738    }
 739
 740    pub fn set_condition_duration(&mut self, duration: Option<Duration>) {
 741        self.condition_duration = duration;
 742    }
 743
 744    pub fn condition_duration(&self) -> Duration {
 745        self.condition_duration.unwrap_or_else(|| {
 746            if std::env::var("CI").is_ok() {
 747                Duration::from_secs(2)
 748            } else {
 749                Duration::from_millis(500)
 750            }
 751        })
 752    }
 753
 754    pub fn assert_clipboard_content(&mut self, expected_content: Option<&str>) {
 755        self.update(|cx| {
 756            let actual_content = cx.read_from_clipboard().map(|item| item.text().to_owned());
 757            let expected_content = expected_content.map(|content| content.to_owned());
 758            assert_eq!(actual_content, expected_content);
 759        })
 760    }
 761}
 762
 763impl AsyncAppContext {
 764    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
 765    where
 766        F: FnOnce(AsyncAppContext) -> Fut,
 767        Fut: 'static + Future<Output = T>,
 768        T: 'static,
 769    {
 770        self.0.borrow().foreground.spawn(f(self.clone()))
 771    }
 772
 773    pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
 774        callback(self.0.borrow().as_ref())
 775    }
 776
 777    pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 778        self.0.borrow_mut().update(callback)
 779    }
 780
 781    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 782    where
 783        T: Entity,
 784        F: FnOnce(&mut ModelContext<T>) -> T,
 785    {
 786        self.update(|cx| cx.add_model(build_model))
 787    }
 788
 789    pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
 790    where
 791        T: View,
 792        F: FnOnce(&mut ViewContext<T>) -> T,
 793    {
 794        self.update(|cx| cx.add_view(window_id, build_view))
 795    }
 796
 797    pub fn add_window<T, F>(
 798        &mut self,
 799        window_options: WindowOptions,
 800        build_root_view: F,
 801    ) -> (usize, ViewHandle<T>)
 802    where
 803        T: View,
 804        F: FnOnce(&mut ViewContext<T>) -> T,
 805    {
 806        self.update(|cx| cx.add_window(window_options, build_root_view))
 807    }
 808
 809    pub fn platform(&self) -> Arc<dyn Platform> {
 810        self.0.borrow().platform()
 811    }
 812
 813    pub fn foreground(&self) -> Rc<executor::Foreground> {
 814        self.0.borrow().foreground.clone()
 815    }
 816
 817    pub fn background(&self) -> Arc<executor::Background> {
 818        self.0.borrow().cx.background.clone()
 819    }
 820}
 821
 822impl UpdateModel for AsyncAppContext {
 823    fn update_model<E: Entity, O>(
 824        &mut self,
 825        handle: &ModelHandle<E>,
 826        update: &mut dyn FnMut(&mut E, &mut ModelContext<E>) -> O,
 827    ) -> O {
 828        self.0.borrow_mut().update_model(handle, update)
 829    }
 830}
 831
 832impl UpgradeModelHandle for AsyncAppContext {
 833    fn upgrade_model_handle<T: Entity>(
 834        &self,
 835        handle: &WeakModelHandle<T>,
 836    ) -> Option<ModelHandle<T>> {
 837        self.0.borrow().upgrade_model_handle(handle)
 838    }
 839
 840    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
 841        self.0.borrow().model_handle_is_upgradable(handle)
 842    }
 843
 844    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
 845        self.0.borrow().upgrade_any_model_handle(handle)
 846    }
 847}
 848
 849impl UpgradeViewHandle for AsyncAppContext {
 850    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
 851        self.0.borrow_mut().upgrade_view_handle(handle)
 852    }
 853
 854    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
 855        self.0.borrow_mut().upgrade_any_view_handle(handle)
 856    }
 857}
 858
 859impl ReadModelWith for AsyncAppContext {
 860    fn read_model_with<E: Entity, T>(
 861        &self,
 862        handle: &ModelHandle<E>,
 863        read: &mut dyn FnMut(&E, &AppContext) -> T,
 864    ) -> T {
 865        let cx = self.0.borrow();
 866        let cx = cx.as_ref();
 867        read(handle.read(cx), cx)
 868    }
 869}
 870
 871impl UpdateView for AsyncAppContext {
 872    fn update_view<T, S>(
 873        &mut self,
 874        handle: &ViewHandle<T>,
 875        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 876    ) -> S
 877    where
 878        T: View,
 879    {
 880        self.0.borrow_mut().update_view(handle, update)
 881    }
 882}
 883
 884impl ReadViewWith for AsyncAppContext {
 885    fn read_view_with<V, T>(
 886        &self,
 887        handle: &ViewHandle<V>,
 888        read: &mut dyn FnMut(&V, &AppContext) -> T,
 889    ) -> T
 890    where
 891        V: View,
 892    {
 893        let cx = self.0.borrow();
 894        let cx = cx.as_ref();
 895        read(handle.read(cx), cx)
 896    }
 897}
 898
 899#[cfg(any(test, feature = "test-support"))]
 900impl UpdateModel for TestAppContext {
 901    fn update_model<T: Entity, O>(
 902        &mut self,
 903        handle: &ModelHandle<T>,
 904        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
 905    ) -> O {
 906        self.cx.borrow_mut().update_model(handle, update)
 907    }
 908}
 909
 910#[cfg(any(test, feature = "test-support"))]
 911impl ReadModelWith for TestAppContext {
 912    fn read_model_with<E: Entity, T>(
 913        &self,
 914        handle: &ModelHandle<E>,
 915        read: &mut dyn FnMut(&E, &AppContext) -> T,
 916    ) -> T {
 917        let cx = self.cx.borrow();
 918        let cx = cx.as_ref();
 919        read(handle.read(cx), cx)
 920    }
 921}
 922
 923#[cfg(any(test, feature = "test-support"))]
 924impl UpdateView for TestAppContext {
 925    fn update_view<T, S>(
 926        &mut self,
 927        handle: &ViewHandle<T>,
 928        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 929    ) -> S
 930    where
 931        T: View,
 932    {
 933        self.cx.borrow_mut().update_view(handle, update)
 934    }
 935}
 936
 937#[cfg(any(test, feature = "test-support"))]
 938impl ReadViewWith for TestAppContext {
 939    fn read_view_with<V, T>(
 940        &self,
 941        handle: &ViewHandle<V>,
 942        read: &mut dyn FnMut(&V, &AppContext) -> T,
 943    ) -> T
 944    where
 945        V: View,
 946    {
 947        let cx = self.cx.borrow();
 948        let cx = cx.as_ref();
 949        read(handle.read(cx), cx)
 950    }
 951}
 952
 953type ActionCallback =
 954    dyn FnMut(&mut dyn AnyView, &dyn Action, &mut MutableAppContext, usize, usize);
 955type GlobalActionCallback = dyn FnMut(&dyn Action, &mut MutableAppContext);
 956
 957type SubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut MutableAppContext) -> bool>;
 958type GlobalSubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut MutableAppContext)>;
 959type ObservationCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>;
 960type FocusObservationCallback = Box<dyn FnMut(bool, &mut MutableAppContext) -> bool>;
 961type GlobalObservationCallback = Box<dyn FnMut(&mut MutableAppContext)>;
 962type ReleaseObservationCallback = Box<dyn FnOnce(&dyn Any, &mut MutableAppContext)>;
 963type ActionObservationCallback = Box<dyn FnMut(TypeId, &mut MutableAppContext)>;
 964type WindowActivationCallback = Box<dyn FnMut(bool, &mut MutableAppContext) -> bool>;
 965type WindowFullscreenCallback = Box<dyn FnMut(bool, &mut MutableAppContext) -> bool>;
 966type DeserializeActionCallback = fn(json: &str) -> anyhow::Result<Box<dyn Action>>;
 967type WindowShouldCloseSubscriptionCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>;
 968
 969pub struct MutableAppContext {
 970    weak_self: Option<rc::Weak<RefCell<Self>>>,
 971    foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 972    assets: Arc<AssetCache>,
 973    cx: AppContext,
 974    action_deserializers: HashMap<&'static str, (TypeId, DeserializeActionCallback)>,
 975    capture_actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 976    actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 977    global_actions: HashMap<TypeId, Box<GlobalActionCallback>>,
 978    keystroke_matcher: keymap::Matcher,
 979    next_entity_id: usize,
 980    next_window_id: usize,
 981    next_subscription_id: usize,
 982    frame_count: usize,
 983
 984    focus_observations: CallbackCollection<usize, FocusObservationCallback>,
 985    global_subscriptions: CallbackCollection<TypeId, GlobalSubscriptionCallback>,
 986    global_observations: CallbackCollection<TypeId, GlobalObservationCallback>,
 987    subscriptions: CallbackCollection<usize, SubscriptionCallback>,
 988    observations: CallbackCollection<usize, ObservationCallback>,
 989    window_activation_observations: CallbackCollection<usize, WindowActivationCallback>,
 990    window_fullscreen_observations: CallbackCollection<usize, WindowFullscreenCallback>,
 991
 992    release_observations: Arc<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>,
 993    action_dispatch_observations: Arc<Mutex<BTreeMap<usize, ActionObservationCallback>>>,
 994
 995    presenters_and_platform_windows:
 996        HashMap<usize, (Rc<RefCell<Presenter>>, Box<dyn platform::Window>)>,
 997    foreground: Rc<executor::Foreground>,
 998    pending_effects: VecDeque<Effect>,
 999    pending_focus_index: Option<usize>,
1000    pending_notifications: HashSet<usize>,
1001    pending_global_notifications: HashSet<TypeId>,
1002    pending_flushes: usize,
1003    flushing_effects: bool,
1004    halt_action_dispatch: bool,
1005}
1006
1007impl MutableAppContext {
1008    fn new(
1009        foreground: Rc<executor::Foreground>,
1010        background: Arc<executor::Background>,
1011        platform: Arc<dyn platform::Platform>,
1012        foreground_platform: Rc<dyn platform::ForegroundPlatform>,
1013        font_cache: Arc<FontCache>,
1014        ref_counts: RefCounts,
1015        asset_source: impl AssetSource,
1016    ) -> Self {
1017        Self {
1018            weak_self: None,
1019            foreground_platform,
1020            assets: Arc::new(AssetCache::new(asset_source)),
1021            cx: AppContext {
1022                models: Default::default(),
1023                views: Default::default(),
1024                windows: Default::default(),
1025                globals: Default::default(),
1026                element_states: Default::default(),
1027                ref_counts: Arc::new(Mutex::new(ref_counts)),
1028                background,
1029                font_cache,
1030                platform,
1031            },
1032            action_deserializers: Default::default(),
1033            capture_actions: Default::default(),
1034            actions: Default::default(),
1035            global_actions: Default::default(),
1036            keystroke_matcher: keymap::Matcher::default(),
1037            next_entity_id: 0,
1038            next_window_id: 0,
1039            next_subscription_id: 0,
1040            frame_count: 0,
1041            subscriptions: Default::default(),
1042            global_subscriptions: Default::default(),
1043            observations: Default::default(),
1044            focus_observations: Default::default(),
1045            release_observations: Default::default(),
1046            global_observations: Default::default(),
1047            window_activation_observations: Default::default(),
1048            window_fullscreen_observations: Default::default(),
1049            action_dispatch_observations: Default::default(),
1050            presenters_and_platform_windows: Default::default(),
1051            foreground,
1052            pending_effects: VecDeque::new(),
1053            pending_focus_index: None,
1054            pending_notifications: Default::default(),
1055            pending_global_notifications: Default::default(),
1056            pending_flushes: 0,
1057            flushing_effects: false,
1058            halt_action_dispatch: false,
1059        }
1060    }
1061
1062    pub fn upgrade(&self) -> App {
1063        App(self.weak_self.as_ref().unwrap().upgrade().unwrap())
1064    }
1065
1066    pub fn quit(&mut self) {
1067        let mut futures = Vec::new();
1068        for model_id in self.cx.models.keys().copied().collect::<Vec<_>>() {
1069            let mut model = self.cx.models.remove(&model_id).unwrap();
1070            futures.extend(model.app_will_quit(self));
1071            self.cx.models.insert(model_id, model);
1072        }
1073
1074        for view_id in self.cx.views.keys().copied().collect::<Vec<_>>() {
1075            let mut view = self.cx.views.remove(&view_id).unwrap();
1076            futures.extend(view.app_will_quit(self));
1077            self.cx.views.insert(view_id, view);
1078        }
1079
1080        self.remove_all_windows();
1081
1082        let futures = futures::future::join_all(futures);
1083        if self
1084            .background
1085            .block_with_timeout(Duration::from_millis(100), futures)
1086            .is_err()
1087        {
1088            log::error!("timed out waiting on app_will_quit");
1089        }
1090    }
1091
1092    pub fn remove_all_windows(&mut self) {
1093        for (window_id, _) in self.cx.windows.drain() {
1094            self.presenters_and_platform_windows.remove(&window_id);
1095        }
1096        self.flush_effects();
1097    }
1098
1099    pub fn platform(&self) -> Arc<dyn platform::Platform> {
1100        self.cx.platform.clone()
1101    }
1102
1103    pub fn font_cache(&self) -> &Arc<FontCache> {
1104        &self.cx.font_cache
1105    }
1106
1107    pub fn foreground(&self) -> &Rc<executor::Foreground> {
1108        &self.foreground
1109    }
1110
1111    pub fn background(&self) -> &Arc<executor::Background> {
1112        &self.cx.background
1113    }
1114
1115    pub fn debug_elements(&self, window_id: usize) -> Option<crate::json::Value> {
1116        self.presenters_and_platform_windows
1117            .get(&window_id)
1118            .and_then(|(presenter, _)| presenter.borrow().debug_elements(self))
1119    }
1120
1121    pub fn deserialize_action(
1122        &self,
1123        name: &str,
1124        argument: Option<&str>,
1125    ) -> Result<Box<dyn Action>> {
1126        let callback = self
1127            .action_deserializers
1128            .get(name)
1129            .ok_or_else(|| anyhow!("unknown action {}", name))?
1130            .1;
1131        callback(argument.unwrap_or("{}"))
1132            .with_context(|| format!("invalid data for action {}", name))
1133    }
1134
1135    pub fn add_action<A, V, F>(&mut self, handler: F)
1136    where
1137        A: Action,
1138        V: View,
1139        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
1140    {
1141        self.add_action_internal(handler, false)
1142    }
1143
1144    pub fn capture_action<A, V, F>(&mut self, handler: F)
1145    where
1146        A: Action,
1147        V: View,
1148        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
1149    {
1150        self.add_action_internal(handler, true)
1151    }
1152
1153    fn add_action_internal<A, V, F>(&mut self, mut handler: F, capture: bool)
1154    where
1155        A: Action,
1156        V: View,
1157        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
1158    {
1159        let handler = Box::new(
1160            move |view: &mut dyn AnyView,
1161                  action: &dyn Action,
1162                  cx: &mut MutableAppContext,
1163                  window_id: usize,
1164                  view_id: usize| {
1165                let action = action.as_any().downcast_ref().unwrap();
1166                let mut cx = ViewContext::new(cx, window_id, view_id);
1167                handler(
1168                    view.as_any_mut()
1169                        .downcast_mut()
1170                        .expect("downcast is type safe"),
1171                    action,
1172                    &mut cx,
1173                );
1174            },
1175        );
1176
1177        self.action_deserializers
1178            .entry(A::qualified_name())
1179            .or_insert((TypeId::of::<A>(), A::from_json_str));
1180
1181        let actions = if capture {
1182            &mut self.capture_actions
1183        } else {
1184            &mut self.actions
1185        };
1186
1187        actions
1188            .entry(TypeId::of::<V>())
1189            .or_default()
1190            .entry(TypeId::of::<A>())
1191            .or_default()
1192            .push(handler);
1193    }
1194
1195    pub fn add_async_action<A, V, F>(&mut self, mut handler: F)
1196    where
1197        A: Action,
1198        V: View,
1199        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> Option<Task<Result<()>>>,
1200    {
1201        self.add_action(move |view, action, cx| {
1202            handler(view, action, cx).map(|task| task.detach_and_log_err(cx));
1203        })
1204    }
1205
1206    pub fn add_global_action<A, F>(&mut self, mut handler: F)
1207    where
1208        A: Action,
1209        F: 'static + FnMut(&A, &mut MutableAppContext),
1210    {
1211        let handler = Box::new(move |action: &dyn Action, cx: &mut MutableAppContext| {
1212            let action = action.as_any().downcast_ref().unwrap();
1213            handler(action, cx);
1214        });
1215
1216        self.action_deserializers
1217            .entry(A::qualified_name())
1218            .or_insert((TypeId::of::<A>(), A::from_json_str));
1219
1220        if self
1221            .global_actions
1222            .insert(TypeId::of::<A>(), handler)
1223            .is_some()
1224        {
1225            panic!(
1226                "registered multiple global handlers for {}",
1227                type_name::<A>()
1228            );
1229        }
1230    }
1231
1232    pub fn window_ids(&self) -> impl Iterator<Item = usize> + '_ {
1233        self.cx.windows.keys().cloned()
1234    }
1235
1236    pub fn activate_window(&self, window_id: usize) {
1237        if let Some((_, window)) = self.presenters_and_platform_windows.get(&window_id) {
1238            window.activate()
1239        }
1240    }
1241
1242    pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
1243        self.cx
1244            .windows
1245            .get(&window_id)
1246            .and_then(|window| window.root_view.clone().downcast::<T>())
1247    }
1248
1249    pub fn window_is_active(&self, window_id: usize) -> bool {
1250        self.cx
1251            .windows
1252            .get(&window_id)
1253            .map_or(false, |window| window.is_active)
1254    }
1255
1256    pub fn window_is_fullscreen(&self, window_id: usize) -> bool {
1257        self.cx
1258            .windows
1259            .get(&window_id)
1260            .map_or(false, |window| window.is_fullscreen)
1261    }
1262
1263    pub fn render_view(&mut self, params: RenderParams) -> Result<ElementBox> {
1264        let window_id = params.window_id;
1265        let view_id = params.view_id;
1266        let mut view = self
1267            .cx
1268            .views
1269            .remove(&(params.window_id, params.view_id))
1270            .ok_or(anyhow!("view not found"))?;
1271        let element = view.render(params, self);
1272        self.cx.views.insert((window_id, view_id), view);
1273        Ok(element)
1274    }
1275
1276    pub fn render_views(
1277        &mut self,
1278        window_id: usize,
1279        titlebar_height: f32,
1280    ) -> HashMap<usize, ElementBox> {
1281        self.start_frame();
1282        let view_ids = self
1283            .views
1284            .keys()
1285            .filter_map(|(win_id, view_id)| {
1286                if *win_id == window_id {
1287                    Some(*view_id)
1288                } else {
1289                    None
1290                }
1291            })
1292            .collect::<Vec<_>>();
1293        view_ids
1294            .into_iter()
1295            .map(|view_id| {
1296                (
1297                    view_id,
1298                    self.render_view(RenderParams {
1299                        window_id,
1300                        view_id,
1301                        titlebar_height,
1302                        hovered_region_ids: Default::default(),
1303                        clicked_region_id: None,
1304                        right_clicked_region_id: None,
1305                        refreshing: false,
1306                    })
1307                    .unwrap(),
1308                )
1309            })
1310            .collect()
1311    }
1312
1313    pub(crate) fn start_frame(&mut self) {
1314        self.frame_count += 1;
1315    }
1316
1317    pub fn update<T, F: FnOnce(&mut Self) -> T>(&mut self, callback: F) -> T {
1318        self.pending_flushes += 1;
1319        let result = callback(self);
1320        self.flush_effects();
1321        result
1322    }
1323
1324    pub fn set_menus(&mut self, menus: Vec<Menu>) {
1325        self.foreground_platform
1326            .set_menus(menus, &self.keystroke_matcher);
1327    }
1328
1329    fn show_character_palette(&self, window_id: usize) {
1330        let (_, window) = &self.presenters_and_platform_windows[&window_id];
1331        window.show_character_palette();
1332    }
1333
1334    pub fn minimize_window(&self, window_id: usize) {
1335        let (_, window) = &self.presenters_and_platform_windows[&window_id];
1336        window.minimize();
1337    }
1338
1339    pub fn zoom_window(&self, window_id: usize) {
1340        let (_, window) = &self.presenters_and_platform_windows[&window_id];
1341        window.zoom();
1342    }
1343
1344    fn prompt(
1345        &self,
1346        window_id: usize,
1347        level: PromptLevel,
1348        msg: &str,
1349        answers: &[&str],
1350    ) -> oneshot::Receiver<usize> {
1351        let (_, window) = &self.presenters_and_platform_windows[&window_id];
1352        window.prompt(level, msg, answers)
1353    }
1354
1355    pub fn prompt_for_paths(
1356        &self,
1357        options: PathPromptOptions,
1358    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
1359        self.foreground_platform.prompt_for_paths(options)
1360    }
1361
1362    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
1363        self.foreground_platform.prompt_for_new_path(directory)
1364    }
1365
1366    pub fn emit_global<E: Any>(&mut self, payload: E) {
1367        self.pending_effects.push_back(Effect::GlobalEvent {
1368            payload: Box::new(payload),
1369        });
1370    }
1371
1372    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1373    where
1374        E: Entity,
1375        E::Event: 'static,
1376        H: Handle<E>,
1377        F: 'static + FnMut(H, &E::Event, &mut Self),
1378    {
1379        self.subscribe_internal(handle, move |handle, event, cx| {
1380            callback(handle, event, cx);
1381            true
1382        })
1383    }
1384
1385    pub fn subscribe_global<E, F>(&mut self, mut callback: F) -> Subscription
1386    where
1387        E: Any,
1388        F: 'static + FnMut(&E, &mut Self),
1389    {
1390        let subscription_id = post_inc(&mut self.next_subscription_id);
1391        let type_id = TypeId::of::<E>();
1392        self.pending_effects.push_back(Effect::GlobalSubscription {
1393            type_id,
1394            subscription_id,
1395            callback: Box::new(move |payload, cx| {
1396                let payload = payload.downcast_ref().expect("downcast is type safe");
1397                callback(payload, cx)
1398            }),
1399        });
1400
1401        Subscription::GlobalSubscription {
1402            id: subscription_id,
1403            type_id,
1404            subscriptions: Some(self.global_subscriptions.downgrade()),
1405        }
1406    }
1407
1408    pub fn observe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1409    where
1410        E: Entity,
1411        E::Event: 'static,
1412        H: Handle<E>,
1413        F: 'static + FnMut(H, &mut Self),
1414    {
1415        self.observe_internal(handle, move |handle, cx| {
1416            callback(handle, cx);
1417            true
1418        })
1419    }
1420
1421    pub fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1422    where
1423        E: Entity,
1424        E::Event: 'static,
1425        H: Handle<E>,
1426        F: 'static + FnMut(H, &E::Event, &mut Self) -> bool,
1427    {
1428        let subscription_id = post_inc(&mut self.next_subscription_id);
1429        let emitter = handle.downgrade();
1430        self.pending_effects.push_back(Effect::Subscription {
1431            entity_id: handle.id(),
1432            subscription_id,
1433            callback: Box::new(move |payload, cx| {
1434                if let Some(emitter) = H::upgrade_from(&emitter, cx.as_ref()) {
1435                    let payload = payload.downcast_ref().expect("downcast is type safe");
1436                    callback(emitter, payload, cx)
1437                } else {
1438                    false
1439                }
1440            }),
1441        });
1442        Subscription::Subscription {
1443            id: subscription_id,
1444            entity_id: handle.id(),
1445            subscriptions: Some(self.subscriptions.downgrade()),
1446        }
1447    }
1448
1449    fn observe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1450    where
1451        E: Entity,
1452        E::Event: 'static,
1453        H: Handle<E>,
1454        F: 'static + FnMut(H, &mut Self) -> bool,
1455    {
1456        let subscription_id = post_inc(&mut self.next_subscription_id);
1457        let observed = handle.downgrade();
1458        let entity_id = handle.id();
1459        self.pending_effects.push_back(Effect::Observation {
1460            entity_id,
1461            subscription_id,
1462            callback: Box::new(move |cx| {
1463                if let Some(observed) = H::upgrade_from(&observed, cx) {
1464                    callback(observed, cx)
1465                } else {
1466                    false
1467                }
1468            }),
1469        });
1470        Subscription::Observation {
1471            id: subscription_id,
1472            entity_id,
1473            observations: Some(self.observations.downgrade()),
1474        }
1475    }
1476
1477    fn observe_focus<F, V>(&mut self, handle: &ViewHandle<V>, mut callback: F) -> Subscription
1478    where
1479        F: 'static + FnMut(ViewHandle<V>, bool, &mut MutableAppContext) -> bool,
1480        V: View,
1481    {
1482        let subscription_id = post_inc(&mut self.next_subscription_id);
1483        let observed = handle.downgrade();
1484        let view_id = handle.id();
1485
1486        self.pending_effects.push_back(Effect::FocusObservation {
1487            view_id,
1488            subscription_id,
1489            callback: Box::new(move |focused, cx| {
1490                if let Some(observed) = observed.upgrade(cx) {
1491                    callback(observed, focused, cx)
1492                } else {
1493                    false
1494                }
1495            }),
1496        });
1497
1498        Subscription::FocusObservation {
1499            id: subscription_id,
1500            view_id,
1501            observations: Some(self.focus_observations.downgrade()),
1502        }
1503    }
1504
1505    pub fn observe_global<G, F>(&mut self, mut observe: F) -> Subscription
1506    where
1507        G: Any,
1508        F: 'static + FnMut(&mut MutableAppContext),
1509    {
1510        let type_id = TypeId::of::<G>();
1511        let id = post_inc(&mut self.next_subscription_id);
1512
1513        self.global_observations.add_callback(
1514            type_id,
1515            id,
1516            Box::new(move |cx: &mut MutableAppContext| observe(cx)),
1517        );
1518
1519        Subscription::GlobalObservation {
1520            id,
1521            type_id,
1522            observations: Some(self.global_observations.downgrade()),
1523        }
1524    }
1525
1526    pub fn observe_release<E, H, F>(&mut self, handle: &H, callback: F) -> Subscription
1527    where
1528        E: Entity,
1529        E::Event: 'static,
1530        H: Handle<E>,
1531        F: 'static + FnOnce(&E, &mut Self),
1532    {
1533        let id = post_inc(&mut self.next_subscription_id);
1534        self.release_observations
1535            .lock()
1536            .entry(handle.id())
1537            .or_default()
1538            .insert(
1539                id,
1540                Box::new(move |released, cx| {
1541                    let released = released.downcast_ref().unwrap();
1542                    callback(released, cx)
1543                }),
1544            );
1545        Subscription::ReleaseObservation {
1546            id,
1547            entity_id: handle.id(),
1548            observations: Some(Arc::downgrade(&self.release_observations)),
1549        }
1550    }
1551
1552    pub fn observe_actions<F>(&mut self, callback: F) -> Subscription
1553    where
1554        F: 'static + FnMut(TypeId, &mut MutableAppContext),
1555    {
1556        let id = post_inc(&mut self.next_subscription_id);
1557        self.action_dispatch_observations
1558            .lock()
1559            .insert(id, Box::new(callback));
1560        Subscription::ActionObservation {
1561            id,
1562            observations: Some(Arc::downgrade(&self.action_dispatch_observations)),
1563        }
1564    }
1565
1566    fn observe_window_activation<F>(&mut self, window_id: usize, callback: F) -> Subscription
1567    where
1568        F: 'static + FnMut(bool, &mut MutableAppContext) -> bool,
1569    {
1570        let subscription_id = post_inc(&mut self.next_subscription_id);
1571        self.pending_effects
1572            .push_back(Effect::WindowActivationObservation {
1573                window_id,
1574                subscription_id,
1575                callback: Box::new(callback),
1576            });
1577        Subscription::WindowActivationObservation {
1578            id: subscription_id,
1579            window_id,
1580            observations: Some(self.window_activation_observations.downgrade()),
1581        }
1582    }
1583
1584    fn observe_fullscreen<F>(&mut self, window_id: usize, callback: F) -> Subscription
1585    where
1586        F: 'static + FnMut(bool, &mut MutableAppContext) -> bool,
1587    {
1588        let subscription_id = post_inc(&mut self.next_subscription_id);
1589        self.pending_effects
1590            .push_back(Effect::WindowFullscreenObservation {
1591                window_id,
1592                subscription_id,
1593                callback: Box::new(callback),
1594            });
1595        Subscription::WindowFullscreenObservation {
1596            id: subscription_id,
1597            window_id,
1598            observations: Some(self.window_activation_observations.downgrade()),
1599        }
1600    }
1601
1602    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut MutableAppContext)) {
1603        self.pending_effects.push_back(Effect::Deferred {
1604            callback: Box::new(callback),
1605            after_window_update: false,
1606        })
1607    }
1608
1609    pub fn after_window_update(&mut self, callback: impl 'static + FnOnce(&mut MutableAppContext)) {
1610        self.pending_effects.push_back(Effect::Deferred {
1611            callback: Box::new(callback),
1612            after_window_update: true,
1613        })
1614    }
1615
1616    pub(crate) fn notify_model(&mut self, model_id: usize) {
1617        if self.pending_notifications.insert(model_id) {
1618            self.pending_effects
1619                .push_back(Effect::ModelNotification { model_id });
1620        }
1621    }
1622
1623    pub(crate) fn notify_view(&mut self, window_id: usize, view_id: usize) {
1624        if self.pending_notifications.insert(view_id) {
1625            self.pending_effects
1626                .push_back(Effect::ViewNotification { window_id, view_id });
1627        }
1628    }
1629
1630    pub(crate) fn notify_global(&mut self, type_id: TypeId) {
1631        if self.pending_global_notifications.insert(type_id) {
1632            self.pending_effects
1633                .push_back(Effect::GlobalNotification { type_id });
1634        }
1635    }
1636
1637    pub fn all_action_names<'a>(&'a self) -> impl Iterator<Item = &'static str> + 'a {
1638        self.action_deserializers.keys().copied()
1639    }
1640
1641    pub fn available_actions(
1642        &self,
1643        window_id: usize,
1644        view_id: usize,
1645    ) -> impl Iterator<Item = (&'static str, Box<dyn Action>, SmallVec<[&Binding; 1]>)> {
1646        let mut action_types: HashSet<_> = self.global_actions.keys().copied().collect();
1647
1648        let presenter = self
1649            .presenters_and_platform_windows
1650            .get(&window_id)
1651            .unwrap()
1652            .0
1653            .clone();
1654        let mut dispatch_path = Vec::new();
1655        presenter
1656            .borrow()
1657            .compute_dispatch_path_from(view_id, &mut dispatch_path);
1658        for view_id in dispatch_path {
1659            if let Some(view) = self.views.get(&(window_id, view_id)) {
1660                let view_type = view.as_any().type_id();
1661                if let Some(actions) = self.actions.get(&view_type) {
1662                    action_types.extend(actions.keys().copied());
1663                }
1664            }
1665        }
1666
1667        self.action_deserializers
1668            .iter()
1669            .filter_map(move |(name, (type_id, deserialize))| {
1670                if action_types.contains(type_id) {
1671                    Some((
1672                        *name,
1673                        deserialize("{}").ok()?,
1674                        self.keystroke_matcher
1675                            .bindings_for_action_type(*type_id)
1676                            .collect(),
1677                    ))
1678                } else {
1679                    None
1680                }
1681            })
1682    }
1683
1684    pub fn is_action_available(&self, action: &dyn Action) -> bool {
1685        let action_type = action.as_any().type_id();
1686        if let Some(window_id) = self.cx.platform.key_window_id() {
1687            if let Some((presenter, _)) = self.presenters_and_platform_windows.get(&window_id) {
1688                let dispatch_path = presenter.borrow().dispatch_path(&self.cx);
1689                for view_id in dispatch_path {
1690                    if let Some(view) = self.views.get(&(window_id, view_id)) {
1691                        let view_type = view.as_any().type_id();
1692                        if let Some(actions) = self.actions.get(&view_type) {
1693                            if actions.contains_key(&action_type) {
1694                                return true;
1695                            }
1696                        }
1697                    }
1698                }
1699            }
1700        }
1701        self.global_actions.contains_key(&action_type)
1702    }
1703
1704    /// Return keystrokes that would dispatch the given action closest to the focused view, if there are any.
1705    pub(crate) fn keystrokes_for_action(
1706        &self,
1707        window_id: usize,
1708        dispatch_path: &[usize],
1709        action: &dyn Action,
1710    ) -> Option<SmallVec<[Keystroke; 2]>> {
1711        for view_id in dispatch_path.iter().rev() {
1712            let view = self
1713                .cx
1714                .views
1715                .get(&(window_id, *view_id))
1716                .expect("view in responder chain does not exist");
1717            let cx = view.keymap_context(self.as_ref());
1718            let keystrokes = self.keystroke_matcher.keystrokes_for_action(action, &cx);
1719            if keystrokes.is_some() {
1720                return keystrokes;
1721            }
1722        }
1723
1724        None
1725    }
1726
1727    pub fn dispatch_action_at(&mut self, window_id: usize, view_id: usize, action: &dyn Action) {
1728        let presenter = self
1729            .presenters_and_platform_windows
1730            .get(&window_id)
1731            .unwrap()
1732            .0
1733            .clone();
1734        let mut dispatch_path = Vec::new();
1735        presenter
1736            .borrow()
1737            .compute_dispatch_path_from(view_id, &mut dispatch_path);
1738        self.dispatch_action_any(window_id, &dispatch_path, action);
1739    }
1740
1741    pub fn dispatch_action<A: Action>(
1742        &mut self,
1743        window_id: usize,
1744        dispatch_path: Vec<usize>,
1745        action: &A,
1746    ) {
1747        self.dispatch_action_any(window_id, &dispatch_path, action);
1748    }
1749
1750    pub(crate) fn dispatch_action_any(
1751        &mut self,
1752        window_id: usize,
1753        path: &[usize],
1754        action: &dyn Action,
1755    ) -> bool {
1756        self.update(|this| {
1757            this.halt_action_dispatch = false;
1758            for (capture_phase, view_id) in path
1759                .iter()
1760                .map(|view_id| (true, *view_id))
1761                .chain(path.iter().rev().map(|view_id| (false, *view_id)))
1762            {
1763                if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
1764                    let type_id = view.as_any().type_id();
1765
1766                    if let Some((name, mut handlers)) = this
1767                        .actions_mut(capture_phase)
1768                        .get_mut(&type_id)
1769                        .and_then(|h| h.remove_entry(&action.id()))
1770                    {
1771                        for handler in handlers.iter_mut().rev() {
1772                            this.halt_action_dispatch = true;
1773                            handler(view.as_mut(), action, this, window_id, view_id);
1774                            if this.halt_action_dispatch {
1775                                break;
1776                            }
1777                        }
1778                        this.actions_mut(capture_phase)
1779                            .get_mut(&type_id)
1780                            .unwrap()
1781                            .insert(name, handlers);
1782                    }
1783
1784                    this.cx.views.insert((window_id, view_id), view);
1785
1786                    if this.halt_action_dispatch {
1787                        break;
1788                    }
1789                }
1790            }
1791
1792            if !this.halt_action_dispatch {
1793                this.halt_action_dispatch = this.dispatch_global_action_any(action);
1794            }
1795
1796            this.pending_effects
1797                .push_back(Effect::ActionDispatchNotification {
1798                    action_id: action.id(),
1799                });
1800            this.halt_action_dispatch
1801        })
1802    }
1803
1804    fn actions_mut(
1805        &mut self,
1806        capture_phase: bool,
1807    ) -> &mut HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>> {
1808        if capture_phase {
1809            &mut self.capture_actions
1810        } else {
1811            &mut self.actions
1812        }
1813    }
1814
1815    pub fn dispatch_global_action<A: Action>(&mut self, action: A) {
1816        self.dispatch_global_action_any(&action);
1817    }
1818
1819    fn dispatch_global_action_any(&mut self, action: &dyn Action) -> bool {
1820        self.update(|this| {
1821            if let Some((name, mut handler)) = this.global_actions.remove_entry(&action.id()) {
1822                handler(action, this);
1823                this.global_actions.insert(name, handler);
1824                true
1825            } else {
1826                false
1827            }
1828        })
1829    }
1830
1831    pub fn add_bindings<T: IntoIterator<Item = keymap::Binding>>(&mut self, bindings: T) {
1832        self.keystroke_matcher.add_bindings(bindings);
1833    }
1834
1835    pub fn clear_bindings(&mut self) {
1836        self.keystroke_matcher.clear_bindings();
1837    }
1838
1839    pub fn dispatch_keystroke(
1840        &mut self,
1841        window_id: usize,
1842        dispatch_path: Vec<usize>,
1843        keystroke: &Keystroke,
1844    ) -> bool {
1845        let mut context_chain = Vec::new();
1846        for view_id in &dispatch_path {
1847            let view = self
1848                .cx
1849                .views
1850                .get(&(window_id, *view_id))
1851                .expect("view in responder chain does not exist");
1852            context_chain.push(view.keymap_context(self.as_ref()));
1853        }
1854
1855        let mut pending = false;
1856        for (i, cx) in context_chain.iter().enumerate().rev() {
1857            match self
1858                .keystroke_matcher
1859                .push_keystroke(keystroke.clone(), dispatch_path[i], cx)
1860            {
1861                MatchResult::None => {}
1862                MatchResult::Pending => pending = true,
1863                MatchResult::Action(action) => {
1864                    if self.dispatch_action_any(window_id, &dispatch_path[0..=i], action.as_ref()) {
1865                        self.keystroke_matcher.clear_pending();
1866                        return true;
1867                    }
1868                }
1869            }
1870        }
1871
1872        pending
1873    }
1874
1875    pub fn default_global<T: 'static + Default>(&mut self) -> &T {
1876        let type_id = TypeId::of::<T>();
1877        self.update(|this| {
1878            if let Entry::Vacant(entry) = this.cx.globals.entry(type_id) {
1879                entry.insert(Box::new(T::default()));
1880                this.notify_global(type_id);
1881            }
1882        });
1883        self.globals.get(&type_id).unwrap().downcast_ref().unwrap()
1884    }
1885
1886    pub fn set_global<T: 'static>(&mut self, state: T) {
1887        self.update(|this| {
1888            let type_id = TypeId::of::<T>();
1889            this.cx.globals.insert(type_id, Box::new(state));
1890            this.notify_global(type_id);
1891        });
1892    }
1893
1894    pub fn update_default_global<T, F, U>(&mut self, update: F) -> U
1895    where
1896        T: 'static + Default,
1897        F: FnOnce(&mut T, &mut MutableAppContext) -> U,
1898    {
1899        self.update(|this| {
1900            let type_id = TypeId::of::<T>();
1901            let mut state = this
1902                .cx
1903                .globals
1904                .remove(&type_id)
1905                .unwrap_or_else(|| Box::new(T::default()));
1906            let result = update(state.downcast_mut().unwrap(), this);
1907            this.cx.globals.insert(type_id, state);
1908            this.notify_global(type_id);
1909            result
1910        })
1911    }
1912
1913    pub fn update_global<T, F, U>(&mut self, update: F) -> U
1914    where
1915        T: 'static,
1916        F: FnOnce(&mut T, &mut MutableAppContext) -> U,
1917    {
1918        self.update(|this| {
1919            let type_id = TypeId::of::<T>();
1920            let mut state = this
1921                .cx
1922                .globals
1923                .remove(&type_id)
1924                .expect("no global has been added for this type");
1925            let result = update(state.downcast_mut().unwrap(), this);
1926            this.cx.globals.insert(type_id, state);
1927            this.notify_global(type_id);
1928            result
1929        })
1930    }
1931
1932    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
1933    where
1934        T: Entity,
1935        F: FnOnce(&mut ModelContext<T>) -> T,
1936    {
1937        self.update(|this| {
1938            let model_id = post_inc(&mut this.next_entity_id);
1939            let handle = ModelHandle::new(model_id, &this.cx.ref_counts);
1940            let mut cx = ModelContext::new(this, model_id);
1941            let model = build_model(&mut cx);
1942            this.cx.models.insert(model_id, Box::new(model));
1943            handle
1944        })
1945    }
1946
1947    pub fn add_window<T, F>(
1948        &mut self,
1949        window_options: WindowOptions,
1950        build_root_view: F,
1951    ) -> (usize, ViewHandle<T>)
1952    where
1953        T: View,
1954        F: FnOnce(&mut ViewContext<T>) -> T,
1955    {
1956        self.update(|this| {
1957            let window_id = post_inc(&mut this.next_window_id);
1958            let root_view = this.add_view(window_id, build_root_view);
1959            this.cx.windows.insert(
1960                window_id,
1961                Window {
1962                    root_view: root_view.clone().into(),
1963                    focused_view_id: Some(root_view.id()),
1964                    is_active: false,
1965                    invalidation: None,
1966                    is_fullscreen: false,
1967                },
1968            );
1969            root_view.update(this, |view, cx| view.on_focus(cx));
1970            this.open_platform_window(window_id, window_options);
1971
1972            (window_id, root_view)
1973        })
1974    }
1975
1976    pub fn replace_root_view<T, F>(&mut self, window_id: usize, build_root_view: F) -> ViewHandle<T>
1977    where
1978        T: View,
1979        F: FnOnce(&mut ViewContext<T>) -> T,
1980    {
1981        self.update(|this| {
1982            let root_view = this.add_view(window_id, build_root_view);
1983            let window = this.cx.windows.get_mut(&window_id).unwrap();
1984            window.root_view = root_view.clone().into();
1985            window.focused_view_id = Some(root_view.id());
1986            root_view
1987        })
1988    }
1989
1990    pub fn remove_window(&mut self, window_id: usize) {
1991        self.cx.windows.remove(&window_id);
1992        self.presenters_and_platform_windows.remove(&window_id);
1993        self.flush_effects();
1994    }
1995
1996    fn open_platform_window(&mut self, window_id: usize, window_options: WindowOptions) {
1997        let mut window =
1998            self.cx
1999                .platform
2000                .open_window(window_id, window_options, self.foreground.clone());
2001        let presenter = Rc::new(RefCell::new(
2002            self.build_presenter(window_id, window.titlebar_height()),
2003        ));
2004
2005        {
2006            let mut app = self.upgrade();
2007            let presenter = Rc::downgrade(&presenter);
2008            window.on_event(Box::new(move |event| {
2009                app.update(|cx| {
2010                    if let Some(presenter) = presenter.upgrade() {
2011                        if let Event::KeyDown(KeyDownEvent { keystroke, .. }) = &event {
2012                            if cx.dispatch_keystroke(
2013                                window_id,
2014                                presenter.borrow().dispatch_path(cx.as_ref()),
2015                                keystroke,
2016                            ) {
2017                                return true;
2018                            }
2019                        }
2020
2021                        presenter.borrow_mut().dispatch_event(event, cx)
2022                    } else {
2023                        false
2024                    }
2025                })
2026            }));
2027        }
2028
2029        {
2030            let mut app = self.upgrade();
2031            window.on_active_status_change(Box::new(move |is_active| {
2032                app.update(|cx| cx.window_changed_active_status(window_id, is_active))
2033            }));
2034        }
2035
2036        {
2037            let mut app = self.upgrade();
2038            window.on_resize(Box::new(move || {
2039                app.update(|cx| cx.window_was_resized(window_id))
2040            }));
2041        }
2042
2043        {
2044            let mut app = self.upgrade();
2045            window.on_fullscreen(Box::new(move |is_fullscreen| {
2046                app.update(|cx| cx.window_was_fullscreen_changed(window_id, is_fullscreen))
2047            }));
2048        }
2049
2050        {
2051            let mut app = self.upgrade();
2052            window.on_close(Box::new(move || {
2053                app.update(|cx| cx.remove_window(window_id));
2054            }));
2055        }
2056
2057        window.set_input_handler(Box::new(WindowInputHandler {
2058            app: self.upgrade().0,
2059            window_id,
2060        }));
2061
2062        let scene =
2063            presenter
2064                .borrow_mut()
2065                .build_scene(window.size(), window.scale_factor(), false, self);
2066        window.present_scene(scene);
2067        self.presenters_and_platform_windows
2068            .insert(window_id, (presenter.clone(), window));
2069    }
2070
2071    pub fn build_presenter(&mut self, window_id: usize, titlebar_height: f32) -> Presenter {
2072        Presenter::new(
2073            window_id,
2074            titlebar_height,
2075            self.cx.font_cache.clone(),
2076            TextLayoutCache::new(self.cx.platform.fonts()),
2077            self.assets.clone(),
2078            self,
2079        )
2080    }
2081
2082    pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
2083    where
2084        T: View,
2085        F: FnOnce(&mut ViewContext<T>) -> T,
2086    {
2087        self.add_option_view(window_id, |cx| Some(build_view(cx)))
2088            .unwrap()
2089    }
2090
2091    pub fn add_option_view<T, F>(
2092        &mut self,
2093        window_id: usize,
2094        build_view: F,
2095    ) -> Option<ViewHandle<T>>
2096    where
2097        T: View,
2098        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
2099    {
2100        self.update(|this| {
2101            let view_id = post_inc(&mut this.next_entity_id);
2102            let mut cx = ViewContext::new(this, window_id, view_id);
2103            let handle = if let Some(view) = build_view(&mut cx) {
2104                this.cx.views.insert((window_id, view_id), Box::new(view));
2105                if let Some(window) = this.cx.windows.get_mut(&window_id) {
2106                    window
2107                        .invalidation
2108                        .get_or_insert_with(Default::default)
2109                        .updated
2110                        .insert(view_id);
2111                }
2112                Some(ViewHandle::new(window_id, view_id, &this.cx.ref_counts))
2113            } else {
2114                None
2115            };
2116            handle
2117        })
2118    }
2119
2120    fn remove_dropped_entities(&mut self) {
2121        loop {
2122            let (dropped_models, dropped_views, dropped_element_states) =
2123                self.cx.ref_counts.lock().take_dropped();
2124            if dropped_models.is_empty()
2125                && dropped_views.is_empty()
2126                && dropped_element_states.is_empty()
2127            {
2128                break;
2129            }
2130
2131            for model_id in dropped_models {
2132                self.subscriptions.remove(model_id);
2133                self.observations.remove(model_id);
2134                let mut model = self.cx.models.remove(&model_id).unwrap();
2135                model.release(self);
2136                self.pending_effects
2137                    .push_back(Effect::ModelRelease { model_id, model });
2138            }
2139
2140            for (window_id, view_id) in dropped_views {
2141                self.subscriptions.remove(view_id);
2142                self.observations.remove(view_id);
2143                let mut view = self.cx.views.remove(&(window_id, view_id)).unwrap();
2144                view.release(self);
2145                let change_focus_to = self.cx.windows.get_mut(&window_id).and_then(|window| {
2146                    window
2147                        .invalidation
2148                        .get_or_insert_with(Default::default)
2149                        .removed
2150                        .push(view_id);
2151                    if window.focused_view_id == Some(view_id) {
2152                        Some(window.root_view.id())
2153                    } else {
2154                        None
2155                    }
2156                });
2157
2158                if let Some(view_id) = change_focus_to {
2159                    self.handle_focus_effect(window_id, Some(view_id));
2160                }
2161
2162                self.pending_effects
2163                    .push_back(Effect::ViewRelease { view_id, view });
2164            }
2165
2166            for key in dropped_element_states {
2167                self.cx.element_states.remove(&key);
2168            }
2169        }
2170    }
2171
2172    fn flush_effects(&mut self) {
2173        self.pending_flushes = self.pending_flushes.saturating_sub(1);
2174        let mut after_window_update_callbacks = Vec::new();
2175
2176        if !self.flushing_effects && self.pending_flushes == 0 {
2177            self.flushing_effects = true;
2178
2179            let mut refreshing = false;
2180            loop {
2181                if let Some(effect) = self.pending_effects.pop_front() {
2182                    if let Some(pending_focus_index) = self.pending_focus_index.as_mut() {
2183                        *pending_focus_index = pending_focus_index.saturating_sub(1);
2184                    }
2185                    match effect {
2186                        Effect::Subscription {
2187                            entity_id,
2188                            subscription_id,
2189                            callback,
2190                        } => self.subscriptions.add_or_remove_callback(
2191                            entity_id,
2192                            subscription_id,
2193                            callback,
2194                        ),
2195
2196                        Effect::Event { entity_id, payload } => {
2197                            let mut subscriptions = self.subscriptions.clone();
2198                            subscriptions.emit_and_cleanup(entity_id, self, |callback, this| {
2199                                callback(payload.as_ref(), this)
2200                            })
2201                        }
2202
2203                        Effect::GlobalSubscription {
2204                            type_id,
2205                            subscription_id,
2206                            callback,
2207                        } => self.global_subscriptions.add_or_remove_callback(
2208                            type_id,
2209                            subscription_id,
2210                            callback,
2211                        ),
2212
2213                        Effect::GlobalEvent { payload } => self.emit_global_event(payload),
2214
2215                        Effect::Observation {
2216                            entity_id,
2217                            subscription_id,
2218                            callback,
2219                        } => self.observations.add_or_remove_callback(
2220                            entity_id,
2221                            subscription_id,
2222                            callback,
2223                        ),
2224
2225                        Effect::ModelNotification { model_id } => {
2226                            let mut observations = self.observations.clone();
2227                            observations
2228                                .emit_and_cleanup(model_id, self, |callback, this| callback(this));
2229                        }
2230
2231                        Effect::ViewNotification { window_id, view_id } => {
2232                            self.handle_view_notification_effect(window_id, view_id)
2233                        }
2234
2235                        Effect::GlobalNotification { type_id } => {
2236                            let mut subscriptions = self.global_observations.clone();
2237                            subscriptions.emit_and_cleanup(type_id, self, |callback, this| {
2238                                callback(this);
2239                                true
2240                            });
2241                        }
2242
2243                        Effect::Deferred {
2244                            callback,
2245                            after_window_update,
2246                        } => {
2247                            if after_window_update {
2248                                after_window_update_callbacks.push(callback);
2249                            } else {
2250                                callback(self)
2251                            }
2252                        }
2253
2254                        Effect::ModelRelease { model_id, model } => {
2255                            self.handle_entity_release_effect(model_id, model.as_any())
2256                        }
2257
2258                        Effect::ViewRelease { view_id, view } => {
2259                            self.handle_entity_release_effect(view_id, view.as_any())
2260                        }
2261
2262                        Effect::Focus { window_id, view_id } => {
2263                            self.handle_focus_effect(window_id, view_id);
2264                        }
2265
2266                        Effect::FocusObservation {
2267                            view_id,
2268                            subscription_id,
2269                            callback,
2270                        } => {
2271                            self.focus_observations.add_or_remove_callback(
2272                                view_id,
2273                                subscription_id,
2274                                callback,
2275                            );
2276                        }
2277
2278                        Effect::ResizeWindow { window_id } => {
2279                            if let Some(window) = self.cx.windows.get_mut(&window_id) {
2280                                window
2281                                    .invalidation
2282                                    .get_or_insert(WindowInvalidation::default());
2283                            }
2284                        }
2285
2286                        Effect::WindowActivationObservation {
2287                            window_id,
2288                            subscription_id,
2289                            callback,
2290                        } => self.window_activation_observations.add_or_remove_callback(
2291                            window_id,
2292                            subscription_id,
2293                            callback,
2294                        ),
2295
2296                        Effect::ActivateWindow {
2297                            window_id,
2298                            is_active,
2299                        } => self.handle_window_activation_effect(window_id, is_active),
2300
2301                        Effect::WindowFullscreenObservation {
2302                            window_id,
2303                            subscription_id,
2304                            callback,
2305                        } => self.window_fullscreen_observations.add_or_remove_callback(
2306                            window_id,
2307                            subscription_id,
2308                            callback,
2309                        ),
2310
2311                        Effect::FullscreenWindow {
2312                            window_id,
2313                            is_fullscreen,
2314                        } => self.handle_fullscreen_effect(window_id, is_fullscreen),
2315
2316                        Effect::RefreshWindows => {
2317                            refreshing = true;
2318                        }
2319                        Effect::ActionDispatchNotification { action_id } => {
2320                            self.handle_action_dispatch_notification_effect(action_id)
2321                        }
2322                        Effect::WindowShouldCloseSubscription {
2323                            window_id,
2324                            callback,
2325                        } => {
2326                            self.handle_window_should_close_subscription_effect(window_id, callback)
2327                        }
2328                    }
2329                    self.pending_notifications.clear();
2330                    self.remove_dropped_entities();
2331                } else {
2332                    self.remove_dropped_entities();
2333                    if refreshing {
2334                        self.perform_window_refresh();
2335                    } else {
2336                        self.update_windows();
2337                    }
2338
2339                    if self.pending_effects.is_empty() {
2340                        for callback in after_window_update_callbacks.drain(..) {
2341                            callback(self);
2342                        }
2343
2344                        if self.pending_effects.is_empty() {
2345                            self.flushing_effects = false;
2346                            self.pending_notifications.clear();
2347                            self.pending_global_notifications.clear();
2348                            break;
2349                        }
2350                    }
2351
2352                    refreshing = false;
2353                }
2354            }
2355        }
2356    }
2357
2358    fn update_windows(&mut self) {
2359        let mut invalidations: HashMap<_, _> = Default::default();
2360        for (window_id, window) in &mut self.cx.windows {
2361            if let Some(invalidation) = window.invalidation.take() {
2362                invalidations.insert(*window_id, invalidation);
2363            }
2364        }
2365
2366        for (window_id, mut invalidation) in invalidations {
2367            if let Some((presenter, mut window)) =
2368                self.presenters_and_platform_windows.remove(&window_id)
2369            {
2370                {
2371                    let mut presenter = presenter.borrow_mut();
2372                    presenter.invalidate(&mut invalidation, self);
2373                    let scene =
2374                        presenter.build_scene(window.size(), window.scale_factor(), false, self);
2375                    window.present_scene(scene);
2376                }
2377                self.presenters_and_platform_windows
2378                    .insert(window_id, (presenter, window));
2379            }
2380        }
2381    }
2382
2383    fn window_was_resized(&mut self, window_id: usize) {
2384        self.pending_effects
2385            .push_back(Effect::ResizeWindow { window_id });
2386    }
2387
2388    fn window_was_fullscreen_changed(&mut self, window_id: usize, is_fullscreen: bool) {
2389        self.pending_effects.push_back(Effect::FullscreenWindow {
2390            window_id,
2391            is_fullscreen,
2392        });
2393    }
2394
2395    fn window_changed_active_status(&mut self, window_id: usize, is_active: bool) {
2396        self.pending_effects.push_back(Effect::ActivateWindow {
2397            window_id,
2398            is_active,
2399        });
2400    }
2401
2402    pub fn refresh_windows(&mut self) {
2403        self.pending_effects.push_back(Effect::RefreshWindows);
2404    }
2405
2406    fn perform_window_refresh(&mut self) {
2407        let mut presenters = mem::take(&mut self.presenters_and_platform_windows);
2408        for (window_id, (presenter, window)) in &mut presenters {
2409            let mut invalidation = self
2410                .cx
2411                .windows
2412                .get_mut(&window_id)
2413                .unwrap()
2414                .invalidation
2415                .take();
2416            let mut presenter = presenter.borrow_mut();
2417            presenter.refresh(
2418                invalidation.as_mut().unwrap_or(&mut Default::default()),
2419                self,
2420            );
2421            let scene = presenter.build_scene(window.size(), window.scale_factor(), true, self);
2422            window.present_scene(scene);
2423        }
2424        self.presenters_and_platform_windows = presenters;
2425    }
2426
2427    fn emit_global_event(&mut self, payload: Box<dyn Any>) {
2428        let type_id = (&*payload).type_id();
2429
2430        let mut subscriptions = self.global_subscriptions.clone();
2431        subscriptions.emit_and_cleanup(type_id, self, |callback, this| {
2432            callback(payload.as_ref(), this);
2433            true //Always alive
2434        });
2435    }
2436
2437    fn handle_view_notification_effect(
2438        &mut self,
2439        observed_window_id: usize,
2440        observed_view_id: usize,
2441    ) {
2442        if self
2443            .cx
2444            .views
2445            .contains_key(&(observed_window_id, observed_view_id))
2446        {
2447            if let Some(window) = self.cx.windows.get_mut(&observed_window_id) {
2448                window
2449                    .invalidation
2450                    .get_or_insert_with(Default::default)
2451                    .updated
2452                    .insert(observed_view_id);
2453            }
2454
2455            let mut observations = self.observations.clone();
2456            observations.emit_and_cleanup(observed_view_id, self, |callback, this| callback(this));
2457        }
2458    }
2459
2460    fn handle_entity_release_effect(&mut self, entity_id: usize, entity: &dyn Any) {
2461        let callbacks = self.release_observations.lock().remove(&entity_id);
2462        if let Some(callbacks) = callbacks {
2463            for (_, callback) in callbacks {
2464                callback(entity, self);
2465            }
2466        }
2467    }
2468
2469    fn handle_fullscreen_effect(&mut self, window_id: usize, is_fullscreen: bool) {
2470        //Short circuit evaluation if we're already g2g
2471        if self
2472            .cx
2473            .windows
2474            .get(&window_id)
2475            .map(|w| w.is_fullscreen == is_fullscreen)
2476            .unwrap_or(false)
2477        {
2478            return;
2479        }
2480
2481        self.update(|this| {
2482            let window = this.cx.windows.get_mut(&window_id)?;
2483            window.is_fullscreen = is_fullscreen;
2484
2485            let mut observations = this.window_fullscreen_observations.clone();
2486            observations.emit_and_cleanup(window_id, this, |callback, this| {
2487                callback(is_fullscreen, this)
2488            });
2489
2490            Some(())
2491        });
2492    }
2493
2494    fn handle_window_activation_effect(&mut self, window_id: usize, active: bool) {
2495        //Short circuit evaluation if we're already g2g
2496        if self
2497            .cx
2498            .windows
2499            .get(&window_id)
2500            .map(|w| w.is_active == active)
2501            .unwrap_or(false)
2502        {
2503            return;
2504        }
2505
2506        self.update(|this| {
2507            let window = this.cx.windows.get_mut(&window_id)?;
2508            window.is_active = active;
2509
2510            //Handle focus
2511            let view_id = window.focused_view_id?;
2512            if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
2513                if active {
2514                    view.on_focus(this, window_id, view_id);
2515                } else {
2516                    view.on_blur(this, window_id, view_id);
2517                }
2518                this.cx.views.insert((window_id, view_id), view);
2519            }
2520
2521            let mut observations = this.window_activation_observations.clone();
2522            observations.emit_and_cleanup(window_id, this, |callback, this| callback(active, this));
2523
2524            Some(())
2525        });
2526    }
2527
2528    fn handle_focus_effect(&mut self, window_id: usize, focused_id: Option<usize>) {
2529        self.pending_focus_index.take();
2530
2531        if self
2532            .cx
2533            .windows
2534            .get(&window_id)
2535            .map(|w| w.focused_view_id)
2536            .map_or(false, |cur_focused| cur_focused == focused_id)
2537        {
2538            return;
2539        }
2540
2541        self.update(|this| {
2542            let blurred_id = this.cx.windows.get_mut(&window_id).and_then(|window| {
2543                let blurred_id = window.focused_view_id;
2544                window.focused_view_id = focused_id;
2545                blurred_id
2546            });
2547
2548            if let Some(blurred_id) = blurred_id {
2549                if let Some(mut blurred_view) = this.cx.views.remove(&(window_id, blurred_id)) {
2550                    blurred_view.on_blur(this, window_id, blurred_id);
2551                    this.cx.views.insert((window_id, blurred_id), blurred_view);
2552
2553                    let mut subscriptions = this.focus_observations.clone();
2554                    subscriptions
2555                        .emit_and_cleanup(blurred_id, this, |callback, this| callback(false, this));
2556                }
2557            }
2558
2559            if let Some(focused_id) = focused_id {
2560                if let Some(mut focused_view) = this.cx.views.remove(&(window_id, focused_id)) {
2561                    focused_view.on_focus(this, window_id, focused_id);
2562                    this.cx.views.insert((window_id, focused_id), focused_view);
2563
2564                    let mut subscriptions = this.focus_observations.clone();
2565                    subscriptions
2566                        .emit_and_cleanup(focused_id, this, |callback, this| callback(true, this));
2567                }
2568            }
2569        })
2570    }
2571
2572    fn handle_action_dispatch_notification_effect(&mut self, action_id: TypeId) {
2573        let mut callbacks = mem::take(&mut *self.action_dispatch_observations.lock());
2574        for (_, callback) in &mut callbacks {
2575            callback(action_id, self);
2576        }
2577        self.action_dispatch_observations.lock().extend(callbacks);
2578    }
2579
2580    fn handle_window_should_close_subscription_effect(
2581        &mut self,
2582        window_id: usize,
2583        mut callback: WindowShouldCloseSubscriptionCallback,
2584    ) {
2585        let mut app = self.upgrade();
2586        if let Some((_, window)) = self.presenters_and_platform_windows.get_mut(&window_id) {
2587            window.on_should_close(Box::new(move || app.update(|cx| callback(cx))))
2588        }
2589    }
2590
2591    pub fn focus(&mut self, window_id: usize, view_id: Option<usize>) {
2592        if let Some(pending_focus_index) = self.pending_focus_index {
2593            self.pending_effects.remove(pending_focus_index);
2594        }
2595        self.pending_focus_index = Some(self.pending_effects.len());
2596        self.pending_effects
2597            .push_back(Effect::Focus { window_id, view_id });
2598    }
2599
2600    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
2601    where
2602        F: FnOnce(AsyncAppContext) -> Fut,
2603        Fut: 'static + Future<Output = T>,
2604        T: 'static,
2605    {
2606        let future = f(self.to_async());
2607        let cx = self.to_async();
2608        self.foreground.spawn(async move {
2609            let result = future.await;
2610            cx.0.borrow_mut().flush_effects();
2611            result
2612        })
2613    }
2614
2615    pub fn to_async(&self) -> AsyncAppContext {
2616        AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
2617    }
2618
2619    pub fn write_to_clipboard(&self, item: ClipboardItem) {
2620        self.cx.platform.write_to_clipboard(item);
2621    }
2622
2623    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
2624        self.cx.platform.read_from_clipboard()
2625    }
2626
2627    #[cfg(any(test, feature = "test-support"))]
2628    pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
2629        self.cx.ref_counts.lock().leak_detector.clone()
2630    }
2631}
2632
2633impl ReadModel for MutableAppContext {
2634    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2635        if let Some(model) = self.cx.models.get(&handle.model_id) {
2636            model
2637                .as_any()
2638                .downcast_ref()
2639                .expect("downcast is type safe")
2640        } else {
2641            panic!("circular model reference");
2642        }
2643    }
2644}
2645
2646impl UpdateModel for MutableAppContext {
2647    fn update_model<T: Entity, V>(
2648        &mut self,
2649        handle: &ModelHandle<T>,
2650        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
2651    ) -> V {
2652        if let Some(mut model) = self.cx.models.remove(&handle.model_id) {
2653            self.update(|this| {
2654                let mut cx = ModelContext::new(this, handle.model_id);
2655                let result = update(
2656                    model
2657                        .as_any_mut()
2658                        .downcast_mut()
2659                        .expect("downcast is type safe"),
2660                    &mut cx,
2661                );
2662                this.cx.models.insert(handle.model_id, model);
2663                result
2664            })
2665        } else {
2666            panic!("circular model update");
2667        }
2668    }
2669}
2670
2671impl UpgradeModelHandle for MutableAppContext {
2672    fn upgrade_model_handle<T: Entity>(
2673        &self,
2674        handle: &WeakModelHandle<T>,
2675    ) -> Option<ModelHandle<T>> {
2676        self.cx.upgrade_model_handle(handle)
2677    }
2678
2679    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2680        self.cx.model_handle_is_upgradable(handle)
2681    }
2682
2683    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2684        self.cx.upgrade_any_model_handle(handle)
2685    }
2686}
2687
2688impl UpgradeViewHandle for MutableAppContext {
2689    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2690        self.cx.upgrade_view_handle(handle)
2691    }
2692
2693    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
2694        self.cx.upgrade_any_view_handle(handle)
2695    }
2696}
2697
2698impl ReadView for MutableAppContext {
2699    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2700        if let Some(view) = self.cx.views.get(&(handle.window_id, handle.view_id)) {
2701            view.as_any().downcast_ref().expect("downcast is type safe")
2702        } else {
2703            panic!("circular view reference");
2704        }
2705    }
2706}
2707
2708impl UpdateView for MutableAppContext {
2709    fn update_view<T, S>(
2710        &mut self,
2711        handle: &ViewHandle<T>,
2712        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
2713    ) -> S
2714    where
2715        T: View,
2716    {
2717        self.update(|this| {
2718            let mut view = this
2719                .cx
2720                .views
2721                .remove(&(handle.window_id, handle.view_id))
2722                .expect("circular view update");
2723
2724            let mut cx = ViewContext::new(this, handle.window_id, handle.view_id);
2725            let result = update(
2726                view.as_any_mut()
2727                    .downcast_mut()
2728                    .expect("downcast is type safe"),
2729                &mut cx,
2730            );
2731            this.cx
2732                .views
2733                .insert((handle.window_id, handle.view_id), view);
2734            result
2735        })
2736    }
2737}
2738
2739impl AsRef<AppContext> for MutableAppContext {
2740    fn as_ref(&self) -> &AppContext {
2741        &self.cx
2742    }
2743}
2744
2745impl Deref for MutableAppContext {
2746    type Target = AppContext;
2747
2748    fn deref(&self) -> &Self::Target {
2749        &self.cx
2750    }
2751}
2752
2753pub struct AppContext {
2754    models: HashMap<usize, Box<dyn AnyModel>>,
2755    views: HashMap<(usize, usize), Box<dyn AnyView>>,
2756    windows: HashMap<usize, Window>,
2757    globals: HashMap<TypeId, Box<dyn Any>>,
2758    element_states: HashMap<ElementStateId, Box<dyn Any>>,
2759    background: Arc<executor::Background>,
2760    ref_counts: Arc<Mutex<RefCounts>>,
2761    font_cache: Arc<FontCache>,
2762    platform: Arc<dyn Platform>,
2763}
2764
2765impl AppContext {
2766    pub(crate) fn root_view(&self, window_id: usize) -> Option<AnyViewHandle> {
2767        self.windows
2768            .get(&window_id)
2769            .map(|window| window.root_view.clone())
2770    }
2771
2772    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
2773        self.windows
2774            .get(&window_id)
2775            .map(|window| window.root_view.id())
2776    }
2777
2778    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
2779        self.windows
2780            .get(&window_id)
2781            .and_then(|window| window.focused_view_id)
2782    }
2783
2784    pub fn background(&self) -> &Arc<executor::Background> {
2785        &self.background
2786    }
2787
2788    pub fn font_cache(&self) -> &Arc<FontCache> {
2789        &self.font_cache
2790    }
2791
2792    pub fn platform(&self) -> &Arc<dyn Platform> {
2793        &self.platform
2794    }
2795
2796    pub fn has_global<T: 'static>(&self) -> bool {
2797        self.globals.contains_key(&TypeId::of::<T>())
2798    }
2799
2800    pub fn global<T: 'static>(&self) -> &T {
2801        if let Some(global) = self.globals.get(&TypeId::of::<T>()) {
2802            global.downcast_ref().unwrap()
2803        } else {
2804            panic!("no global has been added for {}", type_name::<T>());
2805        }
2806    }
2807}
2808
2809impl ReadModel for AppContext {
2810    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2811        if let Some(model) = self.models.get(&handle.model_id) {
2812            model
2813                .as_any()
2814                .downcast_ref()
2815                .expect("downcast should be type safe")
2816        } else {
2817            panic!("circular model reference");
2818        }
2819    }
2820}
2821
2822impl UpgradeModelHandle for AppContext {
2823    fn upgrade_model_handle<T: Entity>(
2824        &self,
2825        handle: &WeakModelHandle<T>,
2826    ) -> Option<ModelHandle<T>> {
2827        if self.models.contains_key(&handle.model_id) {
2828            Some(ModelHandle::new(handle.model_id, &self.ref_counts))
2829        } else {
2830            None
2831        }
2832    }
2833
2834    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2835        self.models.contains_key(&handle.model_id)
2836    }
2837
2838    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2839        if self.models.contains_key(&handle.model_id) {
2840            Some(AnyModelHandle::new(
2841                handle.model_id,
2842                handle.model_type,
2843                self.ref_counts.clone(),
2844            ))
2845        } else {
2846            None
2847        }
2848    }
2849}
2850
2851impl UpgradeViewHandle for AppContext {
2852    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2853        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2854            Some(ViewHandle::new(
2855                handle.window_id,
2856                handle.view_id,
2857                &self.ref_counts,
2858            ))
2859        } else {
2860            None
2861        }
2862    }
2863
2864    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
2865        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2866            Some(AnyViewHandle::new(
2867                handle.window_id,
2868                handle.view_id,
2869                handle.view_type,
2870                self.ref_counts.clone(),
2871            ))
2872        } else {
2873            None
2874        }
2875    }
2876}
2877
2878impl ReadView for AppContext {
2879    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2880        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
2881            view.as_any()
2882                .downcast_ref()
2883                .expect("downcast should be type safe")
2884        } else {
2885            panic!("circular view reference");
2886        }
2887    }
2888}
2889
2890struct Window {
2891    root_view: AnyViewHandle,
2892    focused_view_id: Option<usize>,
2893    is_active: bool,
2894    is_fullscreen: bool,
2895    invalidation: Option<WindowInvalidation>,
2896}
2897
2898#[derive(Default, Clone)]
2899pub struct WindowInvalidation {
2900    pub updated: HashSet<usize>,
2901    pub removed: Vec<usize>,
2902}
2903
2904pub enum Effect {
2905    Subscription {
2906        entity_id: usize,
2907        subscription_id: usize,
2908        callback: SubscriptionCallback,
2909    },
2910    Event {
2911        entity_id: usize,
2912        payload: Box<dyn Any>,
2913    },
2914    GlobalSubscription {
2915        type_id: TypeId,
2916        subscription_id: usize,
2917        callback: GlobalSubscriptionCallback,
2918    },
2919    GlobalEvent {
2920        payload: Box<dyn Any>,
2921    },
2922    Observation {
2923        entity_id: usize,
2924        subscription_id: usize,
2925        callback: ObservationCallback,
2926    },
2927    ModelNotification {
2928        model_id: usize,
2929    },
2930    ViewNotification {
2931        window_id: usize,
2932        view_id: usize,
2933    },
2934    Deferred {
2935        callback: Box<dyn FnOnce(&mut MutableAppContext)>,
2936        after_window_update: bool,
2937    },
2938    GlobalNotification {
2939        type_id: TypeId,
2940    },
2941    ModelRelease {
2942        model_id: usize,
2943        model: Box<dyn AnyModel>,
2944    },
2945    ViewRelease {
2946        view_id: usize,
2947        view: Box<dyn AnyView>,
2948    },
2949    Focus {
2950        window_id: usize,
2951        view_id: Option<usize>,
2952    },
2953    FocusObservation {
2954        view_id: usize,
2955        subscription_id: usize,
2956        callback: FocusObservationCallback,
2957    },
2958    ResizeWindow {
2959        window_id: usize,
2960    },
2961    FullscreenWindow {
2962        window_id: usize,
2963        is_fullscreen: bool,
2964    },
2965    ActivateWindow {
2966        window_id: usize,
2967        is_active: bool,
2968    },
2969    WindowActivationObservation {
2970        window_id: usize,
2971        subscription_id: usize,
2972        callback: WindowActivationCallback,
2973    },
2974    WindowFullscreenObservation {
2975        window_id: usize,
2976        subscription_id: usize,
2977        callback: WindowFullscreenCallback,
2978    },
2979    RefreshWindows,
2980    ActionDispatchNotification {
2981        action_id: TypeId,
2982    },
2983    WindowShouldCloseSubscription {
2984        window_id: usize,
2985        callback: WindowShouldCloseSubscriptionCallback,
2986    },
2987}
2988
2989impl Debug for Effect {
2990    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2991        match self {
2992            Effect::Subscription {
2993                entity_id,
2994                subscription_id,
2995                ..
2996            } => f
2997                .debug_struct("Effect::Subscribe")
2998                .field("entity_id", entity_id)
2999                .field("subscription_id", subscription_id)
3000                .finish(),
3001            Effect::Event { entity_id, .. } => f
3002                .debug_struct("Effect::Event")
3003                .field("entity_id", entity_id)
3004                .finish(),
3005            Effect::GlobalSubscription {
3006                type_id,
3007                subscription_id,
3008                ..
3009            } => f
3010                .debug_struct("Effect::Subscribe")
3011                .field("type_id", type_id)
3012                .field("subscription_id", subscription_id)
3013                .finish(),
3014            Effect::GlobalEvent { payload, .. } => f
3015                .debug_struct("Effect::GlobalEvent")
3016                .field("type_id", &(&*payload).type_id())
3017                .finish(),
3018            Effect::Observation {
3019                entity_id,
3020                subscription_id,
3021                ..
3022            } => f
3023                .debug_struct("Effect::Observation")
3024                .field("entity_id", entity_id)
3025                .field("subscription_id", subscription_id)
3026                .finish(),
3027            Effect::ModelNotification { model_id } => f
3028                .debug_struct("Effect::ModelNotification")
3029                .field("model_id", model_id)
3030                .finish(),
3031            Effect::ViewNotification { window_id, view_id } => f
3032                .debug_struct("Effect::ViewNotification")
3033                .field("window_id", window_id)
3034                .field("view_id", view_id)
3035                .finish(),
3036            Effect::GlobalNotification { type_id } => f
3037                .debug_struct("Effect::GlobalNotification")
3038                .field("type_id", type_id)
3039                .finish(),
3040            Effect::Deferred { .. } => f.debug_struct("Effect::Deferred").finish(),
3041            Effect::ModelRelease { model_id, .. } => f
3042                .debug_struct("Effect::ModelRelease")
3043                .field("model_id", model_id)
3044                .finish(),
3045            Effect::ViewRelease { view_id, .. } => f
3046                .debug_struct("Effect::ViewRelease")
3047                .field("view_id", view_id)
3048                .finish(),
3049            Effect::Focus { window_id, view_id } => f
3050                .debug_struct("Effect::Focus")
3051                .field("window_id", window_id)
3052                .field("view_id", view_id)
3053                .finish(),
3054            Effect::FocusObservation {
3055                view_id,
3056                subscription_id,
3057                ..
3058            } => f
3059                .debug_struct("Effect::FocusObservation")
3060                .field("view_id", view_id)
3061                .field("subscription_id", subscription_id)
3062                .finish(),
3063            Effect::ActionDispatchNotification { action_id, .. } => f
3064                .debug_struct("Effect::ActionDispatchNotification")
3065                .field("action_id", action_id)
3066                .finish(),
3067            Effect::ResizeWindow { window_id } => f
3068                .debug_struct("Effect::RefreshWindow")
3069                .field("window_id", window_id)
3070                .finish(),
3071            Effect::WindowActivationObservation {
3072                window_id,
3073                subscription_id,
3074                ..
3075            } => f
3076                .debug_struct("Effect::WindowActivationObservation")
3077                .field("window_id", window_id)
3078                .field("subscription_id", subscription_id)
3079                .finish(),
3080            Effect::ActivateWindow {
3081                window_id,
3082                is_active,
3083            } => f
3084                .debug_struct("Effect::ActivateWindow")
3085                .field("window_id", window_id)
3086                .field("is_active", is_active)
3087                .finish(),
3088            Effect::FullscreenWindow {
3089                window_id,
3090                is_fullscreen,
3091            } => f
3092                .debug_struct("Effect::FullscreenWindow")
3093                .field("window_id", window_id)
3094                .field("is_fullscreen", is_fullscreen)
3095                .finish(),
3096            Effect::WindowFullscreenObservation {
3097                window_id,
3098                subscription_id,
3099                callback: _,
3100            } => f
3101                .debug_struct("Effect::WindowFullscreenObservation")
3102                .field("window_id", window_id)
3103                .field("subscription_id", subscription_id)
3104                .finish(),
3105            Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
3106            Effect::WindowShouldCloseSubscription { window_id, .. } => f
3107                .debug_struct("Effect::WindowShouldCloseSubscription")
3108                .field("window_id", window_id)
3109                .finish(),
3110        }
3111    }
3112}
3113
3114pub trait AnyModel {
3115    fn as_any(&self) -> &dyn Any;
3116    fn as_any_mut(&mut self) -> &mut dyn Any;
3117    fn release(&mut self, cx: &mut MutableAppContext);
3118    fn app_will_quit(
3119        &mut self,
3120        cx: &mut MutableAppContext,
3121    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
3122}
3123
3124impl<T> AnyModel for T
3125where
3126    T: Entity,
3127{
3128    fn as_any(&self) -> &dyn Any {
3129        self
3130    }
3131
3132    fn as_any_mut(&mut self) -> &mut dyn Any {
3133        self
3134    }
3135
3136    fn release(&mut self, cx: &mut MutableAppContext) {
3137        self.release(cx);
3138    }
3139
3140    fn app_will_quit(
3141        &mut self,
3142        cx: &mut MutableAppContext,
3143    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
3144        self.app_will_quit(cx)
3145    }
3146}
3147
3148pub trait AnyView {
3149    fn as_any(&self) -> &dyn Any;
3150    fn as_any_mut(&mut self) -> &mut dyn Any;
3151    fn release(&mut self, cx: &mut MutableAppContext);
3152    fn app_will_quit(
3153        &mut self,
3154        cx: &mut MutableAppContext,
3155    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
3156    fn ui_name(&self) -> &'static str;
3157    fn render<'a>(&mut self, params: RenderParams, cx: &mut MutableAppContext) -> ElementBox;
3158    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
3159    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
3160    fn keymap_context(&self, cx: &AppContext) -> keymap::Context;
3161    fn debug_json(&self, cx: &AppContext) -> serde_json::Value;
3162
3163    fn text_for_range(&self, range: Range<usize>, cx: &AppContext) -> Option<String>;
3164    fn selected_text_range(&self, cx: &AppContext) -> Option<Range<usize>>;
3165    fn marked_text_range(&self, cx: &AppContext) -> Option<Range<usize>>;
3166    fn unmark_text(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
3167    fn replace_text_in_range(
3168        &mut self,
3169        range: Option<Range<usize>>,
3170        text: &str,
3171        cx: &mut MutableAppContext,
3172        window_id: usize,
3173        view_id: usize,
3174    );
3175    fn replace_and_mark_text_in_range(
3176        &mut self,
3177        range: Option<Range<usize>>,
3178        new_text: &str,
3179        new_selected_range: Option<Range<usize>>,
3180        cx: &mut MutableAppContext,
3181        window_id: usize,
3182        view_id: usize,
3183    );
3184}
3185
3186impl<T> AnyView for T
3187where
3188    T: View,
3189{
3190    fn as_any(&self) -> &dyn Any {
3191        self
3192    }
3193
3194    fn as_any_mut(&mut self) -> &mut dyn Any {
3195        self
3196    }
3197
3198    fn release(&mut self, cx: &mut MutableAppContext) {
3199        self.release(cx);
3200    }
3201
3202    fn app_will_quit(
3203        &mut self,
3204        cx: &mut MutableAppContext,
3205    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
3206        self.app_will_quit(cx)
3207    }
3208
3209    fn ui_name(&self) -> &'static str {
3210        T::ui_name()
3211    }
3212
3213    fn render<'a>(&mut self, params: RenderParams, cx: &mut MutableAppContext) -> ElementBox {
3214        View::render(self, &mut RenderContext::new(params, cx))
3215    }
3216
3217    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
3218        let mut cx = ViewContext::new(cx, window_id, view_id);
3219        View::on_focus(self, &mut cx);
3220    }
3221
3222    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
3223        let mut cx = ViewContext::new(cx, window_id, view_id);
3224        View::on_blur(self, &mut cx);
3225    }
3226
3227    fn keymap_context(&self, cx: &AppContext) -> keymap::Context {
3228        View::keymap_context(self, cx)
3229    }
3230
3231    fn debug_json(&self, cx: &AppContext) -> serde_json::Value {
3232        View::debug_json(self, cx)
3233    }
3234
3235    fn text_for_range(&self, range: Range<usize>, cx: &AppContext) -> Option<String> {
3236        View::text_for_range(self, range, cx)
3237    }
3238
3239    fn selected_text_range(&self, cx: &AppContext) -> Option<Range<usize>> {
3240        View::selected_text_range(self, cx)
3241    }
3242
3243    fn marked_text_range(&self, cx: &AppContext) -> Option<Range<usize>> {
3244        View::marked_text_range(self, cx)
3245    }
3246
3247    fn unmark_text(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
3248        let mut cx = ViewContext::new(cx, window_id, view_id);
3249        View::unmark_text(self, &mut cx)
3250    }
3251
3252    fn replace_text_in_range(
3253        &mut self,
3254        range: Option<Range<usize>>,
3255        text: &str,
3256        cx: &mut MutableAppContext,
3257        window_id: usize,
3258        view_id: usize,
3259    ) {
3260        let mut cx = ViewContext::new(cx, window_id, view_id);
3261        View::replace_text_in_range(self, range, text, &mut cx)
3262    }
3263
3264    fn replace_and_mark_text_in_range(
3265        &mut self,
3266        range: Option<Range<usize>>,
3267        new_text: &str,
3268        new_selected_range: Option<Range<usize>>,
3269        cx: &mut MutableAppContext,
3270        window_id: usize,
3271        view_id: usize,
3272    ) {
3273        let mut cx = ViewContext::new(cx, window_id, view_id);
3274        View::replace_and_mark_text_in_range(self, range, new_text, new_selected_range, &mut cx)
3275    }
3276}
3277
3278pub struct ModelContext<'a, T: ?Sized> {
3279    app: &'a mut MutableAppContext,
3280    model_id: usize,
3281    model_type: PhantomData<T>,
3282    halt_stream: bool,
3283}
3284
3285impl<'a, T: Entity> ModelContext<'a, T> {
3286    fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
3287        Self {
3288            app,
3289            model_id,
3290            model_type: PhantomData,
3291            halt_stream: false,
3292        }
3293    }
3294
3295    pub fn background(&self) -> &Arc<executor::Background> {
3296        &self.app.cx.background
3297    }
3298
3299    pub fn halt_stream(&mut self) {
3300        self.halt_stream = true;
3301    }
3302
3303    pub fn model_id(&self) -> usize {
3304        self.model_id
3305    }
3306
3307    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
3308    where
3309        S: Entity,
3310        F: FnOnce(&mut ModelContext<S>) -> S,
3311    {
3312        self.app.add_model(build_model)
3313    }
3314
3315    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ModelContext<T>)) {
3316        let handle = self.handle();
3317        self.app.defer(move |cx| {
3318            handle.update(cx, |model, cx| {
3319                callback(model, cx);
3320            })
3321        })
3322    }
3323
3324    pub fn emit(&mut self, payload: T::Event) {
3325        self.app.pending_effects.push_back(Effect::Event {
3326            entity_id: self.model_id,
3327            payload: Box::new(payload),
3328        });
3329    }
3330
3331    pub fn notify(&mut self) {
3332        self.app.notify_model(self.model_id);
3333    }
3334
3335    pub fn subscribe<S: Entity, F>(
3336        &mut self,
3337        handle: &ModelHandle<S>,
3338        mut callback: F,
3339    ) -> Subscription
3340    where
3341        S::Event: 'static,
3342        F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
3343    {
3344        let subscriber = self.weak_handle();
3345        self.app
3346            .subscribe_internal(handle, move |emitter, event, cx| {
3347                if let Some(subscriber) = subscriber.upgrade(cx) {
3348                    subscriber.update(cx, |subscriber, cx| {
3349                        callback(subscriber, emitter, event, cx);
3350                    });
3351                    true
3352                } else {
3353                    false
3354                }
3355            })
3356    }
3357
3358    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
3359    where
3360        S: Entity,
3361        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
3362    {
3363        let observer = self.weak_handle();
3364        self.app.observe_internal(handle, move |observed, cx| {
3365            if let Some(observer) = observer.upgrade(cx) {
3366                observer.update(cx, |observer, cx| {
3367                    callback(observer, observed, cx);
3368                });
3369                true
3370            } else {
3371                false
3372            }
3373        })
3374    }
3375
3376    pub fn observe_global<G, F>(&mut self, mut callback: F) -> Subscription
3377    where
3378        G: Any,
3379        F: 'static + FnMut(&mut T, &mut ModelContext<T>),
3380    {
3381        let observer = self.weak_handle();
3382        self.app.observe_global::<G, _>(move |cx| {
3383            if let Some(observer) = observer.upgrade(cx) {
3384                observer.update(cx, |observer, cx| callback(observer, cx));
3385            }
3386        })
3387    }
3388
3389    pub fn observe_release<S, F>(
3390        &mut self,
3391        handle: &ModelHandle<S>,
3392        mut callback: F,
3393    ) -> Subscription
3394    where
3395        S: Entity,
3396        F: 'static + FnMut(&mut T, &S, &mut ModelContext<T>),
3397    {
3398        let observer = self.weak_handle();
3399        self.app.observe_release(handle, move |released, cx| {
3400            if let Some(observer) = observer.upgrade(cx) {
3401                observer.update(cx, |observer, cx| {
3402                    callback(observer, released, cx);
3403                });
3404            }
3405        })
3406    }
3407
3408    pub fn handle(&self) -> ModelHandle<T> {
3409        ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
3410    }
3411
3412    pub fn weak_handle(&self) -> WeakModelHandle<T> {
3413        WeakModelHandle::new(self.model_id)
3414    }
3415
3416    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
3417    where
3418        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
3419        Fut: 'static + Future<Output = S>,
3420        S: 'static,
3421    {
3422        let handle = self.handle();
3423        self.app.spawn(|cx| f(handle, cx))
3424    }
3425
3426    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
3427    where
3428        F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
3429        Fut: 'static + Future<Output = S>,
3430        S: 'static,
3431    {
3432        let handle = self.weak_handle();
3433        self.app.spawn(|cx| f(handle, cx))
3434    }
3435}
3436
3437impl<M> AsRef<AppContext> for ModelContext<'_, M> {
3438    fn as_ref(&self) -> &AppContext {
3439        &self.app.cx
3440    }
3441}
3442
3443impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
3444    fn as_mut(&mut self) -> &mut MutableAppContext {
3445        self.app
3446    }
3447}
3448
3449impl<M> ReadModel for ModelContext<'_, M> {
3450    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
3451        self.app.read_model(handle)
3452    }
3453}
3454
3455impl<M> UpdateModel for ModelContext<'_, M> {
3456    fn update_model<T: Entity, V>(
3457        &mut self,
3458        handle: &ModelHandle<T>,
3459        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
3460    ) -> V {
3461        self.app.update_model(handle, update)
3462    }
3463}
3464
3465impl<M> UpgradeModelHandle for ModelContext<'_, M> {
3466    fn upgrade_model_handle<T: Entity>(
3467        &self,
3468        handle: &WeakModelHandle<T>,
3469    ) -> Option<ModelHandle<T>> {
3470        self.cx.upgrade_model_handle(handle)
3471    }
3472
3473    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
3474        self.cx.model_handle_is_upgradable(handle)
3475    }
3476
3477    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
3478        self.cx.upgrade_any_model_handle(handle)
3479    }
3480}
3481
3482impl<M> Deref for ModelContext<'_, M> {
3483    type Target = MutableAppContext;
3484
3485    fn deref(&self) -> &Self::Target {
3486        &self.app
3487    }
3488}
3489
3490impl<M> DerefMut for ModelContext<'_, M> {
3491    fn deref_mut(&mut self) -> &mut Self::Target {
3492        &mut self.app
3493    }
3494}
3495
3496pub struct ViewContext<'a, T: ?Sized> {
3497    app: &'a mut MutableAppContext,
3498    window_id: usize,
3499    view_id: usize,
3500    view_type: PhantomData<T>,
3501}
3502
3503impl<'a, T: View> ViewContext<'a, T> {
3504    fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
3505        Self {
3506            app,
3507            window_id,
3508            view_id,
3509            view_type: PhantomData,
3510        }
3511    }
3512
3513    pub fn handle(&self) -> ViewHandle<T> {
3514        ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
3515    }
3516
3517    pub fn weak_handle(&self) -> WeakViewHandle<T> {
3518        WeakViewHandle::new(self.window_id, self.view_id)
3519    }
3520
3521    pub fn window_id(&self) -> usize {
3522        self.window_id
3523    }
3524
3525    pub fn view_id(&self) -> usize {
3526        self.view_id
3527    }
3528
3529    pub fn foreground(&self) -> &Rc<executor::Foreground> {
3530        self.app.foreground()
3531    }
3532
3533    pub fn background_executor(&self) -> &Arc<executor::Background> {
3534        &self.app.cx.background
3535    }
3536
3537    pub fn platform(&self) -> Arc<dyn Platform> {
3538        self.app.platform()
3539    }
3540
3541    pub fn show_character_palette(&self) {
3542        self.app.show_character_palette(self.window_id);
3543    }
3544
3545    pub fn minimize_window(&self) {
3546        self.app.minimize_window(self.window_id)
3547    }
3548
3549    pub fn zoom_window(&self) {
3550        self.app.zoom_window(self.window_id)
3551    }
3552
3553    pub fn prompt(
3554        &self,
3555        level: PromptLevel,
3556        msg: &str,
3557        answers: &[&str],
3558    ) -> oneshot::Receiver<usize> {
3559        self.app.prompt(self.window_id, level, msg, answers)
3560    }
3561
3562    pub fn prompt_for_paths(
3563        &self,
3564        options: PathPromptOptions,
3565    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
3566        self.app.prompt_for_paths(options)
3567    }
3568
3569    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
3570        self.app.prompt_for_new_path(directory)
3571    }
3572
3573    pub fn debug_elements(&self) -> crate::json::Value {
3574        self.app.debug_elements(self.window_id).unwrap()
3575    }
3576
3577    pub fn focus<S>(&mut self, handle: S)
3578    where
3579        S: Into<AnyViewHandle>,
3580    {
3581        let handle = handle.into();
3582        self.app.focus(handle.window_id, Some(handle.view_id));
3583    }
3584
3585    pub fn focus_self(&mut self) {
3586        self.app.focus(self.window_id, Some(self.view_id));
3587    }
3588
3589    pub fn is_self_focused(&self) -> bool {
3590        self.app.focused_view_id(self.window_id) == Some(self.view_id)
3591    }
3592
3593    pub fn blur(&mut self) {
3594        self.app.focus(self.window_id, None);
3595    }
3596
3597    pub fn set_window_title(&mut self, title: &str) {
3598        let window_id = self.window_id();
3599        if let Some((_, window)) = self.presenters_and_platform_windows.get_mut(&window_id) {
3600            window.set_title(title);
3601        }
3602    }
3603
3604    pub fn set_window_edited(&mut self, edited: bool) {
3605        let window_id = self.window_id();
3606        if let Some((_, window)) = self.presenters_and_platform_windows.get_mut(&window_id) {
3607            window.set_edited(edited);
3608        }
3609    }
3610
3611    pub fn on_window_should_close<F>(&mut self, mut callback: F)
3612    where
3613        F: 'static + FnMut(&mut T, &mut ViewContext<T>) -> bool,
3614    {
3615        let window_id = self.window_id();
3616        let view = self.weak_handle();
3617        self.pending_effects
3618            .push_back(Effect::WindowShouldCloseSubscription {
3619                window_id,
3620                callback: Box::new(move |cx| {
3621                    if let Some(view) = view.upgrade(cx) {
3622                        view.update(cx, |view, cx| callback(view, cx))
3623                    } else {
3624                        true
3625                    }
3626                }),
3627            });
3628    }
3629
3630    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
3631    where
3632        S: Entity,
3633        F: FnOnce(&mut ModelContext<S>) -> S,
3634    {
3635        self.app.add_model(build_model)
3636    }
3637
3638    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
3639    where
3640        S: View,
3641        F: FnOnce(&mut ViewContext<S>) -> S,
3642    {
3643        self.app.add_view(self.window_id, build_view)
3644    }
3645
3646    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
3647    where
3648        S: View,
3649        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
3650    {
3651        self.app.add_option_view(self.window_id, build_view)
3652    }
3653
3654    pub fn replace_root_view<V, F>(&mut self, build_root_view: F) -> ViewHandle<V>
3655    where
3656        V: View,
3657        F: FnOnce(&mut ViewContext<V>) -> V,
3658    {
3659        let window_id = self.window_id;
3660        self.update(|this| {
3661            let root_view = this.add_view(window_id, build_root_view);
3662            let window = this.cx.windows.get_mut(&window_id).unwrap();
3663            window.root_view = root_view.clone().into();
3664            window.focused_view_id = Some(root_view.id());
3665            root_view
3666        })
3667    }
3668
3669    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
3670    where
3671        E: Entity,
3672        E::Event: 'static,
3673        H: Handle<E>,
3674        F: 'static + FnMut(&mut T, H, &E::Event, &mut ViewContext<T>),
3675    {
3676        let subscriber = self.weak_handle();
3677        self.app
3678            .subscribe_internal(handle, move |emitter, event, cx| {
3679                if let Some(subscriber) = subscriber.upgrade(cx) {
3680                    subscriber.update(cx, |subscriber, cx| {
3681                        callback(subscriber, emitter, event, cx);
3682                    });
3683                    true
3684                } else {
3685                    false
3686                }
3687            })
3688    }
3689
3690    pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3691    where
3692        E: Entity,
3693        H: Handle<E>,
3694        F: 'static + FnMut(&mut T, H, &mut ViewContext<T>),
3695    {
3696        let observer = self.weak_handle();
3697        self.app.observe_internal(handle, move |observed, cx| {
3698            if let Some(observer) = observer.upgrade(cx) {
3699                observer.update(cx, |observer, cx| {
3700                    callback(observer, observed, cx);
3701                });
3702                true
3703            } else {
3704                false
3705            }
3706        })
3707    }
3708
3709    pub fn observe_focus<F, V>(&mut self, handle: &ViewHandle<V>, mut callback: F) -> Subscription
3710    where
3711        F: 'static + FnMut(&mut T, ViewHandle<V>, bool, &mut ViewContext<T>),
3712        V: View,
3713    {
3714        let observer = self.weak_handle();
3715        self.app
3716            .observe_focus(handle, move |observed, focused, cx| {
3717                if let Some(observer) = observer.upgrade(cx) {
3718                    observer.update(cx, |observer, cx| {
3719                        callback(observer, observed, focused, cx);
3720                    });
3721                    true
3722                } else {
3723                    false
3724                }
3725            })
3726    }
3727
3728    pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3729    where
3730        E: Entity,
3731        H: Handle<E>,
3732        F: 'static + FnMut(&mut T, &E, &mut ViewContext<T>),
3733    {
3734        let observer = self.weak_handle();
3735        self.app.observe_release(handle, move |released, cx| {
3736            if let Some(observer) = observer.upgrade(cx) {
3737                observer.update(cx, |observer, cx| {
3738                    callback(observer, released, cx);
3739                });
3740            }
3741        })
3742    }
3743
3744    pub fn observe_actions<F>(&mut self, mut callback: F) -> Subscription
3745    where
3746        F: 'static + FnMut(&mut T, TypeId, &mut ViewContext<T>),
3747    {
3748        let observer = self.weak_handle();
3749        self.app.observe_actions(move |action_id, cx| {
3750            if let Some(observer) = observer.upgrade(cx) {
3751                observer.update(cx, |observer, cx| {
3752                    callback(observer, action_id, cx);
3753                });
3754            }
3755        })
3756    }
3757
3758    pub fn observe_window_activation<F>(&mut self, mut callback: F) -> Subscription
3759    where
3760        F: 'static + FnMut(&mut T, bool, &mut ViewContext<T>),
3761    {
3762        let observer = self.weak_handle();
3763        self.app
3764            .observe_window_activation(self.window_id(), move |active, cx| {
3765                if let Some(observer) = observer.upgrade(cx) {
3766                    observer.update(cx, |observer, cx| {
3767                        callback(observer, active, cx);
3768                    });
3769                    true
3770                } else {
3771                    false
3772                }
3773            })
3774    }
3775
3776    pub fn observe_fullscreen<F>(&mut self, mut callback: F) -> Subscription
3777    where
3778        F: 'static + FnMut(&mut T, bool, &mut ViewContext<T>),
3779    {
3780        let observer = self.weak_handle();
3781        self.app
3782            .observe_fullscreen(self.window_id(), move |active, cx| {
3783                if let Some(observer) = observer.upgrade(cx) {
3784                    observer.update(cx, |observer, cx| {
3785                        callback(observer, active, cx);
3786                    });
3787                    true
3788                } else {
3789                    false
3790                }
3791            })
3792    }
3793
3794    pub fn emit(&mut self, payload: T::Event) {
3795        self.app.pending_effects.push_back(Effect::Event {
3796            entity_id: self.view_id,
3797            payload: Box::new(payload),
3798        });
3799    }
3800
3801    pub fn notify(&mut self) {
3802        self.app.notify_view(self.window_id, self.view_id);
3803    }
3804
3805    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>)) {
3806        let handle = self.handle();
3807        self.app.defer(move |cx| {
3808            handle.update(cx, |view, cx| {
3809                callback(view, cx);
3810            })
3811        })
3812    }
3813
3814    pub fn after_window_update(
3815        &mut self,
3816        callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>),
3817    ) {
3818        let handle = self.handle();
3819        self.app.after_window_update(move |cx| {
3820            handle.update(cx, |view, cx| {
3821                callback(view, cx);
3822            })
3823        })
3824    }
3825
3826    pub fn propagate_action(&mut self) {
3827        self.app.halt_action_dispatch = false;
3828    }
3829
3830    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
3831    where
3832        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
3833        Fut: 'static + Future<Output = S>,
3834        S: 'static,
3835    {
3836        let handle = self.handle();
3837        self.app.spawn(|cx| f(handle, cx))
3838    }
3839
3840    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
3841    where
3842        F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut,
3843        Fut: 'static + Future<Output = S>,
3844        S: 'static,
3845    {
3846        let handle = self.weak_handle();
3847        self.app.spawn(|cx| f(handle, cx))
3848    }
3849}
3850
3851pub struct RenderParams {
3852    pub window_id: usize,
3853    pub view_id: usize,
3854    pub titlebar_height: f32,
3855    pub hovered_region_ids: HashSet<MouseRegionId>,
3856    pub clicked_region_id: Option<MouseRegionId>,
3857    pub right_clicked_region_id: Option<MouseRegionId>,
3858    pub refreshing: bool,
3859}
3860
3861pub struct RenderContext<'a, T: View> {
3862    pub(crate) window_id: usize,
3863    pub(crate) view_id: usize,
3864    pub(crate) view_type: PhantomData<T>,
3865    pub(crate) hovered_region_ids: HashSet<MouseRegionId>,
3866    pub(crate) clicked_region_id: Option<MouseRegionId>,
3867    pub(crate) right_clicked_region_id: Option<MouseRegionId>,
3868    pub app: &'a mut MutableAppContext,
3869    pub titlebar_height: f32,
3870    pub refreshing: bool,
3871}
3872
3873#[derive(Clone, Copy, Default)]
3874pub struct MouseState {
3875    pub hovered: bool,
3876    pub clicked: bool,
3877    pub right_clicked: bool,
3878}
3879
3880impl<'a, V: View> RenderContext<'a, V> {
3881    fn new(params: RenderParams, app: &'a mut MutableAppContext) -> Self {
3882        Self {
3883            app,
3884            window_id: params.window_id,
3885            view_id: params.view_id,
3886            view_type: PhantomData,
3887            titlebar_height: params.titlebar_height,
3888            hovered_region_ids: params.hovered_region_ids.clone(),
3889            clicked_region_id: params.clicked_region_id,
3890            right_clicked_region_id: params.right_clicked_region_id,
3891            refreshing: params.refreshing,
3892        }
3893    }
3894
3895    pub fn handle(&self) -> WeakViewHandle<V> {
3896        WeakViewHandle::new(self.window_id, self.view_id)
3897    }
3898
3899    pub fn window_id(&self) -> usize {
3900        self.window_id
3901    }
3902
3903    pub fn view_id(&self) -> usize {
3904        self.view_id
3905    }
3906
3907    pub fn mouse_state<Tag: 'static>(&self, region_id: usize) -> MouseState {
3908        let region_id = MouseRegionId {
3909            view_id: self.view_id,
3910            discriminant: (TypeId::of::<Tag>(), region_id),
3911        };
3912        MouseState {
3913            hovered: self.hovered_region_ids.contains(&region_id),
3914            clicked: self.clicked_region_id == Some(region_id),
3915            right_clicked: self.right_clicked_region_id == Some(region_id),
3916        }
3917    }
3918
3919    pub fn element_state<Tag: 'static, T: 'static + Default>(
3920        &mut self,
3921        element_id: usize,
3922    ) -> ElementStateHandle<T> {
3923        let id = ElementStateId {
3924            view_id: self.view_id(),
3925            element_id,
3926            tag: TypeId::of::<Tag>(),
3927        };
3928        self.cx
3929            .element_states
3930            .entry(id)
3931            .or_insert_with(|| Box::new(T::default()));
3932        ElementStateHandle::new(id, self.frame_count, &self.cx.ref_counts)
3933    }
3934}
3935
3936impl AsRef<AppContext> for &AppContext {
3937    fn as_ref(&self) -> &AppContext {
3938        self
3939    }
3940}
3941
3942impl<V: View> Deref for RenderContext<'_, V> {
3943    type Target = MutableAppContext;
3944
3945    fn deref(&self) -> &Self::Target {
3946        self.app
3947    }
3948}
3949
3950impl<V: View> DerefMut for RenderContext<'_, V> {
3951    fn deref_mut(&mut self) -> &mut Self::Target {
3952        self.app
3953    }
3954}
3955
3956impl<V: View> ReadModel for RenderContext<'_, V> {
3957    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
3958        self.app.read_model(handle)
3959    }
3960}
3961
3962impl<V: View> UpdateModel for RenderContext<'_, V> {
3963    fn update_model<T: Entity, O>(
3964        &mut self,
3965        handle: &ModelHandle<T>,
3966        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
3967    ) -> O {
3968        self.app.update_model(handle, update)
3969    }
3970}
3971
3972impl<V: View> ReadView for RenderContext<'_, V> {
3973    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
3974        self.app.read_view(handle)
3975    }
3976}
3977
3978impl<M> AsRef<AppContext> for ViewContext<'_, M> {
3979    fn as_ref(&self) -> &AppContext {
3980        &self.app.cx
3981    }
3982}
3983
3984impl<M> Deref for ViewContext<'_, M> {
3985    type Target = MutableAppContext;
3986
3987    fn deref(&self) -> &Self::Target {
3988        &self.app
3989    }
3990}
3991
3992impl<M> DerefMut for ViewContext<'_, M> {
3993    fn deref_mut(&mut self) -> &mut Self::Target {
3994        &mut self.app
3995    }
3996}
3997
3998impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
3999    fn as_mut(&mut self) -> &mut MutableAppContext {
4000        self.app
4001    }
4002}
4003
4004impl<V> ReadModel for ViewContext<'_, V> {
4005    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
4006        self.app.read_model(handle)
4007    }
4008}
4009
4010impl<V> UpgradeModelHandle for ViewContext<'_, V> {
4011    fn upgrade_model_handle<T: Entity>(
4012        &self,
4013        handle: &WeakModelHandle<T>,
4014    ) -> Option<ModelHandle<T>> {
4015        self.cx.upgrade_model_handle(handle)
4016    }
4017
4018    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
4019        self.cx.model_handle_is_upgradable(handle)
4020    }
4021
4022    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
4023        self.cx.upgrade_any_model_handle(handle)
4024    }
4025}
4026
4027impl<V> UpgradeViewHandle for ViewContext<'_, V> {
4028    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
4029        self.cx.upgrade_view_handle(handle)
4030    }
4031
4032    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
4033        self.cx.upgrade_any_view_handle(handle)
4034    }
4035}
4036
4037impl<V: View> UpgradeViewHandle for RenderContext<'_, V> {
4038    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
4039        self.cx.upgrade_view_handle(handle)
4040    }
4041
4042    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
4043        self.cx.upgrade_any_view_handle(handle)
4044    }
4045}
4046
4047impl<V: View> UpdateModel for ViewContext<'_, V> {
4048    fn update_model<T: Entity, O>(
4049        &mut self,
4050        handle: &ModelHandle<T>,
4051        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
4052    ) -> O {
4053        self.app.update_model(handle, update)
4054    }
4055}
4056
4057impl<V: View> ReadView for ViewContext<'_, V> {
4058    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
4059        self.app.read_view(handle)
4060    }
4061}
4062
4063impl<V: View> UpdateView for ViewContext<'_, V> {
4064    fn update_view<T, S>(
4065        &mut self,
4066        handle: &ViewHandle<T>,
4067        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
4068    ) -> S
4069    where
4070        T: View,
4071    {
4072        self.app.update_view(handle, update)
4073    }
4074}
4075
4076pub trait Handle<T> {
4077    type Weak: 'static;
4078    fn id(&self) -> usize;
4079    fn location(&self) -> EntityLocation;
4080    fn downgrade(&self) -> Self::Weak;
4081    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4082    where
4083        Self: Sized;
4084}
4085
4086pub trait WeakHandle {
4087    fn id(&self) -> usize;
4088}
4089
4090#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
4091pub enum EntityLocation {
4092    Model(usize),
4093    View(usize, usize),
4094}
4095
4096pub struct ModelHandle<T: Entity> {
4097    model_id: usize,
4098    model_type: PhantomData<T>,
4099    ref_counts: Arc<Mutex<RefCounts>>,
4100
4101    #[cfg(any(test, feature = "test-support"))]
4102    handle_id: usize,
4103}
4104
4105impl<T: Entity> ModelHandle<T> {
4106    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4107        ref_counts.lock().inc_model(model_id);
4108
4109        #[cfg(any(test, feature = "test-support"))]
4110        let handle_id = ref_counts
4111            .lock()
4112            .leak_detector
4113            .lock()
4114            .handle_created(Some(type_name::<T>()), model_id);
4115
4116        Self {
4117            model_id,
4118            model_type: PhantomData,
4119            ref_counts: ref_counts.clone(),
4120
4121            #[cfg(any(test, feature = "test-support"))]
4122            handle_id,
4123        }
4124    }
4125
4126    pub fn downgrade(&self) -> WeakModelHandle<T> {
4127        WeakModelHandle::new(self.model_id)
4128    }
4129
4130    pub fn id(&self) -> usize {
4131        self.model_id
4132    }
4133
4134    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
4135        cx.read_model(self)
4136    }
4137
4138    pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
4139    where
4140        C: ReadModelWith,
4141        F: FnOnce(&T, &AppContext) -> S,
4142    {
4143        let mut read = Some(read);
4144        cx.read_model_with(self, &mut |model, cx| {
4145            let read = read.take().unwrap();
4146            read(model, cx)
4147        })
4148    }
4149
4150    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
4151    where
4152        C: UpdateModel,
4153        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
4154    {
4155        let mut update = Some(update);
4156        cx.update_model(self, &mut |model, cx| {
4157            let update = update.take().unwrap();
4158            update(model, cx)
4159        })
4160    }
4161
4162    #[cfg(any(test, feature = "test-support"))]
4163    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
4164        let (tx, mut rx) = futures::channel::mpsc::unbounded();
4165        let mut cx = cx.cx.borrow_mut();
4166        let subscription = cx.observe(self, move |_, _| {
4167            tx.unbounded_send(()).ok();
4168        });
4169
4170        let duration = if std::env::var("CI").is_ok() {
4171            Duration::from_secs(5)
4172        } else {
4173            Duration::from_secs(1)
4174        };
4175
4176        async move {
4177            let notification = crate::util::timeout(duration, rx.next())
4178                .await
4179                .expect("next notification timed out");
4180            drop(subscription);
4181            notification.expect("model dropped while test was waiting for its next notification")
4182        }
4183    }
4184
4185    #[cfg(any(test, feature = "test-support"))]
4186    pub fn next_event(&self, cx: &TestAppContext) -> impl Future<Output = T::Event>
4187    where
4188        T::Event: Clone,
4189    {
4190        let (tx, mut rx) = futures::channel::mpsc::unbounded();
4191        let mut cx = cx.cx.borrow_mut();
4192        let subscription = cx.subscribe(self, move |_, event, _| {
4193            tx.unbounded_send(event.clone()).ok();
4194        });
4195
4196        let duration = if std::env::var("CI").is_ok() {
4197            Duration::from_secs(5)
4198        } else {
4199            Duration::from_secs(1)
4200        };
4201
4202        cx.foreground.start_waiting();
4203        async move {
4204            let event = crate::util::timeout(duration, rx.next())
4205                .await
4206                .expect("next event timed out");
4207            drop(subscription);
4208            event.expect("model dropped while test was waiting for its next event")
4209        }
4210    }
4211
4212    #[cfg(any(test, feature = "test-support"))]
4213    pub fn condition(
4214        &self,
4215        cx: &TestAppContext,
4216        mut predicate: impl FnMut(&T, &AppContext) -> bool,
4217    ) -> impl Future<Output = ()> {
4218        let (tx, mut rx) = futures::channel::mpsc::unbounded();
4219
4220        let mut cx = cx.cx.borrow_mut();
4221        let subscriptions = (
4222            cx.observe(self, {
4223                let tx = tx.clone();
4224                move |_, _| {
4225                    tx.unbounded_send(()).ok();
4226                }
4227            }),
4228            cx.subscribe(self, {
4229                let tx = tx.clone();
4230                move |_, _, _| {
4231                    tx.unbounded_send(()).ok();
4232                }
4233            }),
4234        );
4235
4236        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
4237        let handle = self.downgrade();
4238        let duration = if std::env::var("CI").is_ok() {
4239            Duration::from_secs(5)
4240        } else {
4241            Duration::from_secs(1)
4242        };
4243
4244        async move {
4245            crate::util::timeout(duration, async move {
4246                loop {
4247                    {
4248                        let cx = cx.borrow();
4249                        let cx = cx.as_ref();
4250                        if predicate(
4251                            handle
4252                                .upgrade(cx)
4253                                .expect("model dropped with pending condition")
4254                                .read(cx),
4255                            cx,
4256                        ) {
4257                            break;
4258                        }
4259                    }
4260
4261                    cx.borrow().foreground().start_waiting();
4262                    rx.next()
4263                        .await
4264                        .expect("model dropped with pending condition");
4265                    cx.borrow().foreground().finish_waiting();
4266                }
4267            })
4268            .await
4269            .expect("condition timed out");
4270            drop(subscriptions);
4271        }
4272    }
4273}
4274
4275impl<T: Entity> Clone for ModelHandle<T> {
4276    fn clone(&self) -> Self {
4277        Self::new(self.model_id, &self.ref_counts)
4278    }
4279}
4280
4281impl<T: Entity> PartialEq for ModelHandle<T> {
4282    fn eq(&self, other: &Self) -> bool {
4283        self.model_id == other.model_id
4284    }
4285}
4286
4287impl<T: Entity> Eq for ModelHandle<T> {}
4288
4289impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
4290    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
4291        self.model_id == other.model_id
4292    }
4293}
4294
4295impl<T: Entity> Hash for ModelHandle<T> {
4296    fn hash<H: Hasher>(&self, state: &mut H) {
4297        self.model_id.hash(state);
4298    }
4299}
4300
4301impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
4302    fn borrow(&self) -> &usize {
4303        &self.model_id
4304    }
4305}
4306
4307impl<T: Entity> Debug for ModelHandle<T> {
4308    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4309        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
4310            .field(&self.model_id)
4311            .finish()
4312    }
4313}
4314
4315unsafe impl<T: Entity> Send for ModelHandle<T> {}
4316unsafe impl<T: Entity> Sync for ModelHandle<T> {}
4317
4318impl<T: Entity> Drop for ModelHandle<T> {
4319    fn drop(&mut self) {
4320        let mut ref_counts = self.ref_counts.lock();
4321        ref_counts.dec_model(self.model_id);
4322
4323        #[cfg(any(test, feature = "test-support"))]
4324        ref_counts
4325            .leak_detector
4326            .lock()
4327            .handle_dropped(self.model_id, self.handle_id);
4328    }
4329}
4330
4331impl<T: Entity> Handle<T> for ModelHandle<T> {
4332    type Weak = WeakModelHandle<T>;
4333
4334    fn id(&self) -> usize {
4335        self.model_id
4336    }
4337
4338    fn location(&self) -> EntityLocation {
4339        EntityLocation::Model(self.model_id)
4340    }
4341
4342    fn downgrade(&self) -> Self::Weak {
4343        self.downgrade()
4344    }
4345
4346    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4347    where
4348        Self: Sized,
4349    {
4350        weak.upgrade(cx)
4351    }
4352}
4353
4354pub struct WeakModelHandle<T> {
4355    model_id: usize,
4356    model_type: PhantomData<T>,
4357}
4358
4359impl<T> WeakHandle for WeakModelHandle<T> {
4360    fn id(&self) -> usize {
4361        self.model_id
4362    }
4363}
4364
4365unsafe impl<T> Send for WeakModelHandle<T> {}
4366unsafe impl<T> Sync for WeakModelHandle<T> {}
4367
4368impl<T: Entity> WeakModelHandle<T> {
4369    fn new(model_id: usize) -> Self {
4370        Self {
4371            model_id,
4372            model_type: PhantomData,
4373        }
4374    }
4375
4376    pub fn id(&self) -> usize {
4377        self.model_id
4378    }
4379
4380    pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
4381        cx.model_handle_is_upgradable(self)
4382    }
4383
4384    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
4385        cx.upgrade_model_handle(self)
4386    }
4387}
4388
4389impl<T> Hash for WeakModelHandle<T> {
4390    fn hash<H: Hasher>(&self, state: &mut H) {
4391        self.model_id.hash(state)
4392    }
4393}
4394
4395impl<T> PartialEq for WeakModelHandle<T> {
4396    fn eq(&self, other: &Self) -> bool {
4397        self.model_id == other.model_id
4398    }
4399}
4400
4401impl<T> Eq for WeakModelHandle<T> {}
4402
4403impl<T> Clone for WeakModelHandle<T> {
4404    fn clone(&self) -> Self {
4405        Self {
4406            model_id: self.model_id,
4407            model_type: PhantomData,
4408        }
4409    }
4410}
4411
4412impl<T> Copy for WeakModelHandle<T> {}
4413
4414pub struct ViewHandle<T> {
4415    window_id: usize,
4416    view_id: usize,
4417    view_type: PhantomData<T>,
4418    ref_counts: Arc<Mutex<RefCounts>>,
4419    #[cfg(any(test, feature = "test-support"))]
4420    handle_id: usize,
4421}
4422
4423impl<T: View> ViewHandle<T> {
4424    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4425        ref_counts.lock().inc_view(window_id, view_id);
4426        #[cfg(any(test, feature = "test-support"))]
4427        let handle_id = ref_counts
4428            .lock()
4429            .leak_detector
4430            .lock()
4431            .handle_created(Some(type_name::<T>()), view_id);
4432
4433        Self {
4434            window_id,
4435            view_id,
4436            view_type: PhantomData,
4437            ref_counts: ref_counts.clone(),
4438
4439            #[cfg(any(test, feature = "test-support"))]
4440            handle_id,
4441        }
4442    }
4443
4444    pub fn downgrade(&self) -> WeakViewHandle<T> {
4445        WeakViewHandle::new(self.window_id, self.view_id)
4446    }
4447
4448    pub fn window_id(&self) -> usize {
4449        self.window_id
4450    }
4451
4452    pub fn id(&self) -> usize {
4453        self.view_id
4454    }
4455
4456    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
4457        cx.read_view(self)
4458    }
4459
4460    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
4461    where
4462        C: ReadViewWith,
4463        F: FnOnce(&T, &AppContext) -> S,
4464    {
4465        let mut read = Some(read);
4466        cx.read_view_with(self, &mut |view, cx| {
4467            let read = read.take().unwrap();
4468            read(view, cx)
4469        })
4470    }
4471
4472    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
4473    where
4474        C: UpdateView,
4475        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
4476    {
4477        let mut update = Some(update);
4478        cx.update_view(self, &mut |view, cx| {
4479            let update = update.take().unwrap();
4480            update(view, cx)
4481        })
4482    }
4483
4484    pub fn defer<C, F>(&self, cx: &mut C, update: F)
4485    where
4486        C: AsMut<MutableAppContext>,
4487        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
4488    {
4489        let this = self.clone();
4490        cx.as_mut().defer(move |cx| {
4491            this.update(cx, |view, cx| update(view, cx));
4492        });
4493    }
4494
4495    pub fn is_focused(&self, cx: &AppContext) -> bool {
4496        cx.focused_view_id(self.window_id)
4497            .map_or(false, |focused_id| focused_id == self.view_id)
4498    }
4499
4500    #[cfg(any(test, feature = "test-support"))]
4501    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
4502        use postage::prelude::{Sink as _, Stream as _};
4503
4504        let (mut tx, mut rx) = postage::mpsc::channel(1);
4505        let mut cx = cx.cx.borrow_mut();
4506        let subscription = cx.observe(self, move |_, _| {
4507            tx.try_send(()).ok();
4508        });
4509
4510        let duration = if std::env::var("CI").is_ok() {
4511            Duration::from_secs(5)
4512        } else {
4513            Duration::from_secs(1)
4514        };
4515
4516        async move {
4517            let notification = crate::util::timeout(duration, rx.recv())
4518                .await
4519                .expect("next notification timed out");
4520            drop(subscription);
4521            notification.expect("model dropped while test was waiting for its next notification")
4522        }
4523    }
4524
4525    #[cfg(any(test, feature = "test-support"))]
4526    pub fn condition(
4527        &self,
4528        cx: &TestAppContext,
4529        mut predicate: impl FnMut(&T, &AppContext) -> bool,
4530    ) -> impl Future<Output = ()> {
4531        use postage::prelude::{Sink as _, Stream as _};
4532
4533        let (tx, mut rx) = postage::mpsc::channel(1024);
4534        let timeout_duration = cx.condition_duration();
4535
4536        let mut cx = cx.cx.borrow_mut();
4537        let subscriptions = self.update(&mut *cx, |_, cx| {
4538            (
4539                cx.observe(self, {
4540                    let mut tx = tx.clone();
4541                    move |_, _, _| {
4542                        tx.blocking_send(()).ok();
4543                    }
4544                }),
4545                cx.subscribe(self, {
4546                    let mut tx = tx.clone();
4547                    move |_, _, _, _| {
4548                        tx.blocking_send(()).ok();
4549                    }
4550                }),
4551            )
4552        });
4553
4554        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
4555        let handle = self.downgrade();
4556
4557        async move {
4558            crate::util::timeout(timeout_duration, async move {
4559                loop {
4560                    {
4561                        let cx = cx.borrow();
4562                        let cx = cx.as_ref();
4563                        if predicate(
4564                            handle
4565                                .upgrade(cx)
4566                                .expect("view dropped with pending condition")
4567                                .read(cx),
4568                            cx,
4569                        ) {
4570                            break;
4571                        }
4572                    }
4573
4574                    cx.borrow().foreground().start_waiting();
4575                    rx.recv()
4576                        .await
4577                        .expect("view dropped with pending condition");
4578                    cx.borrow().foreground().finish_waiting();
4579                }
4580            })
4581            .await
4582            .expect("condition timed out");
4583            drop(subscriptions);
4584        }
4585    }
4586}
4587
4588impl<T: View> Clone for ViewHandle<T> {
4589    fn clone(&self) -> Self {
4590        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
4591    }
4592}
4593
4594impl<T> PartialEq for ViewHandle<T> {
4595    fn eq(&self, other: &Self) -> bool {
4596        self.window_id == other.window_id && self.view_id == other.view_id
4597    }
4598}
4599
4600impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
4601    fn eq(&self, other: &WeakViewHandle<T>) -> bool {
4602        self.window_id == other.window_id && self.view_id == other.view_id
4603    }
4604}
4605
4606impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
4607    fn eq(&self, other: &ViewHandle<T>) -> bool {
4608        self.window_id == other.window_id && self.view_id == other.view_id
4609    }
4610}
4611
4612impl<T> Eq for ViewHandle<T> {}
4613
4614impl<T> Hash for ViewHandle<T> {
4615    fn hash<H: Hasher>(&self, state: &mut H) {
4616        self.window_id.hash(state);
4617        self.view_id.hash(state);
4618    }
4619}
4620
4621impl<T> Debug for ViewHandle<T> {
4622    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4623        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
4624            .field("window_id", &self.window_id)
4625            .field("view_id", &self.view_id)
4626            .finish()
4627    }
4628}
4629
4630impl<T> Drop for ViewHandle<T> {
4631    fn drop(&mut self) {
4632        self.ref_counts
4633            .lock()
4634            .dec_view(self.window_id, self.view_id);
4635        #[cfg(any(test, feature = "test-support"))]
4636        self.ref_counts
4637            .lock()
4638            .leak_detector
4639            .lock()
4640            .handle_dropped(self.view_id, self.handle_id);
4641    }
4642}
4643
4644impl<T: View> Handle<T> for ViewHandle<T> {
4645    type Weak = WeakViewHandle<T>;
4646
4647    fn id(&self) -> usize {
4648        self.view_id
4649    }
4650
4651    fn location(&self) -> EntityLocation {
4652        EntityLocation::View(self.window_id, self.view_id)
4653    }
4654
4655    fn downgrade(&self) -> Self::Weak {
4656        self.downgrade()
4657    }
4658
4659    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4660    where
4661        Self: Sized,
4662    {
4663        weak.upgrade(cx)
4664    }
4665}
4666
4667pub struct AnyViewHandle {
4668    window_id: usize,
4669    view_id: usize,
4670    view_type: TypeId,
4671    ref_counts: Arc<Mutex<RefCounts>>,
4672
4673    #[cfg(any(test, feature = "test-support"))]
4674    handle_id: usize,
4675}
4676
4677impl AnyViewHandle {
4678    fn new(
4679        window_id: usize,
4680        view_id: usize,
4681        view_type: TypeId,
4682        ref_counts: Arc<Mutex<RefCounts>>,
4683    ) -> Self {
4684        ref_counts.lock().inc_view(window_id, view_id);
4685
4686        #[cfg(any(test, feature = "test-support"))]
4687        let handle_id = ref_counts
4688            .lock()
4689            .leak_detector
4690            .lock()
4691            .handle_created(None, view_id);
4692
4693        Self {
4694            window_id,
4695            view_id,
4696            view_type,
4697            ref_counts,
4698            #[cfg(any(test, feature = "test-support"))]
4699            handle_id,
4700        }
4701    }
4702
4703    pub fn id(&self) -> usize {
4704        self.view_id
4705    }
4706
4707    pub fn is<T: 'static>(&self) -> bool {
4708        TypeId::of::<T>() == self.view_type
4709    }
4710
4711    pub fn is_focused(&self, cx: &AppContext) -> bool {
4712        cx.focused_view_id(self.window_id)
4713            .map_or(false, |focused_id| focused_id == self.view_id)
4714    }
4715
4716    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
4717        if self.is::<T>() {
4718            let result = Some(ViewHandle {
4719                window_id: self.window_id,
4720                view_id: self.view_id,
4721                ref_counts: self.ref_counts.clone(),
4722                view_type: PhantomData,
4723                #[cfg(any(test, feature = "test-support"))]
4724                handle_id: self.handle_id,
4725            });
4726            unsafe {
4727                Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
4728            }
4729            std::mem::forget(self);
4730            result
4731        } else {
4732            None
4733        }
4734    }
4735
4736    pub fn downgrade(&self) -> AnyWeakViewHandle {
4737        AnyWeakViewHandle {
4738            window_id: self.window_id,
4739            view_id: self.view_id,
4740            view_type: self.view_type,
4741        }
4742    }
4743
4744    pub fn view_type(&self) -> TypeId {
4745        self.view_type
4746    }
4747
4748    pub fn debug_json(&self, cx: &AppContext) -> serde_json::Value {
4749        cx.views
4750            .get(&(self.window_id, self.view_id))
4751            .map_or_else(|| serde_json::Value::Null, |view| view.debug_json(cx))
4752    }
4753}
4754
4755impl Clone for AnyViewHandle {
4756    fn clone(&self) -> Self {
4757        Self::new(
4758            self.window_id,
4759            self.view_id,
4760            self.view_type,
4761            self.ref_counts.clone(),
4762        )
4763    }
4764}
4765
4766impl From<&AnyViewHandle> for AnyViewHandle {
4767    fn from(handle: &AnyViewHandle) -> Self {
4768        handle.clone()
4769    }
4770}
4771
4772impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
4773    fn from(handle: &ViewHandle<T>) -> Self {
4774        Self::new(
4775            handle.window_id,
4776            handle.view_id,
4777            TypeId::of::<T>(),
4778            handle.ref_counts.clone(),
4779        )
4780    }
4781}
4782
4783impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
4784    fn from(handle: ViewHandle<T>) -> Self {
4785        let any_handle = AnyViewHandle {
4786            window_id: handle.window_id,
4787            view_id: handle.view_id,
4788            view_type: TypeId::of::<T>(),
4789            ref_counts: handle.ref_counts.clone(),
4790            #[cfg(any(test, feature = "test-support"))]
4791            handle_id: handle.handle_id,
4792        };
4793
4794        unsafe {
4795            Arc::decrement_strong_count(Arc::as_ptr(&handle.ref_counts));
4796        }
4797        std::mem::forget(handle);
4798        any_handle
4799    }
4800}
4801
4802impl Drop for AnyViewHandle {
4803    fn drop(&mut self) {
4804        self.ref_counts
4805            .lock()
4806            .dec_view(self.window_id, self.view_id);
4807        #[cfg(any(test, feature = "test-support"))]
4808        self.ref_counts
4809            .lock()
4810            .leak_detector
4811            .lock()
4812            .handle_dropped(self.view_id, self.handle_id);
4813    }
4814}
4815
4816pub struct AnyModelHandle {
4817    model_id: usize,
4818    model_type: TypeId,
4819    ref_counts: Arc<Mutex<RefCounts>>,
4820
4821    #[cfg(any(test, feature = "test-support"))]
4822    handle_id: usize,
4823}
4824
4825impl AnyModelHandle {
4826    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
4827        ref_counts.lock().inc_model(model_id);
4828
4829        #[cfg(any(test, feature = "test-support"))]
4830        let handle_id = ref_counts
4831            .lock()
4832            .leak_detector
4833            .lock()
4834            .handle_created(None, model_id);
4835
4836        Self {
4837            model_id,
4838            model_type,
4839            ref_counts,
4840
4841            #[cfg(any(test, feature = "test-support"))]
4842            handle_id,
4843        }
4844    }
4845
4846    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
4847        if self.is::<T>() {
4848            let result = Some(ModelHandle {
4849                model_id: self.model_id,
4850                model_type: PhantomData,
4851                ref_counts: self.ref_counts.clone(),
4852
4853                #[cfg(any(test, feature = "test-support"))]
4854                handle_id: self.handle_id,
4855            });
4856            unsafe {
4857                Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
4858            }
4859            std::mem::forget(self);
4860            result
4861        } else {
4862            None
4863        }
4864    }
4865
4866    pub fn downgrade(&self) -> AnyWeakModelHandle {
4867        AnyWeakModelHandle {
4868            model_id: self.model_id,
4869            model_type: self.model_type,
4870        }
4871    }
4872
4873    pub fn is<T: Entity>(&self) -> bool {
4874        self.model_type == TypeId::of::<T>()
4875    }
4876
4877    pub fn model_type(&self) -> TypeId {
4878        self.model_type
4879    }
4880}
4881
4882impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
4883    fn from(handle: ModelHandle<T>) -> Self {
4884        Self::new(
4885            handle.model_id,
4886            TypeId::of::<T>(),
4887            handle.ref_counts.clone(),
4888        )
4889    }
4890}
4891
4892impl Clone for AnyModelHandle {
4893    fn clone(&self) -> Self {
4894        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
4895    }
4896}
4897
4898impl Drop for AnyModelHandle {
4899    fn drop(&mut self) {
4900        let mut ref_counts = self.ref_counts.lock();
4901        ref_counts.dec_model(self.model_id);
4902
4903        #[cfg(any(test, feature = "test-support"))]
4904        ref_counts
4905            .leak_detector
4906            .lock()
4907            .handle_dropped(self.model_id, self.handle_id);
4908    }
4909}
4910
4911pub struct AnyWeakModelHandle {
4912    model_id: usize,
4913    model_type: TypeId,
4914}
4915
4916impl AnyWeakModelHandle {
4917    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
4918        cx.upgrade_any_model_handle(self)
4919    }
4920}
4921
4922impl<T: Entity> From<WeakModelHandle<T>> for AnyWeakModelHandle {
4923    fn from(handle: WeakModelHandle<T>) -> Self {
4924        AnyWeakModelHandle {
4925            model_id: handle.model_id,
4926            model_type: TypeId::of::<T>(),
4927        }
4928    }
4929}
4930
4931pub struct WeakViewHandle<T> {
4932    window_id: usize,
4933    view_id: usize,
4934    view_type: PhantomData<T>,
4935}
4936
4937impl<T> WeakHandle for WeakViewHandle<T> {
4938    fn id(&self) -> usize {
4939        self.view_id
4940    }
4941}
4942
4943impl<T: View> WeakViewHandle<T> {
4944    fn new(window_id: usize, view_id: usize) -> Self {
4945        Self {
4946            window_id,
4947            view_id,
4948            view_type: PhantomData,
4949        }
4950    }
4951
4952    pub fn id(&self) -> usize {
4953        self.view_id
4954    }
4955
4956    pub fn window_id(&self) -> usize {
4957        self.window_id
4958    }
4959
4960    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
4961        cx.upgrade_view_handle(self)
4962    }
4963}
4964
4965impl<T> Clone for WeakViewHandle<T> {
4966    fn clone(&self) -> Self {
4967        Self {
4968            window_id: self.window_id,
4969            view_id: self.view_id,
4970            view_type: PhantomData,
4971        }
4972    }
4973}
4974
4975impl<T> PartialEq for WeakViewHandle<T> {
4976    fn eq(&self, other: &Self) -> bool {
4977        self.window_id == other.window_id && self.view_id == other.view_id
4978    }
4979}
4980
4981impl<T> Eq for WeakViewHandle<T> {}
4982
4983impl<T> Hash for WeakViewHandle<T> {
4984    fn hash<H: Hasher>(&self, state: &mut H) {
4985        self.window_id.hash(state);
4986        self.view_id.hash(state);
4987    }
4988}
4989
4990pub struct AnyWeakViewHandle {
4991    window_id: usize,
4992    view_id: usize,
4993    view_type: TypeId,
4994}
4995
4996impl AnyWeakViewHandle {
4997    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<AnyViewHandle> {
4998        cx.upgrade_any_view_handle(self)
4999    }
5000}
5001
5002impl<T: View> From<WeakViewHandle<T>> for AnyWeakViewHandle {
5003    fn from(handle: WeakViewHandle<T>) -> Self {
5004        AnyWeakViewHandle {
5005            window_id: handle.window_id,
5006            view_id: handle.view_id,
5007            view_type: TypeId::of::<T>(),
5008        }
5009    }
5010}
5011
5012#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
5013pub struct ElementStateId {
5014    view_id: usize,
5015    element_id: usize,
5016    tag: TypeId,
5017}
5018
5019pub struct ElementStateHandle<T> {
5020    value_type: PhantomData<T>,
5021    id: ElementStateId,
5022    ref_counts: Weak<Mutex<RefCounts>>,
5023}
5024
5025impl<T: 'static> ElementStateHandle<T> {
5026    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
5027        ref_counts.lock().inc_element_state(id, frame_id);
5028        Self {
5029            value_type: PhantomData,
5030            id,
5031            ref_counts: Arc::downgrade(ref_counts),
5032        }
5033    }
5034
5035    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
5036        cx.element_states
5037            .get(&self.id)
5038            .unwrap()
5039            .downcast_ref()
5040            .unwrap()
5041    }
5042
5043    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
5044    where
5045        C: DerefMut<Target = MutableAppContext>,
5046    {
5047        let mut element_state = cx.deref_mut().cx.element_states.remove(&self.id).unwrap();
5048        let result = f(element_state.downcast_mut().unwrap(), cx);
5049        cx.deref_mut()
5050            .cx
5051            .element_states
5052            .insert(self.id, element_state);
5053        result
5054    }
5055}
5056
5057impl<T> Drop for ElementStateHandle<T> {
5058    fn drop(&mut self) {
5059        if let Some(ref_counts) = self.ref_counts.upgrade() {
5060            ref_counts.lock().dec_element_state(self.id);
5061        }
5062    }
5063}
5064
5065#[must_use]
5066pub enum Subscription {
5067    Subscription {
5068        id: usize,
5069        entity_id: usize,
5070        subscriptions: Option<Weak<Mapping<usize, SubscriptionCallback>>>,
5071    },
5072    GlobalSubscription {
5073        id: usize,
5074        type_id: TypeId,
5075        subscriptions: Option<Weak<Mapping<TypeId, GlobalSubscriptionCallback>>>,
5076    },
5077    Observation {
5078        id: usize,
5079        entity_id: usize,
5080        observations: Option<Weak<Mapping<usize, ObservationCallback>>>,
5081    },
5082    GlobalObservation {
5083        id: usize,
5084        type_id: TypeId,
5085        observations: Option<Weak<Mapping<TypeId, GlobalObservationCallback>>>,
5086    },
5087    FocusObservation {
5088        id: usize,
5089        view_id: usize,
5090        observations: Option<Weak<Mapping<usize, FocusObservationCallback>>>,
5091    },
5092    WindowActivationObservation {
5093        id: usize,
5094        window_id: usize,
5095        observations: Option<Weak<Mapping<usize, WindowActivationCallback>>>,
5096    },
5097    WindowFullscreenObservation {
5098        id: usize,
5099        window_id: usize,
5100        observations: Option<Weak<Mapping<usize, WindowFullscreenCallback>>>,
5101    },
5102
5103    ReleaseObservation {
5104        id: usize,
5105        entity_id: usize,
5106        observations:
5107            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>>,
5108    },
5109    ActionObservation {
5110        id: usize,
5111        observations: Option<Weak<Mutex<BTreeMap<usize, ActionObservationCallback>>>>,
5112    },
5113}
5114
5115impl Subscription {
5116    pub fn detach(&mut self) {
5117        match self {
5118            Subscription::Subscription { subscriptions, .. } => {
5119                subscriptions.take();
5120            }
5121            Subscription::GlobalSubscription { subscriptions, .. } => {
5122                subscriptions.take();
5123            }
5124            Subscription::Observation { observations, .. } => {
5125                observations.take();
5126            }
5127            Subscription::GlobalObservation { observations, .. } => {
5128                observations.take();
5129            }
5130            Subscription::ReleaseObservation { observations, .. } => {
5131                observations.take();
5132            }
5133            Subscription::FocusObservation { observations, .. } => {
5134                observations.take();
5135            }
5136            Subscription::ActionObservation { observations, .. } => {
5137                observations.take();
5138            }
5139            Subscription::WindowActivationObservation { observations, .. } => {
5140                observations.take();
5141            }
5142            Subscription::WindowFullscreenObservation { observations, .. } => {
5143                observations.take();
5144            }
5145        }
5146    }
5147}
5148
5149impl Drop for Subscription {
5150    fn drop(&mut self) {
5151        match self {
5152            Subscription::Subscription {
5153                id,
5154                entity_id,
5155                subscriptions,
5156            } => {
5157                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
5158                    match subscriptions
5159                        .lock()
5160                        .entry(*entity_id)
5161                        .or_default()
5162                        .entry(*id)
5163                    {
5164                        btree_map::Entry::Vacant(entry) => {
5165                            entry.insert(None);
5166                        }
5167                        btree_map::Entry::Occupied(entry) => {
5168                            entry.remove();
5169                        }
5170                    }
5171                }
5172            }
5173            Subscription::GlobalSubscription {
5174                id,
5175                type_id,
5176                subscriptions,
5177            } => {
5178                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
5179                    match subscriptions.lock().entry(*type_id).or_default().entry(*id) {
5180                        btree_map::Entry::Vacant(entry) => {
5181                            entry.insert(None);
5182                        }
5183                        btree_map::Entry::Occupied(entry) => {
5184                            entry.remove();
5185                        }
5186                    }
5187                }
5188            }
5189            Subscription::Observation {
5190                id,
5191                entity_id,
5192                observations,
5193            } => {
5194                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5195                    match observations
5196                        .lock()
5197                        .entry(*entity_id)
5198                        .or_default()
5199                        .entry(*id)
5200                    {
5201                        btree_map::Entry::Vacant(entry) => {
5202                            entry.insert(None);
5203                        }
5204                        btree_map::Entry::Occupied(entry) => {
5205                            entry.remove();
5206                        }
5207                    }
5208                }
5209            }
5210            Subscription::GlobalObservation {
5211                id,
5212                type_id,
5213                observations,
5214            } => {
5215                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5216                    match observations.lock().entry(*type_id).or_default().entry(*id) {
5217                        collections::btree_map::Entry::Vacant(entry) => {
5218                            entry.insert(None);
5219                        }
5220                        collections::btree_map::Entry::Occupied(entry) => {
5221                            entry.remove();
5222                        }
5223                    }
5224                }
5225            }
5226            Subscription::ReleaseObservation {
5227                id,
5228                entity_id,
5229                observations,
5230            } => {
5231                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5232                    if let Some(observations) = observations.lock().get_mut(entity_id) {
5233                        observations.remove(id);
5234                    }
5235                }
5236            }
5237            Subscription::FocusObservation {
5238                id,
5239                view_id,
5240                observations,
5241            } => {
5242                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5243                    match observations.lock().entry(*view_id).or_default().entry(*id) {
5244                        btree_map::Entry::Vacant(entry) => {
5245                            entry.insert(None);
5246                        }
5247                        btree_map::Entry::Occupied(entry) => {
5248                            entry.remove();
5249                        }
5250                    }
5251                }
5252            }
5253            Subscription::ActionObservation { id, observations } => {
5254                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5255                    observations.lock().remove(&id);
5256                }
5257            }
5258            Subscription::WindowActivationObservation {
5259                id,
5260                window_id,
5261                observations,
5262            } => {
5263                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5264                    match observations
5265                        .lock()
5266                        .entry(*window_id)
5267                        .or_default()
5268                        .entry(*id)
5269                    {
5270                        btree_map::Entry::Vacant(entry) => {
5271                            entry.insert(None);
5272                        }
5273                        btree_map::Entry::Occupied(entry) => {
5274                            entry.remove();
5275                        }
5276                    }
5277                }
5278            }
5279            Subscription::WindowFullscreenObservation {
5280                id,
5281                window_id,
5282                observations,
5283            } => {
5284                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5285                    match observations
5286                        .lock()
5287                        .entry(*window_id)
5288                        .or_default()
5289                        .entry(*id)
5290                    {
5291                        btree_map::Entry::Vacant(entry) => {
5292                            entry.insert(None);
5293                        }
5294                        btree_map::Entry::Occupied(entry) => {
5295                            entry.remove();
5296                        }
5297                    }
5298                }
5299            }
5300        }
5301    }
5302}
5303
5304lazy_static! {
5305    static ref LEAK_BACKTRACE: bool =
5306        std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty());
5307}
5308
5309#[cfg(any(test, feature = "test-support"))]
5310#[derive(Default)]
5311pub struct LeakDetector {
5312    next_handle_id: usize,
5313    handle_backtraces: HashMap<
5314        usize,
5315        (
5316            Option<&'static str>,
5317            HashMap<usize, Option<backtrace::Backtrace>>,
5318        ),
5319    >,
5320}
5321
5322#[cfg(any(test, feature = "test-support"))]
5323impl LeakDetector {
5324    fn handle_created(&mut self, type_name: Option<&'static str>, entity_id: usize) -> usize {
5325        let handle_id = post_inc(&mut self.next_handle_id);
5326        let entry = self.handle_backtraces.entry(entity_id).or_default();
5327        let backtrace = if *LEAK_BACKTRACE {
5328            Some(backtrace::Backtrace::new_unresolved())
5329        } else {
5330            None
5331        };
5332        if let Some(type_name) = type_name {
5333            entry.0.get_or_insert(type_name);
5334        }
5335        entry.1.insert(handle_id, backtrace);
5336        handle_id
5337    }
5338
5339    fn handle_dropped(&mut self, entity_id: usize, handle_id: usize) {
5340        if let Some((_, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
5341            assert!(backtraces.remove(&handle_id).is_some());
5342            if backtraces.is_empty() {
5343                self.handle_backtraces.remove(&entity_id);
5344            }
5345        }
5346    }
5347
5348    pub fn assert_dropped(&mut self, entity_id: usize) {
5349        if let Some((type_name, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
5350            for trace in backtraces.values_mut() {
5351                if let Some(trace) = trace {
5352                    trace.resolve();
5353                    eprintln!("{:?}", crate::util::CwdBacktrace(trace));
5354                }
5355            }
5356
5357            let hint = if *LEAK_BACKTRACE {
5358                ""
5359            } else {
5360                " – set LEAK_BACKTRACE=1 for more information"
5361            };
5362
5363            panic!(
5364                "{} handles to {} {} still exist{}",
5365                backtraces.len(),
5366                type_name.unwrap_or("entity"),
5367                entity_id,
5368                hint
5369            );
5370        }
5371    }
5372
5373    pub fn detect(&mut self) {
5374        let mut found_leaks = false;
5375        for (id, (type_name, backtraces)) in self.handle_backtraces.iter_mut() {
5376            eprintln!(
5377                "leaked {} handles to {} {}",
5378                backtraces.len(),
5379                type_name.unwrap_or("entity"),
5380                id
5381            );
5382            for trace in backtraces.values_mut() {
5383                if let Some(trace) = trace {
5384                    trace.resolve();
5385                    eprintln!("{:?}", crate::util::CwdBacktrace(trace));
5386                }
5387            }
5388            found_leaks = true;
5389        }
5390
5391        let hint = if *LEAK_BACKTRACE {
5392            ""
5393        } else {
5394            " – set LEAK_BACKTRACE=1 for more information"
5395        };
5396        assert!(!found_leaks, "detected leaked handles{}", hint);
5397    }
5398}
5399
5400#[derive(Default)]
5401struct RefCounts {
5402    entity_counts: HashMap<usize, usize>,
5403    element_state_counts: HashMap<ElementStateId, ElementStateRefCount>,
5404    dropped_models: HashSet<usize>,
5405    dropped_views: HashSet<(usize, usize)>,
5406    dropped_element_states: HashSet<ElementStateId>,
5407
5408    #[cfg(any(test, feature = "test-support"))]
5409    leak_detector: Arc<Mutex<LeakDetector>>,
5410}
5411
5412struct ElementStateRefCount {
5413    ref_count: usize,
5414    frame_id: usize,
5415}
5416
5417impl RefCounts {
5418    fn inc_model(&mut self, model_id: usize) {
5419        match self.entity_counts.entry(model_id) {
5420            Entry::Occupied(mut entry) => {
5421                *entry.get_mut() += 1;
5422            }
5423            Entry::Vacant(entry) => {
5424                entry.insert(1);
5425                self.dropped_models.remove(&model_id);
5426            }
5427        }
5428    }
5429
5430    fn inc_view(&mut self, window_id: usize, view_id: usize) {
5431        match self.entity_counts.entry(view_id) {
5432            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
5433            Entry::Vacant(entry) => {
5434                entry.insert(1);
5435                self.dropped_views.remove(&(window_id, view_id));
5436            }
5437        }
5438    }
5439
5440    fn inc_element_state(&mut self, id: ElementStateId, frame_id: usize) {
5441        match self.element_state_counts.entry(id) {
5442            Entry::Occupied(mut entry) => {
5443                let entry = entry.get_mut();
5444                if entry.frame_id == frame_id || entry.ref_count >= 2 {
5445                    panic!("used the same element state more than once in the same frame");
5446                }
5447                entry.ref_count += 1;
5448                entry.frame_id = frame_id;
5449            }
5450            Entry::Vacant(entry) => {
5451                entry.insert(ElementStateRefCount {
5452                    ref_count: 1,
5453                    frame_id,
5454                });
5455                self.dropped_element_states.remove(&id);
5456            }
5457        }
5458    }
5459
5460    fn dec_model(&mut self, model_id: usize) {
5461        let count = self.entity_counts.get_mut(&model_id).unwrap();
5462        *count -= 1;
5463        if *count == 0 {
5464            self.entity_counts.remove(&model_id);
5465            self.dropped_models.insert(model_id);
5466        }
5467    }
5468
5469    fn dec_view(&mut self, window_id: usize, view_id: usize) {
5470        let count = self.entity_counts.get_mut(&view_id).unwrap();
5471        *count -= 1;
5472        if *count == 0 {
5473            self.entity_counts.remove(&view_id);
5474            self.dropped_views.insert((window_id, view_id));
5475        }
5476    }
5477
5478    fn dec_element_state(&mut self, id: ElementStateId) {
5479        let entry = self.element_state_counts.get_mut(&id).unwrap();
5480        entry.ref_count -= 1;
5481        if entry.ref_count == 0 {
5482            self.element_state_counts.remove(&id);
5483            self.dropped_element_states.insert(id);
5484        }
5485    }
5486
5487    fn is_entity_alive(&self, entity_id: usize) -> bool {
5488        self.entity_counts.contains_key(&entity_id)
5489    }
5490
5491    fn take_dropped(
5492        &mut self,
5493    ) -> (
5494        HashSet<usize>,
5495        HashSet<(usize, usize)>,
5496        HashSet<ElementStateId>,
5497    ) {
5498        (
5499            std::mem::take(&mut self.dropped_models),
5500            std::mem::take(&mut self.dropped_views),
5501            std::mem::take(&mut self.dropped_element_states),
5502        )
5503    }
5504}
5505
5506#[cfg(test)]
5507mod tests {
5508    use super::*;
5509    use crate::{actions, elements::*, impl_actions, MouseButton, MouseButtonEvent};
5510    use serde::Deserialize;
5511    use smol::future::poll_once;
5512    use std::{
5513        cell::Cell,
5514        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
5515    };
5516
5517    #[crate::test(self)]
5518    fn test_model_handles(cx: &mut MutableAppContext) {
5519        struct Model {
5520            other: Option<ModelHandle<Model>>,
5521            events: Vec<String>,
5522        }
5523
5524        impl Entity for Model {
5525            type Event = usize;
5526        }
5527
5528        impl Model {
5529            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
5530                if let Some(other) = other.as_ref() {
5531                    cx.observe(other, |me, _, _| {
5532                        me.events.push("notified".into());
5533                    })
5534                    .detach();
5535                    cx.subscribe(other, |me, _, event, _| {
5536                        me.events.push(format!("observed event {}", event));
5537                    })
5538                    .detach();
5539                }
5540
5541                Self {
5542                    other,
5543                    events: Vec::new(),
5544                }
5545            }
5546        }
5547
5548        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
5549        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
5550        assert_eq!(cx.cx.models.len(), 2);
5551
5552        handle_1.update(cx, |model, cx| {
5553            model.events.push("updated".into());
5554            cx.emit(1);
5555            cx.notify();
5556            cx.emit(2);
5557        });
5558        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5559        assert_eq!(
5560            handle_2.read(cx).events,
5561            vec![
5562                "observed event 1".to_string(),
5563                "notified".to_string(),
5564                "observed event 2".to_string(),
5565            ]
5566        );
5567
5568        handle_2.update(cx, |model, _| {
5569            drop(handle_1);
5570            model.other.take();
5571        });
5572
5573        assert_eq!(cx.cx.models.len(), 1);
5574        assert!(cx.subscriptions.is_empty());
5575        assert!(cx.observations.is_empty());
5576    }
5577
5578    #[crate::test(self)]
5579    fn test_model_events(cx: &mut MutableAppContext) {
5580        #[derive(Default)]
5581        struct Model {
5582            events: Vec<usize>,
5583        }
5584
5585        impl Entity for Model {
5586            type Event = usize;
5587        }
5588
5589        let handle_1 = cx.add_model(|_| Model::default());
5590        let handle_2 = cx.add_model(|_| Model::default());
5591
5592        handle_1.update(cx, |_, cx| {
5593            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
5594                model.events.push(*event);
5595
5596                cx.subscribe(&emitter, |model, _, event, _| {
5597                    model.events.push(*event * 2);
5598                })
5599                .detach();
5600            })
5601            .detach();
5602        });
5603
5604        handle_2.update(cx, |_, c| c.emit(7));
5605        assert_eq!(handle_1.read(cx).events, vec![7]);
5606
5607        handle_2.update(cx, |_, c| c.emit(5));
5608        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
5609    }
5610
5611    #[crate::test(self)]
5612    fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
5613        #[derive(Default)]
5614        struct Model;
5615
5616        impl Entity for Model {
5617            type Event = ();
5618        }
5619
5620        let events = Rc::new(RefCell::new(Vec::new()));
5621        cx.add_model(|cx| {
5622            drop(cx.subscribe(&cx.handle(), {
5623                let events = events.clone();
5624                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
5625            }));
5626            cx.subscribe(&cx.handle(), {
5627                let events = events.clone();
5628                move |_, _, _, _| events.borrow_mut().push("before emit")
5629            })
5630            .detach();
5631            cx.emit(());
5632            cx.subscribe(&cx.handle(), {
5633                let events = events.clone();
5634                move |_, _, _, _| events.borrow_mut().push("after emit")
5635            })
5636            .detach();
5637            Model
5638        });
5639        assert_eq!(*events.borrow(), ["before emit"]);
5640    }
5641
5642    #[crate::test(self)]
5643    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
5644        #[derive(Default)]
5645        struct Model {
5646            count: usize,
5647            events: Vec<usize>,
5648        }
5649
5650        impl Entity for Model {
5651            type Event = ();
5652        }
5653
5654        let handle_1 = cx.add_model(|_| Model::default());
5655        let handle_2 = cx.add_model(|_| Model::default());
5656
5657        handle_1.update(cx, |_, c| {
5658            c.observe(&handle_2, move |model, observed, c| {
5659                model.events.push(observed.read(c).count);
5660                c.observe(&observed, |model, observed, c| {
5661                    model.events.push(observed.read(c).count * 2);
5662                })
5663                .detach();
5664            })
5665            .detach();
5666        });
5667
5668        handle_2.update(cx, |model, c| {
5669            model.count = 7;
5670            c.notify()
5671        });
5672        assert_eq!(handle_1.read(cx).events, vec![7]);
5673
5674        handle_2.update(cx, |model, c| {
5675            model.count = 5;
5676            c.notify()
5677        });
5678        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
5679    }
5680
5681    #[crate::test(self)]
5682    fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
5683        #[derive(Default)]
5684        struct Model;
5685
5686        impl Entity for Model {
5687            type Event = ();
5688        }
5689
5690        let events = Rc::new(RefCell::new(Vec::new()));
5691        cx.add_model(|cx| {
5692            drop(cx.observe(&cx.handle(), {
5693                let events = events.clone();
5694                move |_, _, _| events.borrow_mut().push("dropped before flush")
5695            }));
5696            cx.observe(&cx.handle(), {
5697                let events = events.clone();
5698                move |_, _, _| events.borrow_mut().push("before notify")
5699            })
5700            .detach();
5701            cx.notify();
5702            cx.observe(&cx.handle(), {
5703                let events = events.clone();
5704                move |_, _, _| events.borrow_mut().push("after notify")
5705            })
5706            .detach();
5707            Model
5708        });
5709        assert_eq!(*events.borrow(), ["before notify"]);
5710    }
5711
5712    #[crate::test(self)]
5713    fn test_defer_and_after_window_update(cx: &mut MutableAppContext) {
5714        struct View {
5715            render_count: usize,
5716        }
5717
5718        impl Entity for View {
5719            type Event = usize;
5720        }
5721
5722        impl super::View for View {
5723            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5724                post_inc(&mut self.render_count);
5725                Empty::new().boxed()
5726            }
5727
5728            fn ui_name() -> &'static str {
5729                "View"
5730            }
5731        }
5732
5733        let (_, view) = cx.add_window(Default::default(), |_| View { render_count: 0 });
5734        let called_defer = Rc::new(AtomicBool::new(false));
5735        let called_after_window_update = Rc::new(AtomicBool::new(false));
5736
5737        view.update(cx, |this, cx| {
5738            assert_eq!(this.render_count, 1);
5739            cx.defer({
5740                let called_defer = called_defer.clone();
5741                move |this, _| {
5742                    assert_eq!(this.render_count, 1);
5743                    called_defer.store(true, SeqCst);
5744                }
5745            });
5746            cx.after_window_update({
5747                let called_after_window_update = called_after_window_update.clone();
5748                move |this, cx| {
5749                    assert_eq!(this.render_count, 2);
5750                    called_after_window_update.store(true, SeqCst);
5751                    cx.notify();
5752                }
5753            });
5754            assert!(!called_defer.load(SeqCst));
5755            assert!(!called_after_window_update.load(SeqCst));
5756            cx.notify();
5757        });
5758
5759        assert!(called_defer.load(SeqCst));
5760        assert!(called_after_window_update.load(SeqCst));
5761        assert_eq!(view.read(cx).render_count, 3);
5762    }
5763
5764    #[crate::test(self)]
5765    fn test_view_handles(cx: &mut MutableAppContext) {
5766        struct View {
5767            other: Option<ViewHandle<View>>,
5768            events: Vec<String>,
5769        }
5770
5771        impl Entity for View {
5772            type Event = usize;
5773        }
5774
5775        impl super::View for View {
5776            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5777                Empty::new().boxed()
5778            }
5779
5780            fn ui_name() -> &'static str {
5781                "View"
5782            }
5783        }
5784
5785        impl View {
5786            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
5787                if let Some(other) = other.as_ref() {
5788                    cx.subscribe(other, |me, _, event, _| {
5789                        me.events.push(format!("observed event {}", event));
5790                    })
5791                    .detach();
5792                }
5793                Self {
5794                    other,
5795                    events: Vec::new(),
5796                }
5797            }
5798        }
5799
5800        let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
5801        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
5802        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
5803        assert_eq!(cx.cx.views.len(), 3);
5804
5805        handle_1.update(cx, |view, cx| {
5806            view.events.push("updated".into());
5807            cx.emit(1);
5808            cx.emit(2);
5809        });
5810        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5811        assert_eq!(
5812            handle_2.read(cx).events,
5813            vec![
5814                "observed event 1".to_string(),
5815                "observed event 2".to_string(),
5816            ]
5817        );
5818
5819        handle_2.update(cx, |view, _| {
5820            drop(handle_1);
5821            view.other.take();
5822        });
5823
5824        assert_eq!(cx.cx.views.len(), 2);
5825        assert!(cx.subscriptions.is_empty());
5826        assert!(cx.observations.is_empty());
5827    }
5828
5829    #[crate::test(self)]
5830    fn test_add_window(cx: &mut MutableAppContext) {
5831        struct View {
5832            mouse_down_count: Arc<AtomicUsize>,
5833        }
5834
5835        impl Entity for View {
5836            type Event = ();
5837        }
5838
5839        impl super::View for View {
5840            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5841                let mouse_down_count = self.mouse_down_count.clone();
5842                EventHandler::new(Empty::new().boxed())
5843                    .on_mouse_down(move |_| {
5844                        mouse_down_count.fetch_add(1, SeqCst);
5845                        true
5846                    })
5847                    .boxed()
5848            }
5849
5850            fn ui_name() -> &'static str {
5851                "View"
5852            }
5853        }
5854
5855        let mouse_down_count = Arc::new(AtomicUsize::new(0));
5856        let (window_id, _) = cx.add_window(Default::default(), |_| View {
5857            mouse_down_count: mouse_down_count.clone(),
5858        });
5859        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
5860        // Ensure window's root element is in a valid lifecycle state.
5861        presenter.borrow_mut().dispatch_event(
5862            Event::MouseDown(MouseButtonEvent {
5863                position: Default::default(),
5864                button: MouseButton::Left,
5865                ctrl: false,
5866                alt: false,
5867                shift: false,
5868                cmd: false,
5869                click_count: 1,
5870            }),
5871            cx,
5872        );
5873        assert_eq!(mouse_down_count.load(SeqCst), 1);
5874    }
5875
5876    #[crate::test(self)]
5877    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
5878        struct Model {
5879            released: Rc<Cell<bool>>,
5880        }
5881
5882        struct View {
5883            released: Rc<Cell<bool>>,
5884        }
5885
5886        impl Entity for Model {
5887            type Event = ();
5888
5889            fn release(&mut self, _: &mut MutableAppContext) {
5890                self.released.set(true);
5891            }
5892        }
5893
5894        impl Entity for View {
5895            type Event = ();
5896
5897            fn release(&mut self, _: &mut MutableAppContext) {
5898                self.released.set(true);
5899            }
5900        }
5901
5902        impl super::View for View {
5903            fn ui_name() -> &'static str {
5904                "View"
5905            }
5906
5907            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5908                Empty::new().boxed()
5909            }
5910        }
5911
5912        let model_released = Rc::new(Cell::new(false));
5913        let model_release_observed = Rc::new(Cell::new(false));
5914        let view_released = Rc::new(Cell::new(false));
5915        let view_release_observed = Rc::new(Cell::new(false));
5916
5917        let model = cx.add_model(|_| Model {
5918            released: model_released.clone(),
5919        });
5920        let (window_id, view) = cx.add_window(Default::default(), |_| View {
5921            released: view_released.clone(),
5922        });
5923        assert!(!model_released.get());
5924        assert!(!view_released.get());
5925
5926        cx.observe_release(&model, {
5927            let model_release_observed = model_release_observed.clone();
5928            move |_, _| model_release_observed.set(true)
5929        })
5930        .detach();
5931        cx.observe_release(&view, {
5932            let view_release_observed = view_release_observed.clone();
5933            move |_, _| view_release_observed.set(true)
5934        })
5935        .detach();
5936
5937        cx.update(move |_| {
5938            drop(model);
5939        });
5940        assert!(model_released.get());
5941        assert!(model_release_observed.get());
5942
5943        drop(view);
5944        cx.remove_window(window_id);
5945        assert!(view_released.get());
5946        assert!(view_release_observed.get());
5947    }
5948
5949    #[crate::test(self)]
5950    fn test_view_events(cx: &mut MutableAppContext) {
5951        #[derive(Default)]
5952        struct View {
5953            events: Vec<usize>,
5954        }
5955
5956        impl Entity for View {
5957            type Event = usize;
5958        }
5959
5960        impl super::View for View {
5961            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5962                Empty::new().boxed()
5963            }
5964
5965            fn ui_name() -> &'static str {
5966                "View"
5967            }
5968        }
5969
5970        struct Model;
5971
5972        impl Entity for Model {
5973            type Event = usize;
5974        }
5975
5976        let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
5977        let handle_2 = cx.add_view(window_id, |_| View::default());
5978        let handle_3 = cx.add_model(|_| Model);
5979
5980        handle_1.update(cx, |_, cx| {
5981            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
5982                me.events.push(*event);
5983
5984                cx.subscribe(&emitter, |me, _, event, _| {
5985                    me.events.push(*event * 2);
5986                })
5987                .detach();
5988            })
5989            .detach();
5990
5991            cx.subscribe(&handle_3, |me, _, event, _| {
5992                me.events.push(*event);
5993            })
5994            .detach();
5995        });
5996
5997        handle_2.update(cx, |_, c| c.emit(7));
5998        assert_eq!(handle_1.read(cx).events, vec![7]);
5999
6000        handle_2.update(cx, |_, c| c.emit(5));
6001        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
6002
6003        handle_3.update(cx, |_, c| c.emit(9));
6004        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
6005    }
6006
6007    #[crate::test(self)]
6008    fn test_global_events(cx: &mut MutableAppContext) {
6009        #[derive(Clone, Debug, Eq, PartialEq)]
6010        struct GlobalEvent(u64);
6011
6012        let events = Rc::new(RefCell::new(Vec::new()));
6013        let first_subscription;
6014        let second_subscription;
6015
6016        {
6017            let events = events.clone();
6018            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
6019                events.borrow_mut().push(("First", e.clone()));
6020            });
6021        }
6022
6023        {
6024            let events = events.clone();
6025            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
6026                events.borrow_mut().push(("Second", e.clone()));
6027            });
6028        }
6029
6030        cx.update(|cx| {
6031            cx.emit_global(GlobalEvent(1));
6032            cx.emit_global(GlobalEvent(2));
6033        });
6034
6035        drop(first_subscription);
6036
6037        cx.update(|cx| {
6038            cx.emit_global(GlobalEvent(3));
6039        });
6040
6041        drop(second_subscription);
6042
6043        cx.update(|cx| {
6044            cx.emit_global(GlobalEvent(4));
6045        });
6046
6047        assert_eq!(
6048            &*events.borrow(),
6049            &[
6050                ("First", GlobalEvent(1)),
6051                ("Second", GlobalEvent(1)),
6052                ("First", GlobalEvent(2)),
6053                ("Second", GlobalEvent(2)),
6054                ("Second", GlobalEvent(3)),
6055            ]
6056        );
6057    }
6058
6059    #[crate::test(self)]
6060    fn test_global_events_emitted_before_subscription_in_same_update_cycle(
6061        cx: &mut MutableAppContext,
6062    ) {
6063        let events = Rc::new(RefCell::new(Vec::new()));
6064        cx.update(|cx| {
6065            {
6066                let events = events.clone();
6067                drop(cx.subscribe_global(move |_: &(), _| {
6068                    events.borrow_mut().push("dropped before emit");
6069                }));
6070            }
6071
6072            {
6073                let events = events.clone();
6074                cx.subscribe_global(move |_: &(), _| {
6075                    events.borrow_mut().push("before emit");
6076                })
6077                .detach();
6078            }
6079
6080            cx.emit_global(());
6081
6082            {
6083                let events = events.clone();
6084                cx.subscribe_global(move |_: &(), _| {
6085                    events.borrow_mut().push("after emit");
6086                })
6087                .detach();
6088            }
6089        });
6090
6091        assert_eq!(*events.borrow(), ["before emit"]);
6092    }
6093
6094    #[crate::test(self)]
6095    fn test_global_nested_events(cx: &mut MutableAppContext) {
6096        #[derive(Clone, Debug, Eq, PartialEq)]
6097        struct GlobalEvent(u64);
6098
6099        let events = Rc::new(RefCell::new(Vec::new()));
6100
6101        {
6102            let events = events.clone();
6103            cx.subscribe_global(move |e: &GlobalEvent, cx| {
6104                events.borrow_mut().push(("Outer", e.clone()));
6105
6106                if e.0 == 1 {
6107                    let events = events.clone();
6108                    cx.subscribe_global(move |e: &GlobalEvent, _| {
6109                        events.borrow_mut().push(("Inner", e.clone()));
6110                    })
6111                    .detach();
6112                }
6113            })
6114            .detach();
6115        }
6116
6117        cx.update(|cx| {
6118            cx.emit_global(GlobalEvent(1));
6119            cx.emit_global(GlobalEvent(2));
6120            cx.emit_global(GlobalEvent(3));
6121        });
6122        cx.update(|cx| {
6123            cx.emit_global(GlobalEvent(4));
6124        });
6125
6126        assert_eq!(
6127            &*events.borrow(),
6128            &[
6129                ("Outer", GlobalEvent(1)),
6130                ("Outer", GlobalEvent(2)),
6131                ("Outer", GlobalEvent(3)),
6132                ("Outer", GlobalEvent(4)),
6133                ("Inner", GlobalEvent(4)),
6134            ]
6135        );
6136    }
6137
6138    #[crate::test(self)]
6139    fn test_global(cx: &mut MutableAppContext) {
6140        type Global = usize;
6141
6142        let observation_count = Rc::new(RefCell::new(0));
6143        let subscription = cx.observe_global::<Global, _>({
6144            let observation_count = observation_count.clone();
6145            move |_| {
6146                *observation_count.borrow_mut() += 1;
6147            }
6148        });
6149
6150        assert!(!cx.has_global::<Global>());
6151        assert_eq!(cx.default_global::<Global>(), &0);
6152        assert_eq!(*observation_count.borrow(), 1);
6153        assert!(cx.has_global::<Global>());
6154        assert_eq!(
6155            cx.update_global::<Global, _, _>(|global, _| {
6156                *global = 1;
6157                "Update Result"
6158            }),
6159            "Update Result"
6160        );
6161        assert_eq!(*observation_count.borrow(), 2);
6162        assert_eq!(cx.global::<Global>(), &1);
6163
6164        drop(subscription);
6165        cx.update_global::<Global, _, _>(|global, _| {
6166            *global = 2;
6167        });
6168        assert_eq!(*observation_count.borrow(), 2);
6169
6170        type OtherGlobal = f32;
6171
6172        let observation_count = Rc::new(RefCell::new(0));
6173        cx.observe_global::<OtherGlobal, _>({
6174            let observation_count = observation_count.clone();
6175            move |_| {
6176                *observation_count.borrow_mut() += 1;
6177            }
6178        })
6179        .detach();
6180
6181        assert_eq!(
6182            cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
6183                assert_eq!(global, &0.0);
6184                *global = 2.0;
6185                "Default update result"
6186            }),
6187            "Default update result"
6188        );
6189        assert_eq!(cx.global::<OtherGlobal>(), &2.0);
6190        assert_eq!(*observation_count.borrow(), 1);
6191    }
6192
6193    #[crate::test(self)]
6194    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
6195        struct View;
6196
6197        impl Entity for View {
6198            type Event = ();
6199        }
6200
6201        impl super::View for View {
6202            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6203                Empty::new().boxed()
6204            }
6205
6206            fn ui_name() -> &'static str {
6207                "View"
6208            }
6209        }
6210
6211        struct Model;
6212
6213        impl Entity for Model {
6214            type Event = ();
6215        }
6216
6217        let (window_id, _) = cx.add_window(Default::default(), |_| View);
6218        let observing_view = cx.add_view(window_id, |_| View);
6219        let emitting_view = cx.add_view(window_id, |_| View);
6220        let observing_model = cx.add_model(|_| Model);
6221        let observed_model = cx.add_model(|_| Model);
6222
6223        observing_view.update(cx, |_, cx| {
6224            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
6225            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
6226        });
6227        observing_model.update(cx, |_, cx| {
6228            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
6229        });
6230
6231        cx.update(|_| {
6232            drop(observing_view);
6233            drop(observing_model);
6234        });
6235
6236        emitting_view.update(cx, |_, cx| cx.emit(()));
6237        observed_model.update(cx, |_, cx| cx.emit(()));
6238    }
6239
6240    #[crate::test(self)]
6241    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
6242        #[derive(Default)]
6243        struct TestView;
6244
6245        impl Entity for TestView {
6246            type Event = ();
6247        }
6248
6249        impl View for TestView {
6250            fn ui_name() -> &'static str {
6251                "TestView"
6252            }
6253
6254            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6255                Empty::new().boxed()
6256            }
6257        }
6258
6259        let events = Rc::new(RefCell::new(Vec::new()));
6260        cx.add_window(Default::default(), |cx| {
6261            drop(cx.subscribe(&cx.handle(), {
6262                let events = events.clone();
6263                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
6264            }));
6265            cx.subscribe(&cx.handle(), {
6266                let events = events.clone();
6267                move |_, _, _, _| events.borrow_mut().push("before emit")
6268            })
6269            .detach();
6270            cx.emit(());
6271            cx.subscribe(&cx.handle(), {
6272                let events = events.clone();
6273                move |_, _, _, _| events.borrow_mut().push("after emit")
6274            })
6275            .detach();
6276            TestView
6277        });
6278        assert_eq!(*events.borrow(), ["before emit"]);
6279    }
6280
6281    #[crate::test(self)]
6282    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
6283        #[derive(Default)]
6284        struct View {
6285            events: Vec<usize>,
6286        }
6287
6288        impl Entity for View {
6289            type Event = usize;
6290        }
6291
6292        impl super::View for View {
6293            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6294                Empty::new().boxed()
6295            }
6296
6297            fn ui_name() -> &'static str {
6298                "View"
6299            }
6300        }
6301
6302        #[derive(Default)]
6303        struct Model {
6304            count: usize,
6305        }
6306
6307        impl Entity for Model {
6308            type Event = ();
6309        }
6310
6311        let (_, view) = cx.add_window(Default::default(), |_| View::default());
6312        let model = cx.add_model(|_| Model::default());
6313
6314        view.update(cx, |_, c| {
6315            c.observe(&model, |me, observed, c| {
6316                me.events.push(observed.read(c).count)
6317            })
6318            .detach();
6319        });
6320
6321        model.update(cx, |model, c| {
6322            model.count = 11;
6323            c.notify();
6324        });
6325        assert_eq!(view.read(cx).events, vec![11]);
6326    }
6327
6328    #[crate::test(self)]
6329    fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
6330        #[derive(Default)]
6331        struct TestView;
6332
6333        impl Entity for TestView {
6334            type Event = ();
6335        }
6336
6337        impl View for TestView {
6338            fn ui_name() -> &'static str {
6339                "TestView"
6340            }
6341
6342            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6343                Empty::new().boxed()
6344            }
6345        }
6346
6347        let events = Rc::new(RefCell::new(Vec::new()));
6348        cx.add_window(Default::default(), |cx| {
6349            drop(cx.observe(&cx.handle(), {
6350                let events = events.clone();
6351                move |_, _, _| events.borrow_mut().push("dropped before flush")
6352            }));
6353            cx.observe(&cx.handle(), {
6354                let events = events.clone();
6355                move |_, _, _| events.borrow_mut().push("before notify")
6356            })
6357            .detach();
6358            cx.notify();
6359            cx.observe(&cx.handle(), {
6360                let events = events.clone();
6361                move |_, _, _| events.borrow_mut().push("after notify")
6362            })
6363            .detach();
6364            TestView
6365        });
6366        assert_eq!(*events.borrow(), ["before notify"]);
6367    }
6368
6369    #[crate::test(self)]
6370    fn test_dropping_observers(cx: &mut MutableAppContext) {
6371        struct View;
6372
6373        impl Entity for View {
6374            type Event = ();
6375        }
6376
6377        impl super::View for View {
6378            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6379                Empty::new().boxed()
6380            }
6381
6382            fn ui_name() -> &'static str {
6383                "View"
6384            }
6385        }
6386
6387        struct Model;
6388
6389        impl Entity for Model {
6390            type Event = ();
6391        }
6392
6393        let (window_id, _) = cx.add_window(Default::default(), |_| View);
6394        let observing_view = cx.add_view(window_id, |_| View);
6395        let observing_model = cx.add_model(|_| Model);
6396        let observed_model = cx.add_model(|_| Model);
6397
6398        observing_view.update(cx, |_, cx| {
6399            cx.observe(&observed_model, |_, _, _| {}).detach();
6400        });
6401        observing_model.update(cx, |_, cx| {
6402            cx.observe(&observed_model, |_, _, _| {}).detach();
6403        });
6404
6405        cx.update(|_| {
6406            drop(observing_view);
6407            drop(observing_model);
6408        });
6409
6410        observed_model.update(cx, |_, cx| cx.notify());
6411    }
6412
6413    #[crate::test(self)]
6414    fn test_dropping_subscriptions_during_callback(cx: &mut MutableAppContext) {
6415        struct Model;
6416
6417        impl Entity for Model {
6418            type Event = u64;
6419        }
6420
6421        // Events
6422        let observing_model = cx.add_model(|_| Model);
6423        let observed_model = cx.add_model(|_| Model);
6424
6425        let events = Rc::new(RefCell::new(Vec::new()));
6426
6427        observing_model.update(cx, |_, cx| {
6428            let events = events.clone();
6429            let subscription = Rc::new(RefCell::new(None));
6430            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
6431                let subscription = subscription.clone();
6432                move |_, _, e, _| {
6433                    subscription.borrow_mut().take();
6434                    events.borrow_mut().push(e.clone());
6435                }
6436            }));
6437        });
6438
6439        observed_model.update(cx, |_, cx| {
6440            cx.emit(1);
6441            cx.emit(2);
6442        });
6443
6444        assert_eq!(*events.borrow(), [1]);
6445
6446        // Global Events
6447        #[derive(Clone, Debug, Eq, PartialEq)]
6448        struct GlobalEvent(u64);
6449
6450        let events = Rc::new(RefCell::new(Vec::new()));
6451
6452        {
6453            let events = events.clone();
6454            let subscription = Rc::new(RefCell::new(None));
6455            *subscription.borrow_mut() = Some(cx.subscribe_global({
6456                let subscription = subscription.clone();
6457                move |e: &GlobalEvent, _| {
6458                    subscription.borrow_mut().take();
6459                    events.borrow_mut().push(e.clone());
6460                }
6461            }));
6462        }
6463
6464        cx.update(|cx| {
6465            cx.emit_global(GlobalEvent(1));
6466            cx.emit_global(GlobalEvent(2));
6467        });
6468
6469        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
6470
6471        // Model Observation
6472        let observing_model = cx.add_model(|_| Model);
6473        let observed_model = cx.add_model(|_| Model);
6474
6475        let observation_count = Rc::new(RefCell::new(0));
6476
6477        observing_model.update(cx, |_, cx| {
6478            let observation_count = observation_count.clone();
6479            let subscription = Rc::new(RefCell::new(None));
6480            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
6481                let subscription = subscription.clone();
6482                move |_, _, _| {
6483                    subscription.borrow_mut().take();
6484                    *observation_count.borrow_mut() += 1;
6485                }
6486            }));
6487        });
6488
6489        observed_model.update(cx, |_, cx| {
6490            cx.notify();
6491        });
6492
6493        observed_model.update(cx, |_, cx| {
6494            cx.notify();
6495        });
6496
6497        assert_eq!(*observation_count.borrow(), 1);
6498
6499        // View Observation
6500        struct View;
6501
6502        impl Entity for View {
6503            type Event = ();
6504        }
6505
6506        impl super::View for View {
6507            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6508                Empty::new().boxed()
6509            }
6510
6511            fn ui_name() -> &'static str {
6512                "View"
6513            }
6514        }
6515
6516        let (window_id, _) = cx.add_window(Default::default(), |_| View);
6517        let observing_view = cx.add_view(window_id, |_| View);
6518        let observed_view = cx.add_view(window_id, |_| View);
6519
6520        let observation_count = Rc::new(RefCell::new(0));
6521        observing_view.update(cx, |_, cx| {
6522            let observation_count = observation_count.clone();
6523            let subscription = Rc::new(RefCell::new(None));
6524            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
6525                let subscription = subscription.clone();
6526                move |_, _, _| {
6527                    subscription.borrow_mut().take();
6528                    *observation_count.borrow_mut() += 1;
6529                }
6530            }));
6531        });
6532
6533        observed_view.update(cx, |_, cx| {
6534            cx.notify();
6535        });
6536
6537        observed_view.update(cx, |_, cx| {
6538            cx.notify();
6539        });
6540
6541        assert_eq!(*observation_count.borrow(), 1);
6542
6543        // Global Observation
6544        let observation_count = Rc::new(RefCell::new(0));
6545        let subscription = Rc::new(RefCell::new(None));
6546        *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
6547            let observation_count = observation_count.clone();
6548            let subscription = subscription.clone();
6549            move |_| {
6550                subscription.borrow_mut().take();
6551                *observation_count.borrow_mut() += 1;
6552            }
6553        }));
6554
6555        cx.default_global::<()>();
6556        cx.set_global(());
6557        assert_eq!(*observation_count.borrow(), 1);
6558    }
6559
6560    #[crate::test(self)]
6561    fn test_focus(cx: &mut MutableAppContext) {
6562        struct View {
6563            name: String,
6564            events: Arc<Mutex<Vec<String>>>,
6565        }
6566
6567        impl Entity for View {
6568            type Event = ();
6569        }
6570
6571        impl super::View for View {
6572            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6573                Empty::new().boxed()
6574            }
6575
6576            fn ui_name() -> &'static str {
6577                "View"
6578            }
6579
6580            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
6581                self.events.lock().push(format!("{} focused", &self.name));
6582            }
6583
6584            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
6585                self.events.lock().push(format!("{} blurred", &self.name));
6586            }
6587        }
6588
6589        let view_events: Arc<Mutex<Vec<String>>> = Default::default();
6590        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
6591            events: view_events.clone(),
6592            name: "view 1".to_string(),
6593        });
6594        let view_2 = cx.add_view(window_id, |_| View {
6595            events: view_events.clone(),
6596            name: "view 2".to_string(),
6597        });
6598
6599        let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
6600        view_1.update(cx, |_, cx| {
6601            cx.observe_focus(&view_2, {
6602                let observed_events = observed_events.clone();
6603                move |this, view, focused, cx| {
6604                    let label = if focused { "focus" } else { "blur" };
6605                    observed_events.lock().push(format!(
6606                        "{} observed {}'s {}",
6607                        this.name,
6608                        view.read(cx).name,
6609                        label
6610                    ))
6611                }
6612            })
6613            .detach();
6614        });
6615        view_2.update(cx, |_, cx| {
6616            cx.observe_focus(&view_1, {
6617                let observed_events = observed_events.clone();
6618                move |this, view, focused, cx| {
6619                    let label = if focused { "focus" } else { "blur" };
6620                    observed_events.lock().push(format!(
6621                        "{} observed {}'s {}",
6622                        this.name,
6623                        view.read(cx).name,
6624                        label
6625                    ))
6626                }
6627            })
6628            .detach();
6629        });
6630        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6631        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6632
6633        view_1.update(cx, |_, cx| {
6634            // Ensure only the latest focus is honored.
6635            cx.focus(&view_2);
6636            cx.focus(&view_1);
6637            cx.focus(&view_2);
6638        });
6639        assert_eq!(
6640            mem::take(&mut *view_events.lock()),
6641            ["view 1 blurred", "view 2 focused"],
6642        );
6643        assert_eq!(
6644            mem::take(&mut *observed_events.lock()),
6645            [
6646                "view 2 observed view 1's blur",
6647                "view 1 observed view 2's focus"
6648            ]
6649        );
6650
6651        view_1.update(cx, |_, cx| cx.focus(&view_1));
6652        assert_eq!(
6653            mem::take(&mut *view_events.lock()),
6654            ["view 2 blurred", "view 1 focused"],
6655        );
6656        assert_eq!(
6657            mem::take(&mut *observed_events.lock()),
6658            [
6659                "view 1 observed view 2's blur",
6660                "view 2 observed view 1's focus"
6661            ]
6662        );
6663
6664        view_1.update(cx, |_, cx| cx.focus(&view_2));
6665        assert_eq!(
6666            mem::take(&mut *view_events.lock()),
6667            ["view 1 blurred", "view 2 focused"],
6668        );
6669        assert_eq!(
6670            mem::take(&mut *observed_events.lock()),
6671            [
6672                "view 2 observed view 1's blur",
6673                "view 1 observed view 2's focus"
6674            ]
6675        );
6676
6677        view_1.update(cx, |_, _| drop(view_2));
6678        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6679        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6680    }
6681
6682    #[crate::test(self)]
6683    fn test_deserialize_actions(cx: &mut MutableAppContext) {
6684        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6685        pub struct ComplexAction {
6686            arg: String,
6687            count: usize,
6688        }
6689
6690        actions!(test::something, [SimpleAction]);
6691        impl_actions!(test::something, [ComplexAction]);
6692
6693        cx.add_global_action(move |_: &SimpleAction, _: &mut MutableAppContext| {});
6694        cx.add_global_action(move |_: &ComplexAction, _: &mut MutableAppContext| {});
6695
6696        let action1 = cx
6697            .deserialize_action(
6698                "test::something::ComplexAction",
6699                Some(r#"{"arg": "a", "count": 5}"#),
6700            )
6701            .unwrap();
6702        let action2 = cx
6703            .deserialize_action("test::something::SimpleAction", None)
6704            .unwrap();
6705        assert_eq!(
6706            action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
6707            &ComplexAction {
6708                arg: "a".to_string(),
6709                count: 5,
6710            }
6711        );
6712        assert_eq!(
6713            action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
6714            &SimpleAction
6715        );
6716    }
6717
6718    #[crate::test(self)]
6719    fn test_dispatch_action(cx: &mut MutableAppContext) {
6720        struct ViewA {
6721            id: usize,
6722        }
6723
6724        impl Entity for ViewA {
6725            type Event = ();
6726        }
6727
6728        impl View for ViewA {
6729            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6730                Empty::new().boxed()
6731            }
6732
6733            fn ui_name() -> &'static str {
6734                "View"
6735            }
6736        }
6737
6738        struct ViewB {
6739            id: usize,
6740        }
6741
6742        impl Entity for ViewB {
6743            type Event = ();
6744        }
6745
6746        impl View for ViewB {
6747            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6748                Empty::new().boxed()
6749            }
6750
6751            fn ui_name() -> &'static str {
6752                "View"
6753            }
6754        }
6755
6756        #[derive(Clone, Default, Deserialize, PartialEq)]
6757        pub struct Action(pub String);
6758
6759        impl_actions!(test, [Action]);
6760
6761        let actions = Rc::new(RefCell::new(Vec::new()));
6762
6763        cx.add_global_action({
6764            let actions = actions.clone();
6765            move |_: &Action, _: &mut MutableAppContext| {
6766                actions.borrow_mut().push("global".to_string());
6767            }
6768        });
6769
6770        cx.add_action({
6771            let actions = actions.clone();
6772            move |view: &mut ViewA, action: &Action, cx| {
6773                assert_eq!(action.0, "bar");
6774                cx.propagate_action();
6775                actions.borrow_mut().push(format!("{} a", view.id));
6776            }
6777        });
6778
6779        cx.add_action({
6780            let actions = actions.clone();
6781            move |view: &mut ViewA, _: &Action, cx| {
6782                if view.id != 1 {
6783                    cx.add_view(|cx| {
6784                        cx.propagate_action(); // Still works on a nested ViewContext
6785                        ViewB { id: 5 }
6786                    });
6787                }
6788                actions.borrow_mut().push(format!("{} b", view.id));
6789            }
6790        });
6791
6792        cx.add_action({
6793            let actions = actions.clone();
6794            move |view: &mut ViewB, _: &Action, cx| {
6795                cx.propagate_action();
6796                actions.borrow_mut().push(format!("{} c", view.id));
6797            }
6798        });
6799
6800        cx.add_action({
6801            let actions = actions.clone();
6802            move |view: &mut ViewB, _: &Action, cx| {
6803                cx.propagate_action();
6804                actions.borrow_mut().push(format!("{} d", view.id));
6805            }
6806        });
6807
6808        cx.capture_action({
6809            let actions = actions.clone();
6810            move |view: &mut ViewA, _: &Action, cx| {
6811                cx.propagate_action();
6812                actions.borrow_mut().push(format!("{} capture", view.id));
6813            }
6814        });
6815
6816        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
6817        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
6818        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
6819        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
6820
6821        let observed_actions = Rc::new(RefCell::new(Vec::new()));
6822        cx.observe_actions({
6823            let observed_actions = observed_actions.clone();
6824            move |action_id, _| observed_actions.borrow_mut().push(action_id)
6825        })
6826        .detach();
6827
6828        cx.dispatch_action(
6829            window_id,
6830            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
6831            &Action("bar".to_string()),
6832        );
6833
6834        assert_eq!(
6835            *actions.borrow(),
6836            vec![
6837                "1 capture",
6838                "3 capture",
6839                "4 d",
6840                "4 c",
6841                "3 b",
6842                "3 a",
6843                "2 d",
6844                "2 c",
6845                "1 b"
6846            ]
6847        );
6848        assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
6849
6850        // Remove view_1, which doesn't propagate the action
6851        actions.borrow_mut().clear();
6852        cx.dispatch_action(
6853            window_id,
6854            vec![view_2.id(), view_3.id(), view_4.id()],
6855            &Action("bar".to_string()),
6856        );
6857
6858        assert_eq!(
6859            *actions.borrow(),
6860            vec![
6861                "3 capture",
6862                "4 d",
6863                "4 c",
6864                "3 b",
6865                "3 a",
6866                "2 d",
6867                "2 c",
6868                "global"
6869            ]
6870        );
6871        assert_eq!(
6872            *observed_actions.borrow(),
6873            [Action::default().id(), Action::default().id()]
6874        );
6875    }
6876
6877    #[crate::test(self)]
6878    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
6879        #[derive(Clone, Deserialize, PartialEq)]
6880        pub struct Action(String);
6881
6882        impl_actions!(test, [Action]);
6883
6884        struct View {
6885            id: usize,
6886            keymap_context: keymap::Context,
6887        }
6888
6889        impl Entity for View {
6890            type Event = ();
6891        }
6892
6893        impl super::View for View {
6894            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6895                Empty::new().boxed()
6896            }
6897
6898            fn ui_name() -> &'static str {
6899                "View"
6900            }
6901
6902            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
6903                self.keymap_context.clone()
6904            }
6905        }
6906
6907        impl View {
6908            fn new(id: usize) -> Self {
6909                View {
6910                    id,
6911                    keymap_context: keymap::Context::default(),
6912                }
6913            }
6914        }
6915
6916        let mut view_1 = View::new(1);
6917        let mut view_2 = View::new(2);
6918        let mut view_3 = View::new(3);
6919        view_1.keymap_context.set.insert("a".into());
6920        view_2.keymap_context.set.insert("a".into());
6921        view_2.keymap_context.set.insert("b".into());
6922        view_3.keymap_context.set.insert("a".into());
6923        view_3.keymap_context.set.insert("b".into());
6924        view_3.keymap_context.set.insert("c".into());
6925
6926        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
6927        let view_2 = cx.add_view(window_id, |_| view_2);
6928        let view_3 = cx.add_view(window_id, |_| view_3);
6929
6930        // This keymap's only binding dispatches an action on view 2 because that view will have
6931        // "a" and "b" in its context, but not "c".
6932        cx.add_bindings(vec![keymap::Binding::new(
6933            "a",
6934            Action("a".to_string()),
6935            Some("a && b && !c"),
6936        )]);
6937
6938        cx.add_bindings(vec![keymap::Binding::new(
6939            "b",
6940            Action("b".to_string()),
6941            None,
6942        )]);
6943
6944        let actions = Rc::new(RefCell::new(Vec::new()));
6945        cx.add_action({
6946            let actions = actions.clone();
6947            move |view: &mut View, action: &Action, cx| {
6948                if action.0 == "a" {
6949                    actions.borrow_mut().push(format!("{} a", view.id));
6950                } else {
6951                    actions
6952                        .borrow_mut()
6953                        .push(format!("{} {}", view.id, action.0));
6954                    cx.propagate_action();
6955                }
6956            }
6957        });
6958
6959        cx.add_global_action({
6960            let actions = actions.clone();
6961            move |action: &Action, _| {
6962                actions.borrow_mut().push(format!("global {}", action.0));
6963            }
6964        });
6965
6966        cx.dispatch_keystroke(
6967            window_id,
6968            vec![view_1.id(), view_2.id(), view_3.id()],
6969            &Keystroke::parse("a").unwrap(),
6970        );
6971
6972        assert_eq!(&*actions.borrow(), &["2 a"]);
6973
6974        actions.borrow_mut().clear();
6975        cx.dispatch_keystroke(
6976            window_id,
6977            vec![view_1.id(), view_2.id(), view_3.id()],
6978            &Keystroke::parse("b").unwrap(),
6979        );
6980
6981        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
6982    }
6983
6984    #[crate::test(self)]
6985    async fn test_model_condition(cx: &mut TestAppContext) {
6986        struct Counter(usize);
6987
6988        impl super::Entity for Counter {
6989            type Event = ();
6990        }
6991
6992        impl Counter {
6993            fn inc(&mut self, cx: &mut ModelContext<Self>) {
6994                self.0 += 1;
6995                cx.notify();
6996            }
6997        }
6998
6999        let model = cx.add_model(|_| Counter(0));
7000
7001        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
7002        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
7003        smol::pin!(condition1, condition2);
7004
7005        model.update(cx, |model, cx| model.inc(cx));
7006        assert_eq!(poll_once(&mut condition1).await, None);
7007        assert_eq!(poll_once(&mut condition2).await, None);
7008
7009        model.update(cx, |model, cx| model.inc(cx));
7010        assert_eq!(poll_once(&mut condition1).await, Some(()));
7011        assert_eq!(poll_once(&mut condition2).await, None);
7012
7013        model.update(cx, |model, cx| model.inc(cx));
7014        assert_eq!(poll_once(&mut condition2).await, Some(()));
7015
7016        model.update(cx, |_, cx| cx.notify());
7017    }
7018
7019    #[crate::test(self)]
7020    #[should_panic]
7021    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
7022        struct Model;
7023
7024        impl super::Entity for Model {
7025            type Event = ();
7026        }
7027
7028        let model = cx.add_model(|_| Model);
7029        model.condition(&cx, |_, _| false).await;
7030    }
7031
7032    #[crate::test(self)]
7033    #[should_panic(expected = "model dropped with pending condition")]
7034    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
7035        struct Model;
7036
7037        impl super::Entity for Model {
7038            type Event = ();
7039        }
7040
7041        let model = cx.add_model(|_| Model);
7042        let condition = model.condition(&cx, |_, _| false);
7043        cx.update(|_| drop(model));
7044        condition.await;
7045    }
7046
7047    #[crate::test(self)]
7048    async fn test_view_condition(cx: &mut TestAppContext) {
7049        struct Counter(usize);
7050
7051        impl super::Entity for Counter {
7052            type Event = ();
7053        }
7054
7055        impl super::View for Counter {
7056            fn ui_name() -> &'static str {
7057                "test view"
7058            }
7059
7060            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7061                Empty::new().boxed()
7062            }
7063        }
7064
7065        impl Counter {
7066            fn inc(&mut self, cx: &mut ViewContext<Self>) {
7067                self.0 += 1;
7068                cx.notify();
7069            }
7070        }
7071
7072        let (_, view) = cx.add_window(|_| Counter(0));
7073
7074        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
7075        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
7076        smol::pin!(condition1, condition2);
7077
7078        view.update(cx, |view, cx| view.inc(cx));
7079        assert_eq!(poll_once(&mut condition1).await, None);
7080        assert_eq!(poll_once(&mut condition2).await, None);
7081
7082        view.update(cx, |view, cx| view.inc(cx));
7083        assert_eq!(poll_once(&mut condition1).await, Some(()));
7084        assert_eq!(poll_once(&mut condition2).await, None);
7085
7086        view.update(cx, |view, cx| view.inc(cx));
7087        assert_eq!(poll_once(&mut condition2).await, Some(()));
7088        view.update(cx, |_, cx| cx.notify());
7089    }
7090
7091    #[crate::test(self)]
7092    #[should_panic]
7093    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
7094        struct View;
7095
7096        impl super::Entity for View {
7097            type Event = ();
7098        }
7099
7100        impl super::View for View {
7101            fn ui_name() -> &'static str {
7102                "test view"
7103            }
7104
7105            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7106                Empty::new().boxed()
7107            }
7108        }
7109
7110        let (_, view) = cx.add_window(|_| View);
7111        view.condition(&cx, |_, _| false).await;
7112    }
7113
7114    #[crate::test(self)]
7115    #[should_panic(expected = "view dropped with pending condition")]
7116    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
7117        struct View;
7118
7119        impl super::Entity for View {
7120            type Event = ();
7121        }
7122
7123        impl super::View for View {
7124            fn ui_name() -> &'static str {
7125                "test view"
7126            }
7127
7128            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7129                Empty::new().boxed()
7130            }
7131        }
7132
7133        let window_id = cx.add_window(|_| View).0;
7134        let view = cx.add_view(window_id, |_| View);
7135
7136        let condition = view.condition(&cx, |_, _| false);
7137        cx.update(|_| drop(view));
7138        condition.await;
7139    }
7140
7141    #[crate::test(self)]
7142    fn test_refresh_windows(cx: &mut MutableAppContext) {
7143        struct View(usize);
7144
7145        impl super::Entity for View {
7146            type Event = ();
7147        }
7148
7149        impl super::View for View {
7150            fn ui_name() -> &'static str {
7151                "test view"
7152            }
7153
7154            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7155                Empty::new().named(format!("render count: {}", post_inc(&mut self.0)))
7156            }
7157        }
7158
7159        let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
7160        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
7161
7162        assert_eq!(
7163            presenter.borrow().rendered_views[&root_view.id()].name(),
7164            Some("render count: 0")
7165        );
7166
7167        let view = cx.add_view(window_id, |cx| {
7168            cx.refresh_windows();
7169            View(0)
7170        });
7171
7172        assert_eq!(
7173            presenter.borrow().rendered_views[&root_view.id()].name(),
7174            Some("render count: 1")
7175        );
7176        assert_eq!(
7177            presenter.borrow().rendered_views[&view.id()].name(),
7178            Some("render count: 0")
7179        );
7180
7181        cx.update(|cx| cx.refresh_windows());
7182        assert_eq!(
7183            presenter.borrow().rendered_views[&root_view.id()].name(),
7184            Some("render count: 2")
7185        );
7186        assert_eq!(
7187            presenter.borrow().rendered_views[&view.id()].name(),
7188            Some("render count: 1")
7189        );
7190
7191        cx.update(|cx| {
7192            cx.refresh_windows();
7193            drop(view);
7194        });
7195        assert_eq!(
7196            presenter.borrow().rendered_views[&root_view.id()].name(),
7197            Some("render count: 3")
7198        );
7199        assert_eq!(presenter.borrow().rendered_views.len(), 1);
7200    }
7201
7202    #[crate::test(self)]
7203    async fn test_window_activation(cx: &mut TestAppContext) {
7204        struct View(&'static str);
7205
7206        impl super::Entity for View {
7207            type Event = ();
7208        }
7209
7210        impl super::View for View {
7211            fn ui_name() -> &'static str {
7212                "test view"
7213            }
7214
7215            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7216                Empty::new().boxed()
7217            }
7218        }
7219
7220        let events = Rc::new(RefCell::new(Vec::new()));
7221        let (window_1, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7222            cx.observe_window_activation({
7223                let events = events.clone();
7224                move |this, active, _| events.borrow_mut().push((this.0, active))
7225            })
7226            .detach();
7227            View("window 1")
7228        });
7229        assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
7230
7231        let (window_2, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7232            cx.observe_window_activation({
7233                let events = events.clone();
7234                move |this, active, _| events.borrow_mut().push((this.0, active))
7235            })
7236            .detach();
7237            View("window 2")
7238        });
7239        assert_eq!(
7240            mem::take(&mut *events.borrow_mut()),
7241            [("window 1", false), ("window 2", true)]
7242        );
7243
7244        let (window_3, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7245            cx.observe_window_activation({
7246                let events = events.clone();
7247                move |this, active, _| events.borrow_mut().push((this.0, active))
7248            })
7249            .detach();
7250            View("window 3")
7251        });
7252        assert_eq!(
7253            mem::take(&mut *events.borrow_mut()),
7254            [("window 2", false), ("window 3", true)]
7255        );
7256
7257        cx.simulate_window_activation(Some(window_2));
7258        assert_eq!(
7259            mem::take(&mut *events.borrow_mut()),
7260            [("window 3", false), ("window 2", true)]
7261        );
7262
7263        cx.simulate_window_activation(Some(window_1));
7264        assert_eq!(
7265            mem::take(&mut *events.borrow_mut()),
7266            [("window 2", false), ("window 1", true)]
7267        );
7268
7269        cx.simulate_window_activation(Some(window_3));
7270        assert_eq!(
7271            mem::take(&mut *events.borrow_mut()),
7272            [("window 1", false), ("window 3", true)]
7273        );
7274
7275        cx.simulate_window_activation(Some(window_3));
7276        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
7277    }
7278}