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