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