app.rs

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