app.rs

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