app.rs

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