app.rs

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