app.rs

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