app.rs

   1pub mod action;
   2mod callback_collection;
   3
   4use crate::{
   5    elements::ElementBox,
   6    executor::{self, Task},
   7    geometry::rect::RectF,
   8    keymap::{self, Binding, Keystroke},
   9    platform::{self, KeyDownEvent, Platform, PromptLevel, WindowOptions},
  10    presenter::Presenter,
  11    util::post_inc,
  12    AssetCache, AssetSource, ClipboardItem, FontCache, InputHandler, MouseButton, MouseRegionId,
  13    PathPromptOptions, TextLayoutCache,
  14};
  15pub use action::*;
  16use anyhow::{anyhow, Context, Result};
  17use callback_collection::CallbackCollection;
  18use collections::{btree_map, hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque};
  19use keymap::MatchResult;
  20use lazy_static::lazy_static;
  21use parking_lot::Mutex;
  22use platform::Event;
  23use postage::oneshot;
  24use smallvec::SmallVec;
  25use smol::prelude::*;
  26use std::{
  27    any::{type_name, Any, TypeId},
  28    cell::RefCell,
  29    fmt::{self, Debug},
  30    hash::{Hash, Hasher},
  31    marker::PhantomData,
  32    mem,
  33    ops::{Deref, DerefMut, Range},
  34    path::{Path, PathBuf},
  35    pin::Pin,
  36    rc::{self, Rc},
  37    sync::{Arc, Weak},
  38    time::Duration,
  39};
  40
  41use self::callback_collection::Mapping;
  42
  43pub trait Entity: 'static {
  44    type Event;
  45
  46    fn release(&mut self, _: &mut MutableAppContext) {}
  47    fn app_will_quit(
  48        &mut self,
  49        _: &mut MutableAppContext,
  50    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
  51        None
  52    }
  53}
  54
  55pub trait View: Entity + Sized {
  56    fn ui_name() -> &'static str;
  57    fn render(&mut self, cx: &mut RenderContext<'_, Self>) -> ElementBox;
  58    fn on_focus_in(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {}
  59    fn on_focus_out(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {}
  60    fn keymap_context(&self, _: &AppContext) -> keymap::Context {
  61        Self::default_keymap_context()
  62    }
  63    fn default_keymap_context() -> keymap::Context {
  64        let mut cx = keymap::Context::default();
  65        cx.set.insert(Self::ui_name().into());
  66        cx
  67    }
  68    fn debug_json(&self, _: &AppContext) -> serde_json::Value {
  69        serde_json::Value::Null
  70    }
  71
  72    fn text_for_range(&self, _: Range<usize>, _: &AppContext) -> Option<String> {
  73        None
  74    }
  75    fn selected_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
  76        None
  77    }
  78    fn marked_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
  79        None
  80    }
  81    fn unmark_text(&mut self, _: &mut ViewContext<Self>) {}
  82    fn replace_text_in_range(
  83        &mut self,
  84        _: Option<Range<usize>>,
  85        _: &str,
  86        _: &mut ViewContext<Self>,
  87    ) {
  88    }
  89    fn replace_and_mark_text_in_range(
  90        &mut self,
  91        _: Option<Range<usize>>,
  92        _: &str,
  93        _: Option<Range<usize>>,
  94        _: &mut ViewContext<Self>,
  95    ) {
  96    }
  97}
  98
  99pub trait ReadModel {
 100    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T;
 101}
 102
 103pub trait ReadModelWith {
 104    fn read_model_with<E: Entity, T>(
 105        &self,
 106        handle: &ModelHandle<E>,
 107        read: &mut dyn FnMut(&E, &AppContext) -> T,
 108    ) -> T;
 109}
 110
 111pub trait UpdateModel {
 112    fn update_model<T: Entity, O>(
 113        &mut self,
 114        handle: &ModelHandle<T>,
 115        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
 116    ) -> O;
 117}
 118
 119pub trait UpgradeModelHandle {
 120    fn upgrade_model_handle<T: Entity>(
 121        &self,
 122        handle: &WeakModelHandle<T>,
 123    ) -> Option<ModelHandle<T>>;
 124
 125    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool;
 126
 127    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle>;
 128}
 129
 130pub trait UpgradeViewHandle {
 131    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>>;
 132
 133    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle>;
 134}
 135
 136pub trait ReadView {
 137    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T;
 138}
 139
 140pub trait ReadViewWith {
 141    fn read_view_with<V, T>(
 142        &self,
 143        handle: &ViewHandle<V>,
 144        read: &mut dyn FnMut(&V, &AppContext) -> T,
 145    ) -> T
 146    where
 147        V: View;
 148}
 149
 150pub trait UpdateView {
 151    fn update_view<T, S>(
 152        &mut self,
 153        handle: &ViewHandle<T>,
 154        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 155    ) -> S
 156    where
 157        T: View;
 158}
 159
 160pub struct Menu<'a> {
 161    pub name: &'a str,
 162    pub items: Vec<MenuItem<'a>>,
 163}
 164
 165pub enum MenuItem<'a> {
 166    Separator,
 167    Submenu(Menu<'a>),
 168    Action {
 169        name: &'a str,
 170        action: Box<dyn Action>,
 171    },
 172}
 173
 174#[derive(Clone)]
 175pub struct App(Rc<RefCell<MutableAppContext>>);
 176
 177#[derive(Clone)]
 178pub struct AsyncAppContext(Rc<RefCell<MutableAppContext>>);
 179
 180#[cfg(any(test, feature = "test-support"))]
 181pub struct TestAppContext {
 182    cx: Rc<RefCell<MutableAppContext>>,
 183    foreground_platform: Rc<platform::test::ForegroundPlatform>,
 184    condition_duration: Option<Duration>,
 185}
 186
 187pub struct WindowInputHandler {
 188    app: Rc<RefCell<MutableAppContext>>,
 189    window_id: usize,
 190}
 191
 192impl App {
 193    pub fn new(asset_source: impl AssetSource) -> Result<Self> {
 194        let platform = platform::current::platform();
 195        let foreground_platform = platform::current::foreground_platform();
 196        let foreground = Rc::new(executor::Foreground::platform(platform.dispatcher())?);
 197        let app = Self(Rc::new(RefCell::new(MutableAppContext::new(
 198            foreground,
 199            Arc::new(executor::Background::new()),
 200            platform.clone(),
 201            foreground_platform.clone(),
 202            Arc::new(FontCache::new(platform.fonts())),
 203            Default::default(),
 204            asset_source,
 205        ))));
 206
 207        foreground_platform.on_quit(Box::new({
 208            let cx = app.0.clone();
 209            move || {
 210                cx.borrow_mut().quit();
 211            }
 212        }));
 213        foreground_platform.on_will_open_menu(Box::new({
 214            let cx = app.0.clone();
 215            move || {
 216                let mut cx = cx.borrow_mut();
 217                cx.keystroke_matcher.clear_pending();
 218            }
 219        }));
 220        foreground_platform.on_validate_menu_command(Box::new({
 221            let cx = app.0.clone();
 222            move |action| {
 223                let cx = cx.borrow_mut();
 224                !cx.keystroke_matcher.has_pending_keystrokes() && cx.is_action_available(action)
 225            }
 226        }));
 227        foreground_platform.on_menu_command(Box::new({
 228            let cx = app.0.clone();
 229            move |action| {
 230                let mut cx = cx.borrow_mut();
 231                if let Some(key_window_id) = cx.cx.platform.key_window_id() {
 232                    if let Some(view_id) = cx.focused_view_id(key_window_id) {
 233                        cx.handle_dispatch_action_from_effect(key_window_id, Some(view_id), action);
 234                        return;
 235                    }
 236                }
 237                cx.dispatch_global_action_any(action);
 238            }
 239        }));
 240
 241        app.0.borrow_mut().weak_self = Some(Rc::downgrade(&app.0));
 242        Ok(app)
 243    }
 244
 245    pub fn background(&self) -> Arc<executor::Background> {
 246        self.0.borrow().background().clone()
 247    }
 248
 249    pub fn on_become_active<F>(self, mut callback: F) -> Self
 250    where
 251        F: 'static + FnMut(&mut MutableAppContext),
 252    {
 253        let cx = self.0.clone();
 254        self.0
 255            .borrow_mut()
 256            .foreground_platform
 257            .on_become_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 258        self
 259    }
 260
 261    pub fn on_resign_active<F>(self, mut callback: F) -> Self
 262    where
 263        F: 'static + FnMut(&mut MutableAppContext),
 264    {
 265        let cx = self.0.clone();
 266        self.0
 267            .borrow_mut()
 268            .foreground_platform
 269            .on_resign_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 270        self
 271    }
 272
 273    pub fn on_quit<F>(&mut self, mut callback: F) -> &mut Self
 274    where
 275        F: 'static + FnMut(&mut MutableAppContext),
 276    {
 277        let cx = self.0.clone();
 278        self.0
 279            .borrow_mut()
 280            .foreground_platform
 281            .on_quit(Box::new(move || callback(&mut *cx.borrow_mut())));
 282        self
 283    }
 284
 285    pub fn on_event<F>(&mut self, mut callback: F) -> &mut Self
 286    where
 287        F: 'static + FnMut(Event, &mut MutableAppContext) -> bool,
 288    {
 289        let cx = self.0.clone();
 290        self.0
 291            .borrow_mut()
 292            .foreground_platform
 293            .on_event(Box::new(move |event| {
 294                callback(event, &mut *cx.borrow_mut())
 295            }));
 296        self
 297    }
 298
 299    pub fn on_open_urls<F>(&mut self, mut callback: F) -> &mut Self
 300    where
 301        F: 'static + FnMut(Vec<String>, &mut MutableAppContext),
 302    {
 303        let cx = self.0.clone();
 304        self.0
 305            .borrow_mut()
 306            .foreground_platform
 307            .on_open_urls(Box::new(move |paths| {
 308                callback(paths, &mut *cx.borrow_mut())
 309            }));
 310        self
 311    }
 312
 313    pub fn run<F>(self, on_finish_launching: F)
 314    where
 315        F: 'static + FnOnce(&mut MutableAppContext),
 316    {
 317        let platform = self.0.borrow().foreground_platform.clone();
 318        platform.run(Box::new(move || {
 319            let mut cx = self.0.borrow_mut();
 320            let cx = &mut *cx;
 321            crate::views::init(cx);
 322            on_finish_launching(cx);
 323        }))
 324    }
 325
 326    pub fn platform(&self) -> Arc<dyn Platform> {
 327        self.0.borrow().platform()
 328    }
 329
 330    pub fn font_cache(&self) -> Arc<FontCache> {
 331        self.0.borrow().cx.font_cache.clone()
 332    }
 333
 334    fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 335        let mut state = self.0.borrow_mut();
 336        let result = state.update(callback);
 337        state.pending_notifications.clear();
 338        result
 339    }
 340}
 341
 342impl WindowInputHandler {
 343    fn read_focused_view<T, F>(&self, f: F) -> Option<T>
 344    where
 345        F: FnOnce(&dyn AnyView, &AppContext) -> T,
 346    {
 347        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                false,
 487                cx,
 488            ) {
 489                return true;
 490            }
 491
 492            false
 493        });
 494
 495        if !handled && !keystroke.cmd && !keystroke.ctrl {
 496            WindowInputHandler {
 497                app: self.cx.clone(),
 498                window_id,
 499            }
 500            .replace_text_in_range(None, &keystroke.key)
 501        }
 502    }
 503
 504    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 505    where
 506        T: Entity,
 507        F: FnOnce(&mut ModelContext<T>) -> T,
 508    {
 509        self.cx.borrow_mut().add_model(build_model)
 510    }
 511
 512    pub fn add_window<T, F>(&mut self, build_root_view: F) -> (usize, ViewHandle<T>)
 513    where
 514        T: View,
 515        F: FnOnce(&mut ViewContext<T>) -> T,
 516    {
 517        let (window_id, view) = self
 518            .cx
 519            .borrow_mut()
 520            .add_window(Default::default(), build_root_view);
 521        self.simulate_window_activation(Some(window_id));
 522        (window_id, view)
 523    }
 524
 525    pub fn add_view<T, F>(
 526        &mut self,
 527        parent_handle: impl Into<AnyViewHandle>,
 528        build_view: F,
 529    ) -> ViewHandle<T>
 530    where
 531        T: View,
 532        F: FnOnce(&mut ViewContext<T>) -> T,
 533    {
 534        self.cx.borrow_mut().add_view(parent_handle, build_view)
 535    }
 536
 537    pub fn window_ids(&self) -> Vec<usize> {
 538        self.cx.borrow().window_ids().collect()
 539    }
 540
 541    pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
 542        self.cx.borrow().root_view(window_id)
 543    }
 544
 545    pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
 546        callback(self.cx.borrow().as_ref())
 547    }
 548
 549    pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 550        let mut state = self.cx.borrow_mut();
 551        // Don't increment pending flushes in order for effects to be flushed before the callback
 552        // completes, which is helpful in tests.
 553        let result = callback(&mut *state);
 554        // Flush effects after the callback just in case there are any. This can happen in edge
 555        // cases such as the closure dropping handles.
 556        state.flush_effects();
 557        result
 558    }
 559
 560    pub fn render<F, V, T>(&mut self, handle: &ViewHandle<V>, f: F) -> T
 561    where
 562        F: FnOnce(&mut V, &mut RenderContext<V>) -> T,
 563        V: View,
 564    {
 565        handle.update(&mut *self.cx.borrow_mut(), |view, cx| {
 566            let mut render_cx = RenderContext {
 567                app: cx,
 568                window_id: handle.window_id(),
 569                view_id: handle.id(),
 570                view_type: PhantomData,
 571                titlebar_height: 0.,
 572                hovered_region_ids: Default::default(),
 573                clicked_region_ids: 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_ids: None,
1282                        refreshing: false,
1283                    })
1284                    .unwrap(),
1285                )
1286            })
1287            .collect()
1288    }
1289
1290    pub(crate) fn start_frame(&mut self) {
1291        self.frame_count += 1;
1292    }
1293
1294    pub fn update<T, F: FnOnce(&mut Self) -> T>(&mut self, callback: F) -> T {
1295        self.pending_flushes += 1;
1296        let result = callback(self);
1297        self.flush_effects();
1298        result
1299    }
1300
1301    pub fn set_menus(&mut self, menus: Vec<Menu>) {
1302        self.foreground_platform
1303            .set_menus(menus, &self.keystroke_matcher);
1304    }
1305
1306    fn show_character_palette(&self, window_id: usize) {
1307        let (_, window) = &self.presenters_and_platform_windows[&window_id];
1308        window.show_character_palette();
1309    }
1310
1311    pub fn minimize_window(&self, window_id: usize) {
1312        let (_, window) = &self.presenters_and_platform_windows[&window_id];
1313        window.minimize();
1314    }
1315
1316    pub fn zoom_window(&self, window_id: usize) {
1317        let (_, window) = &self.presenters_and_platform_windows[&window_id];
1318        window.zoom();
1319    }
1320
1321    fn prompt(
1322        &self,
1323        window_id: usize,
1324        level: PromptLevel,
1325        msg: &str,
1326        answers: &[&str],
1327    ) -> oneshot::Receiver<usize> {
1328        let (_, window) = &self.presenters_and_platform_windows[&window_id];
1329        window.prompt(level, msg, answers)
1330    }
1331
1332    pub fn prompt_for_paths(
1333        &self,
1334        options: PathPromptOptions,
1335    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
1336        self.foreground_platform.prompt_for_paths(options)
1337    }
1338
1339    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
1340        self.foreground_platform.prompt_for_new_path(directory)
1341    }
1342
1343    pub fn emit_global<E: Any>(&mut self, payload: E) {
1344        self.pending_effects.push_back(Effect::GlobalEvent {
1345            payload: Box::new(payload),
1346        });
1347    }
1348
1349    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1350    where
1351        E: Entity,
1352        E::Event: 'static,
1353        H: Handle<E>,
1354        F: 'static + FnMut(H, &E::Event, &mut Self),
1355    {
1356        self.subscribe_internal(handle, move |handle, event, cx| {
1357            callback(handle, event, cx);
1358            true
1359        })
1360    }
1361
1362    pub fn subscribe_global<E, F>(&mut self, mut callback: F) -> Subscription
1363    where
1364        E: Any,
1365        F: 'static + FnMut(&E, &mut Self),
1366    {
1367        let subscription_id = post_inc(&mut self.next_subscription_id);
1368        let type_id = TypeId::of::<E>();
1369        self.pending_effects.push_back(Effect::GlobalSubscription {
1370            type_id,
1371            subscription_id,
1372            callback: Box::new(move |payload, cx| {
1373                let payload = payload.downcast_ref().expect("downcast is type safe");
1374                callback(payload, cx)
1375            }),
1376        });
1377
1378        Subscription::GlobalSubscription {
1379            id: subscription_id,
1380            type_id,
1381            subscriptions: Some(self.global_subscriptions.downgrade()),
1382        }
1383    }
1384
1385    pub fn observe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1386    where
1387        E: Entity,
1388        E::Event: 'static,
1389        H: Handle<E>,
1390        F: 'static + FnMut(H, &mut Self),
1391    {
1392        self.observe_internal(handle, move |handle, cx| {
1393            callback(handle, cx);
1394            true
1395        })
1396    }
1397
1398    pub fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1399    where
1400        E: Entity,
1401        E::Event: 'static,
1402        H: Handle<E>,
1403        F: 'static + FnMut(H, &E::Event, &mut Self) -> bool,
1404    {
1405        let subscription_id = post_inc(&mut self.next_subscription_id);
1406        let emitter = handle.downgrade();
1407        self.pending_effects.push_back(Effect::Subscription {
1408            entity_id: handle.id(),
1409            subscription_id,
1410            callback: Box::new(move |payload, cx| {
1411                if let Some(emitter) = H::upgrade_from(&emitter, cx.as_ref()) {
1412                    let payload = payload.downcast_ref().expect("downcast is type safe");
1413                    callback(emitter, payload, cx)
1414                } else {
1415                    false
1416                }
1417            }),
1418        });
1419        Subscription::Subscription {
1420            id: subscription_id,
1421            entity_id: handle.id(),
1422            subscriptions: Some(self.subscriptions.downgrade()),
1423        }
1424    }
1425
1426    fn observe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1427    where
1428        E: Entity,
1429        E::Event: 'static,
1430        H: Handle<E>,
1431        F: 'static + FnMut(H, &mut Self) -> bool,
1432    {
1433        let subscription_id = post_inc(&mut self.next_subscription_id);
1434        let observed = handle.downgrade();
1435        let entity_id = handle.id();
1436        self.pending_effects.push_back(Effect::Observation {
1437            entity_id,
1438            subscription_id,
1439            callback: Box::new(move |cx| {
1440                if let Some(observed) = H::upgrade_from(&observed, cx) {
1441                    callback(observed, cx)
1442                } else {
1443                    false
1444                }
1445            }),
1446        });
1447        Subscription::Observation {
1448            id: subscription_id,
1449            entity_id,
1450            observations: Some(self.observations.downgrade()),
1451        }
1452    }
1453
1454    fn observe_focus<F, V>(&mut self, handle: &ViewHandle<V>, mut callback: F) -> Subscription
1455    where
1456        F: 'static + FnMut(ViewHandle<V>, bool, &mut MutableAppContext) -> bool,
1457        V: View,
1458    {
1459        let subscription_id = post_inc(&mut self.next_subscription_id);
1460        let observed = handle.downgrade();
1461        let view_id = handle.id();
1462
1463        self.pending_effects.push_back(Effect::FocusObservation {
1464            view_id,
1465            subscription_id,
1466            callback: Box::new(move |focused, cx| {
1467                if let Some(observed) = observed.upgrade(cx) {
1468                    callback(observed, focused, cx)
1469                } else {
1470                    false
1471                }
1472            }),
1473        });
1474
1475        Subscription::FocusObservation {
1476            id: subscription_id,
1477            view_id,
1478            observations: Some(self.focus_observations.downgrade()),
1479        }
1480    }
1481
1482    pub fn observe_global<G, F>(&mut self, mut observe: F) -> Subscription
1483    where
1484        G: Any,
1485        F: 'static + FnMut(&mut MutableAppContext),
1486    {
1487        let type_id = TypeId::of::<G>();
1488        let id = post_inc(&mut self.next_subscription_id);
1489
1490        self.global_observations.add_callback(
1491            type_id,
1492            id,
1493            Box::new(move |cx: &mut MutableAppContext| observe(cx)),
1494        );
1495
1496        Subscription::GlobalObservation {
1497            id,
1498            type_id,
1499            observations: Some(self.global_observations.downgrade()),
1500        }
1501    }
1502
1503    pub fn observe_release<E, H, F>(&mut self, handle: &H, callback: F) -> Subscription
1504    where
1505        E: Entity,
1506        E::Event: 'static,
1507        H: Handle<E>,
1508        F: 'static + FnOnce(&E, &mut Self),
1509    {
1510        let id = post_inc(&mut self.next_subscription_id);
1511        self.release_observations
1512            .lock()
1513            .entry(handle.id())
1514            .or_default()
1515            .insert(
1516                id,
1517                Box::new(move |released, cx| {
1518                    let released = released.downcast_ref().unwrap();
1519                    callback(released, cx)
1520                }),
1521            );
1522        Subscription::ReleaseObservation {
1523            id,
1524            entity_id: handle.id(),
1525            observations: Some(Arc::downgrade(&self.release_observations)),
1526        }
1527    }
1528
1529    pub fn observe_actions<F>(&mut self, callback: F) -> Subscription
1530    where
1531        F: 'static + FnMut(TypeId, &mut MutableAppContext),
1532    {
1533        let id = post_inc(&mut self.next_subscription_id);
1534        self.action_dispatch_observations
1535            .lock()
1536            .insert(id, Box::new(callback));
1537        Subscription::ActionObservation {
1538            id,
1539            observations: Some(Arc::downgrade(&self.action_dispatch_observations)),
1540        }
1541    }
1542
1543    fn observe_window_activation<F>(&mut self, window_id: usize, callback: F) -> Subscription
1544    where
1545        F: 'static + FnMut(bool, &mut MutableAppContext) -> bool,
1546    {
1547        let subscription_id = post_inc(&mut self.next_subscription_id);
1548        self.pending_effects
1549            .push_back(Effect::WindowActivationObservation {
1550                window_id,
1551                subscription_id,
1552                callback: Box::new(callback),
1553            });
1554        Subscription::WindowActivationObservation {
1555            id: subscription_id,
1556            window_id,
1557            observations: Some(self.window_activation_observations.downgrade()),
1558        }
1559    }
1560
1561    fn observe_fullscreen<F>(&mut self, window_id: usize, callback: F) -> Subscription
1562    where
1563        F: 'static + FnMut(bool, &mut MutableAppContext) -> bool,
1564    {
1565        let subscription_id = post_inc(&mut self.next_subscription_id);
1566        self.pending_effects
1567            .push_back(Effect::WindowFullscreenObservation {
1568                window_id,
1569                subscription_id,
1570                callback: Box::new(callback),
1571            });
1572        Subscription::WindowFullscreenObservation {
1573            id: subscription_id,
1574            window_id,
1575            observations: Some(self.window_activation_observations.downgrade()),
1576        }
1577    }
1578
1579    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut MutableAppContext)) {
1580        self.pending_effects.push_back(Effect::Deferred {
1581            callback: Box::new(callback),
1582            after_window_update: false,
1583        })
1584    }
1585
1586    pub fn after_window_update(&mut self, callback: impl 'static + FnOnce(&mut MutableAppContext)) {
1587        self.pending_effects.push_back(Effect::Deferred {
1588            callback: Box::new(callback),
1589            after_window_update: true,
1590        })
1591    }
1592
1593    pub(crate) fn notify_model(&mut self, model_id: usize) {
1594        if self.pending_notifications.insert(model_id) {
1595            self.pending_effects
1596                .push_back(Effect::ModelNotification { model_id });
1597        }
1598    }
1599
1600    pub(crate) fn notify_view(&mut self, window_id: usize, view_id: usize) {
1601        if self.pending_notifications.insert(view_id) {
1602            self.pending_effects
1603                .push_back(Effect::ViewNotification { window_id, view_id });
1604        }
1605    }
1606
1607    pub(crate) fn notify_global(&mut self, type_id: TypeId) {
1608        if self.pending_global_notifications.insert(type_id) {
1609            self.pending_effects
1610                .push_back(Effect::GlobalNotification { type_id });
1611        }
1612    }
1613
1614    pub(crate) fn name_for_view(&self, window_id: usize, view_id: usize) -> Option<&str> {
1615        self.views
1616            .get(&(window_id, view_id))
1617            .map(|view| view.ui_name())
1618    }
1619
1620    pub fn all_action_names<'a>(&'a self) -> impl Iterator<Item = &'static str> + 'a {
1621        self.action_deserializers.keys().copied()
1622    }
1623
1624    pub fn available_actions(
1625        &self,
1626        window_id: usize,
1627        view_id: usize,
1628    ) -> impl Iterator<Item = (&'static str, Box<dyn Action>, SmallVec<[&Binding; 1]>)> {
1629        let mut action_types: HashSet<_> = self.global_actions.keys().copied().collect();
1630
1631        for view_id in self.parents(window_id, view_id) {
1632            if let Some(view) = self.views.get(&(window_id, view_id)) {
1633                let view_type = view.as_any().type_id();
1634                if let Some(actions) = self.actions.get(&view_type) {
1635                    action_types.extend(actions.keys().copied());
1636                }
1637            }
1638        }
1639
1640        self.action_deserializers
1641            .iter()
1642            .filter_map(move |(name, (type_id, deserialize))| {
1643                if action_types.contains(type_id) {
1644                    Some((
1645                        *name,
1646                        deserialize("{}").ok()?,
1647                        self.keystroke_matcher
1648                            .bindings_for_action_type(*type_id)
1649                            .collect(),
1650                    ))
1651                } else {
1652                    None
1653                }
1654            })
1655    }
1656
1657    pub fn is_action_available(&self, action: &dyn Action) -> bool {
1658        let action_type = action.as_any().type_id();
1659        if let Some(window_id) = self.cx.platform.key_window_id() {
1660            if let Some(focused_view_id) = self.focused_view_id(window_id) {
1661                for view_id in self.parents(window_id, focused_view_id) {
1662                    if let Some(view) = self.views.get(&(window_id, view_id)) {
1663                        let view_type = view.as_any().type_id();
1664                        if let Some(actions) = self.actions.get(&view_type) {
1665                            if actions.contains_key(&action_type) {
1666                                return true;
1667                            }
1668                        }
1669                    }
1670                }
1671            }
1672        }
1673        self.global_actions.contains_key(&action_type)
1674    }
1675
1676    /// Return keystrokes that would dispatch the given action closest to the focused view, if there are any.
1677    pub(crate) fn keystrokes_for_action(
1678        &self,
1679        window_id: usize,
1680        dispatch_path: &[usize],
1681        action: &dyn Action,
1682    ) -> Option<SmallVec<[Keystroke; 2]>> {
1683        for view_id in dispatch_path.iter().rev() {
1684            let view = self
1685                .cx
1686                .views
1687                .get(&(window_id, *view_id))
1688                .expect("view in responder chain does not exist");
1689            let cx = view.keymap_context(self.as_ref());
1690            let keystrokes = self.keystroke_matcher.keystrokes_for_action(action, &cx);
1691            if keystrokes.is_some() {
1692                return keystrokes;
1693            }
1694        }
1695
1696        None
1697    }
1698
1699    // Traverses the parent tree. Walks down the tree toward the passed
1700    // view calling visit with true. Then walks back up the tree calling visit with false.
1701    // If `visit` returns false this function will immediately return.
1702    // Returns a bool indicating if the traversal was completed early.
1703    fn visit_dispatch_path(
1704        &mut self,
1705        window_id: usize,
1706        view_id: usize,
1707        mut visit: impl FnMut(usize, bool, &mut MutableAppContext) -> bool,
1708    ) -> bool {
1709        // List of view ids from the leaf to the root of the window
1710        let path = self.parents(window_id, view_id).collect::<Vec<_>>();
1711
1712        // Walk down from the root to the leaf calling visit with capture_phase = true
1713        for view_id in path.iter().rev() {
1714            if !visit(*view_id, true, self) {
1715                return false;
1716            }
1717        }
1718
1719        // Walk up from the leaf to the root calling visit with capture_phase = false
1720        for view_id in path.iter() {
1721            if !visit(*view_id, false, self) {
1722                return false;
1723            }
1724        }
1725
1726        true
1727    }
1728
1729    // Returns an iterator over all of the view ids from the passed view up to the root of the window
1730    // Includes the passed view itself
1731    fn parents(&self, window_id: usize, mut view_id: usize) -> impl Iterator<Item = usize> + '_ {
1732        std::iter::once(view_id)
1733            .into_iter()
1734            .chain(std::iter::from_fn(move || {
1735                if let Some(ParentId::View(parent_id)) = self.parents.get(&(window_id, view_id)) {
1736                    view_id = *parent_id;
1737                    Some(view_id)
1738                } else {
1739                    None
1740                }
1741            }))
1742    }
1743
1744    fn actions_mut(
1745        &mut self,
1746        capture_phase: bool,
1747    ) -> &mut HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>> {
1748        if capture_phase {
1749            &mut self.capture_actions
1750        } else {
1751            &mut self.actions
1752        }
1753    }
1754
1755    pub fn dispatch_global_action<A: Action>(&mut self, action: A) {
1756        self.dispatch_global_action_any(&action);
1757    }
1758
1759    fn dispatch_global_action_any(&mut self, action: &dyn Action) -> bool {
1760        self.update(|this| {
1761            if let Some((name, mut handler)) = this.global_actions.remove_entry(&action.id()) {
1762                handler(action, this);
1763                this.global_actions.insert(name, handler);
1764                true
1765            } else {
1766                false
1767            }
1768        })
1769    }
1770
1771    pub fn add_bindings<T: IntoIterator<Item = keymap::Binding>>(&mut self, bindings: T) {
1772        self.keystroke_matcher.add_bindings(bindings);
1773    }
1774
1775    pub fn clear_bindings(&mut self) {
1776        self.keystroke_matcher.clear_bindings();
1777    }
1778
1779    pub fn dispatch_keystroke(&mut self, window_id: usize, keystroke: &Keystroke) -> bool {
1780        let mut pending = false;
1781
1782        if let Some(focused_view_id) = self.focused_view_id(window_id) {
1783            for view_id in self.parents(window_id, focused_view_id).collect::<Vec<_>>() {
1784                let keymap_context = self
1785                    .cx
1786                    .views
1787                    .get(&(window_id, view_id))
1788                    .unwrap()
1789                    .keymap_context(self.as_ref());
1790
1791                match self.keystroke_matcher.push_keystroke(
1792                    keystroke.clone(),
1793                    view_id,
1794                    &keymap_context,
1795                ) {
1796                    MatchResult::None => {}
1797                    MatchResult::Pending => pending = true,
1798                    MatchResult::Action(action) => {
1799                        if self.handle_dispatch_action_from_effect(
1800                            window_id,
1801                            Some(view_id),
1802                            action.as_ref(),
1803                        ) {
1804                            self.keystroke_matcher.clear_pending();
1805                            return true;
1806                        }
1807                    }
1808                }
1809            }
1810        }
1811
1812        pending
1813    }
1814
1815    pub fn default_global<T: 'static + Default>(&mut self) -> &T {
1816        let type_id = TypeId::of::<T>();
1817        self.update(|this| {
1818            if let Entry::Vacant(entry) = this.cx.globals.entry(type_id) {
1819                entry.insert(Box::new(T::default()));
1820                this.notify_global(type_id);
1821            }
1822        });
1823        self.globals.get(&type_id).unwrap().downcast_ref().unwrap()
1824    }
1825
1826    pub fn set_global<T: 'static>(&mut self, state: T) {
1827        self.update(|this| {
1828            let type_id = TypeId::of::<T>();
1829            this.cx.globals.insert(type_id, Box::new(state));
1830            this.notify_global(type_id);
1831        });
1832    }
1833
1834    pub fn update_default_global<T, F, U>(&mut self, update: F) -> U
1835    where
1836        T: 'static + Default,
1837        F: FnOnce(&mut T, &mut MutableAppContext) -> U,
1838    {
1839        self.update(|this| {
1840            let type_id = TypeId::of::<T>();
1841            let mut state = this
1842                .cx
1843                .globals
1844                .remove(&type_id)
1845                .unwrap_or_else(|| Box::new(T::default()));
1846            let result = update(state.downcast_mut().unwrap(), this);
1847            this.cx.globals.insert(type_id, state);
1848            this.notify_global(type_id);
1849            result
1850        })
1851    }
1852
1853    pub fn update_global<T, F, U>(&mut self, update: F) -> U
1854    where
1855        T: 'static,
1856        F: FnOnce(&mut T, &mut MutableAppContext) -> U,
1857    {
1858        self.update(|this| {
1859            let type_id = TypeId::of::<T>();
1860            if let Some(mut state) = this.cx.globals.remove(&type_id) {
1861                let result = update(state.downcast_mut().unwrap(), this);
1862                this.cx.globals.insert(type_id, state);
1863                this.notify_global(type_id);
1864                result
1865            } else {
1866                panic!("No global added for {}", std::any::type_name::<T>());
1867            }
1868        })
1869    }
1870
1871    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
1872    where
1873        T: Entity,
1874        F: FnOnce(&mut ModelContext<T>) -> T,
1875    {
1876        self.update(|this| {
1877            let model_id = post_inc(&mut this.next_entity_id);
1878            let handle = ModelHandle::new(model_id, &this.cx.ref_counts);
1879            let mut cx = ModelContext::new(this, model_id);
1880            let model = build_model(&mut cx);
1881            this.cx.models.insert(model_id, Box::new(model));
1882            handle
1883        })
1884    }
1885
1886    pub fn add_window<T, F>(
1887        &mut self,
1888        window_options: WindowOptions,
1889        build_root_view: F,
1890    ) -> (usize, ViewHandle<T>)
1891    where
1892        T: View,
1893        F: FnOnce(&mut ViewContext<T>) -> T,
1894    {
1895        self.update(|this| {
1896            let window_id = post_inc(&mut this.next_window_id);
1897            let root_view = this
1898                .build_and_insert_view(window_id, ParentId::Root, |cx| Some(build_root_view(cx)))
1899                .unwrap();
1900            this.cx.windows.insert(
1901                window_id,
1902                Window {
1903                    root_view: root_view.clone().into(),
1904                    focused_view_id: Some(root_view.id()),
1905                    is_active: false,
1906                    invalidation: None,
1907                    is_fullscreen: false,
1908                },
1909            );
1910            root_view.update(this, |view, cx| view.on_focus_in(cx.handle().into(), cx));
1911            this.open_platform_window(window_id, window_options);
1912
1913            (window_id, root_view)
1914        })
1915    }
1916
1917    pub fn replace_root_view<T, F>(&mut self, window_id: usize, build_root_view: F) -> ViewHandle<T>
1918    where
1919        T: View,
1920        F: FnOnce(&mut ViewContext<T>) -> T,
1921    {
1922        self.update(|this| {
1923            let root_view = this
1924                .build_and_insert_view(window_id, ParentId::Root, |cx| Some(build_root_view(cx)))
1925                .unwrap();
1926            let window = this.cx.windows.get_mut(&window_id).unwrap();
1927            window.root_view = root_view.clone().into();
1928            window.focused_view_id = Some(root_view.id());
1929            root_view
1930        })
1931    }
1932
1933    pub fn remove_window(&mut self, window_id: usize) {
1934        self.cx.windows.remove(&window_id);
1935        self.presenters_and_platform_windows.remove(&window_id);
1936        self.flush_effects();
1937    }
1938
1939    fn open_platform_window(&mut self, window_id: usize, window_options: WindowOptions) {
1940        let mut window =
1941            self.cx
1942                .platform
1943                .open_window(window_id, window_options, self.foreground.clone());
1944        let presenter = Rc::new(RefCell::new(
1945            self.build_presenter(window_id, window.titlebar_height()),
1946        ));
1947
1948        {
1949            let mut app = self.upgrade();
1950            let presenter = Rc::downgrade(&presenter);
1951            window.on_event(Box::new(move |event| {
1952                app.update(|cx| {
1953                    if let Some(presenter) = presenter.upgrade() {
1954                        if let Event::KeyDown(KeyDownEvent { keystroke, .. }) = &event {
1955                            if cx.dispatch_keystroke(window_id, keystroke) {
1956                                return true;
1957                            }
1958                        }
1959
1960                        presenter.borrow_mut().dispatch_event(event, false, cx)
1961                    } else {
1962                        false
1963                    }
1964                })
1965            }));
1966        }
1967
1968        {
1969            let mut app = self.upgrade();
1970            window.on_active_status_change(Box::new(move |is_active| {
1971                app.update(|cx| cx.window_changed_active_status(window_id, is_active))
1972            }));
1973        }
1974
1975        {
1976            let mut app = self.upgrade();
1977            window.on_resize(Box::new(move || {
1978                app.update(|cx| cx.window_was_resized(window_id))
1979            }));
1980        }
1981
1982        {
1983            let mut app = self.upgrade();
1984            window.on_fullscreen(Box::new(move |is_fullscreen| {
1985                app.update(|cx| cx.window_was_fullscreen_changed(window_id, is_fullscreen))
1986            }));
1987        }
1988
1989        {
1990            let mut app = self.upgrade();
1991            window.on_close(Box::new(move || {
1992                app.update(|cx| cx.remove_window(window_id));
1993            }));
1994        }
1995
1996        window.set_input_handler(Box::new(WindowInputHandler {
1997            app: self.upgrade().0,
1998            window_id,
1999        }));
2000
2001        let scene =
2002            presenter
2003                .borrow_mut()
2004                .build_scene(window.size(), window.scale_factor(), false, self);
2005        window.present_scene(scene);
2006        self.presenters_and_platform_windows
2007            .insert(window_id, (presenter.clone(), window));
2008    }
2009
2010    pub fn build_presenter(&mut self, window_id: usize, titlebar_height: f32) -> Presenter {
2011        Presenter::new(
2012            window_id,
2013            titlebar_height,
2014            self.cx.font_cache.clone(),
2015            TextLayoutCache::new(self.cx.platform.fonts()),
2016            self.assets.clone(),
2017            self,
2018        )
2019    }
2020
2021    pub fn add_view<T, F>(
2022        &mut self,
2023        parent_handle: impl Into<AnyViewHandle>,
2024        build_view: F,
2025    ) -> ViewHandle<T>
2026    where
2027        T: View,
2028        F: FnOnce(&mut ViewContext<T>) -> T,
2029    {
2030        let parent_handle = parent_handle.into();
2031        self.build_and_insert_view(
2032            parent_handle.window_id,
2033            ParentId::View(parent_handle.view_id),
2034            |cx| Some(build_view(cx)),
2035        )
2036        .unwrap()
2037    }
2038
2039    pub fn add_option_view<T, F>(
2040        &mut self,
2041        parent_handle: impl Into<AnyViewHandle>,
2042        build_view: F,
2043    ) -> Option<ViewHandle<T>>
2044    where
2045        T: View,
2046        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
2047    {
2048        let parent_handle = parent_handle.into();
2049        self.build_and_insert_view(
2050            parent_handle.window_id,
2051            ParentId::View(parent_handle.view_id),
2052            build_view,
2053        )
2054    }
2055
2056    pub(crate) fn build_and_insert_view<T, F>(
2057        &mut self,
2058        window_id: usize,
2059        parent_id: ParentId,
2060        build_view: F,
2061    ) -> Option<ViewHandle<T>>
2062    where
2063        T: View,
2064        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
2065    {
2066        self.update(|this| {
2067            let view_id = post_inc(&mut this.next_entity_id);
2068            let mut cx = ViewContext::new(this, window_id, view_id);
2069            let handle = if let Some(view) = build_view(&mut cx) {
2070                this.cx.views.insert((window_id, view_id), Box::new(view));
2071                this.cx.parents.insert((window_id, view_id), parent_id);
2072                if let Some(window) = this.cx.windows.get_mut(&window_id) {
2073                    window
2074                        .invalidation
2075                        .get_or_insert_with(Default::default)
2076                        .updated
2077                        .insert(view_id);
2078                }
2079                Some(ViewHandle::new(window_id, view_id, &this.cx.ref_counts))
2080            } else {
2081                None
2082            };
2083            handle
2084        })
2085    }
2086
2087    fn remove_dropped_entities(&mut self) {
2088        loop {
2089            let (dropped_models, dropped_views, dropped_element_states) =
2090                self.cx.ref_counts.lock().take_dropped();
2091            if dropped_models.is_empty()
2092                && dropped_views.is_empty()
2093                && dropped_element_states.is_empty()
2094            {
2095                break;
2096            }
2097
2098            for model_id in dropped_models {
2099                self.subscriptions.remove(model_id);
2100                self.observations.remove(model_id);
2101                let mut model = self.cx.models.remove(&model_id).unwrap();
2102                model.release(self);
2103                self.pending_effects
2104                    .push_back(Effect::ModelRelease { model_id, model });
2105            }
2106
2107            for (window_id, view_id) in dropped_views {
2108                self.subscriptions.remove(view_id);
2109                self.observations.remove(view_id);
2110                let mut view = self.cx.views.remove(&(window_id, view_id)).unwrap();
2111                view.release(self);
2112                let change_focus_to = self.cx.windows.get_mut(&window_id).and_then(|window| {
2113                    window
2114                        .invalidation
2115                        .get_or_insert_with(Default::default)
2116                        .removed
2117                        .push(view_id);
2118                    if window.focused_view_id == Some(view_id) {
2119                        Some(window.root_view.id())
2120                    } else {
2121                        None
2122                    }
2123                });
2124                self.cx.parents.remove(&(window_id, view_id));
2125
2126                if let Some(view_id) = change_focus_to {
2127                    self.handle_focus_effect(window_id, Some(view_id));
2128                }
2129
2130                self.pending_effects
2131                    .push_back(Effect::ViewRelease { view_id, view });
2132            }
2133
2134            for key in dropped_element_states {
2135                self.cx.element_states.remove(&key);
2136            }
2137        }
2138    }
2139
2140    fn flush_effects(&mut self) {
2141        self.pending_flushes = self.pending_flushes.saturating_sub(1);
2142        let mut after_window_update_callbacks = Vec::new();
2143
2144        if !self.flushing_effects && self.pending_flushes == 0 {
2145            self.flushing_effects = true;
2146
2147            let mut refreshing = false;
2148            loop {
2149                if let Some(effect) = self.pending_effects.pop_front() {
2150                    if let Some(pending_focus_index) = self.pending_focus_index.as_mut() {
2151                        *pending_focus_index = pending_focus_index.saturating_sub(1);
2152                    }
2153                    match effect {
2154                        Effect::Subscription {
2155                            entity_id,
2156                            subscription_id,
2157                            callback,
2158                        } => self.subscriptions.add_or_remove_callback(
2159                            entity_id,
2160                            subscription_id,
2161                            callback,
2162                        ),
2163
2164                        Effect::Event { entity_id, payload } => {
2165                            let mut subscriptions = self.subscriptions.clone();
2166                            subscriptions.emit_and_cleanup(entity_id, self, |callback, this| {
2167                                callback(payload.as_ref(), this)
2168                            })
2169                        }
2170
2171                        Effect::GlobalSubscription {
2172                            type_id,
2173                            subscription_id,
2174                            callback,
2175                        } => self.global_subscriptions.add_or_remove_callback(
2176                            type_id,
2177                            subscription_id,
2178                            callback,
2179                        ),
2180
2181                        Effect::GlobalEvent { payload } => self.emit_global_event(payload),
2182
2183                        Effect::Observation {
2184                            entity_id,
2185                            subscription_id,
2186                            callback,
2187                        } => self.observations.add_or_remove_callback(
2188                            entity_id,
2189                            subscription_id,
2190                            callback,
2191                        ),
2192
2193                        Effect::ModelNotification { model_id } => {
2194                            let mut observations = self.observations.clone();
2195                            observations
2196                                .emit_and_cleanup(model_id, self, |callback, this| callback(this));
2197                        }
2198
2199                        Effect::ViewNotification { window_id, view_id } => {
2200                            self.handle_view_notification_effect(window_id, view_id)
2201                        }
2202
2203                        Effect::GlobalNotification { type_id } => {
2204                            let mut subscriptions = self.global_observations.clone();
2205                            subscriptions.emit_and_cleanup(type_id, self, |callback, this| {
2206                                callback(this);
2207                                true
2208                            });
2209                        }
2210
2211                        Effect::Deferred {
2212                            callback,
2213                            after_window_update,
2214                        } => {
2215                            if after_window_update {
2216                                after_window_update_callbacks.push(callback);
2217                            } else {
2218                                callback(self)
2219                            }
2220                        }
2221
2222                        Effect::ModelRelease { model_id, model } => {
2223                            self.handle_entity_release_effect(model_id, model.as_any())
2224                        }
2225
2226                        Effect::ViewRelease { view_id, view } => {
2227                            self.handle_entity_release_effect(view_id, view.as_any())
2228                        }
2229
2230                        Effect::Focus { window_id, view_id } => {
2231                            self.handle_focus_effect(window_id, view_id);
2232                        }
2233
2234                        Effect::FocusObservation {
2235                            view_id,
2236                            subscription_id,
2237                            callback,
2238                        } => {
2239                            self.focus_observations.add_or_remove_callback(
2240                                view_id,
2241                                subscription_id,
2242                                callback,
2243                            );
2244                        }
2245
2246                        Effect::ResizeWindow { window_id } => {
2247                            if let Some(window) = self.cx.windows.get_mut(&window_id) {
2248                                window
2249                                    .invalidation
2250                                    .get_or_insert(WindowInvalidation::default());
2251                            }
2252                        }
2253
2254                        Effect::WindowActivationObservation {
2255                            window_id,
2256                            subscription_id,
2257                            callback,
2258                        } => self.window_activation_observations.add_or_remove_callback(
2259                            window_id,
2260                            subscription_id,
2261                            callback,
2262                        ),
2263
2264                        Effect::ActivateWindow {
2265                            window_id,
2266                            is_active,
2267                        } => self.handle_window_activation_effect(window_id, is_active),
2268
2269                        Effect::WindowFullscreenObservation {
2270                            window_id,
2271                            subscription_id,
2272                            callback,
2273                        } => self.window_fullscreen_observations.add_or_remove_callback(
2274                            window_id,
2275                            subscription_id,
2276                            callback,
2277                        ),
2278
2279                        Effect::FullscreenWindow {
2280                            window_id,
2281                            is_fullscreen,
2282                        } => self.handle_fullscreen_effect(window_id, is_fullscreen),
2283
2284                        Effect::RefreshWindows => {
2285                            refreshing = true;
2286                        }
2287                        Effect::DispatchActionFrom {
2288                            window_id,
2289                            view_id,
2290                            action,
2291                        } => {
2292                            self.handle_dispatch_action_from_effect(
2293                                window_id,
2294                                Some(view_id),
2295                                action.as_ref(),
2296                            );
2297                        }
2298                        Effect::ActionDispatchNotification { action_id } => {
2299                            self.handle_action_dispatch_notification_effect(action_id)
2300                        }
2301                        Effect::WindowShouldCloseSubscription {
2302                            window_id,
2303                            callback,
2304                        } => {
2305                            self.handle_window_should_close_subscription_effect(window_id, callback)
2306                        }
2307                    }
2308                    self.pending_notifications.clear();
2309                    self.remove_dropped_entities();
2310                } else {
2311                    self.remove_dropped_entities();
2312                    if refreshing {
2313                        self.perform_window_refresh();
2314                    } else {
2315                        self.update_windows();
2316                    }
2317
2318                    if self.pending_effects.is_empty() {
2319                        for callback in after_window_update_callbacks.drain(..) {
2320                            callback(self);
2321                        }
2322
2323                        if self.pending_effects.is_empty() {
2324                            self.flushing_effects = false;
2325                            self.pending_notifications.clear();
2326                            self.pending_global_notifications.clear();
2327                            break;
2328                        }
2329                    }
2330
2331                    refreshing = false;
2332                }
2333            }
2334        }
2335    }
2336
2337    fn update_windows(&mut self) {
2338        let mut invalidations: HashMap<_, _> = Default::default();
2339        for (window_id, window) in &mut self.cx.windows {
2340            if let Some(invalidation) = window.invalidation.take() {
2341                invalidations.insert(*window_id, invalidation);
2342            }
2343        }
2344
2345        for (window_id, mut invalidation) in invalidations {
2346            if let Some((presenter, mut window)) =
2347                self.presenters_and_platform_windows.remove(&window_id)
2348            {
2349                {
2350                    let mut presenter = presenter.borrow_mut();
2351                    presenter.invalidate(&mut invalidation, self);
2352                    let scene =
2353                        presenter.build_scene(window.size(), window.scale_factor(), false, self);
2354                    window.present_scene(scene);
2355                }
2356                self.presenters_and_platform_windows
2357                    .insert(window_id, (presenter, window));
2358            }
2359        }
2360    }
2361
2362    fn window_was_resized(&mut self, window_id: usize) {
2363        self.pending_effects
2364            .push_back(Effect::ResizeWindow { window_id });
2365    }
2366
2367    fn window_was_fullscreen_changed(&mut self, window_id: usize, is_fullscreen: bool) {
2368        self.pending_effects.push_back(Effect::FullscreenWindow {
2369            window_id,
2370            is_fullscreen,
2371        });
2372    }
2373
2374    fn window_changed_active_status(&mut self, window_id: usize, is_active: bool) {
2375        self.pending_effects.push_back(Effect::ActivateWindow {
2376            window_id,
2377            is_active,
2378        });
2379    }
2380
2381    pub fn refresh_windows(&mut self) {
2382        self.pending_effects.push_back(Effect::RefreshWindows);
2383    }
2384
2385    pub fn dispatch_action_at(&mut self, window_id: usize, view_id: usize, action: impl Action) {
2386        self.dispatch_any_action_at(window_id, view_id, Box::new(action));
2387    }
2388
2389    pub fn dispatch_any_action_at(
2390        &mut self,
2391        window_id: usize,
2392        view_id: usize,
2393        action: Box<dyn Action>,
2394    ) {
2395        self.pending_effects.push_back(Effect::DispatchActionFrom {
2396            window_id,
2397            view_id,
2398            action,
2399        });
2400    }
2401
2402    fn perform_window_refresh(&mut self) {
2403        let mut presenters = mem::take(&mut self.presenters_and_platform_windows);
2404        for (window_id, (presenter, window)) in &mut presenters {
2405            let mut invalidation = self
2406                .cx
2407                .windows
2408                .get_mut(window_id)
2409                .unwrap()
2410                .invalidation
2411                .take();
2412            let mut presenter = presenter.borrow_mut();
2413            presenter.refresh(
2414                invalidation.as_mut().unwrap_or(&mut Default::default()),
2415                self,
2416            );
2417            let scene = presenter.build_scene(window.size(), window.scale_factor(), true, self);
2418            window.present_scene(scene);
2419        }
2420        self.presenters_and_platform_windows = presenters;
2421    }
2422
2423    fn emit_global_event(&mut self, payload: Box<dyn Any>) {
2424        let type_id = (&*payload).type_id();
2425
2426        let mut subscriptions = self.global_subscriptions.clone();
2427        subscriptions.emit_and_cleanup(type_id, self, |callback, this| {
2428            callback(payload.as_ref(), this);
2429            true //Always alive
2430        });
2431    }
2432
2433    fn handle_view_notification_effect(
2434        &mut self,
2435        observed_window_id: usize,
2436        observed_view_id: usize,
2437    ) {
2438        if self
2439            .cx
2440            .views
2441            .contains_key(&(observed_window_id, observed_view_id))
2442        {
2443            if let Some(window) = self.cx.windows.get_mut(&observed_window_id) {
2444                window
2445                    .invalidation
2446                    .get_or_insert_with(Default::default)
2447                    .updated
2448                    .insert(observed_view_id);
2449            }
2450
2451            let mut observations = self.observations.clone();
2452            observations.emit_and_cleanup(observed_view_id, self, |callback, this| callback(this));
2453        }
2454    }
2455
2456    fn handle_entity_release_effect(&mut self, entity_id: usize, entity: &dyn Any) {
2457        let callbacks = self.release_observations.lock().remove(&entity_id);
2458        if let Some(callbacks) = callbacks {
2459            for (_, callback) in callbacks {
2460                callback(entity, self);
2461            }
2462        }
2463    }
2464
2465    fn handle_fullscreen_effect(&mut self, window_id: usize, is_fullscreen: bool) {
2466        //Short circuit evaluation if we're already g2g
2467        if self
2468            .cx
2469            .windows
2470            .get(&window_id)
2471            .map(|w| w.is_fullscreen == is_fullscreen)
2472            .unwrap_or(false)
2473        {
2474            return;
2475        }
2476
2477        self.update(|this| {
2478            let window = this.cx.windows.get_mut(&window_id)?;
2479            window.is_fullscreen = is_fullscreen;
2480
2481            let mut observations = this.window_fullscreen_observations.clone();
2482            observations.emit_and_cleanup(window_id, this, |callback, this| {
2483                callback(is_fullscreen, this)
2484            });
2485
2486            Some(())
2487        });
2488    }
2489
2490    fn handle_window_activation_effect(&mut self, window_id: usize, active: bool) {
2491        //Short circuit evaluation if we're already g2g
2492        if self
2493            .cx
2494            .windows
2495            .get(&window_id)
2496            .map(|w| w.is_active == active)
2497            .unwrap_or(false)
2498        {
2499            return;
2500        }
2501
2502        self.update(|this| {
2503            let window = this.cx.windows.get_mut(&window_id)?;
2504            window.is_active = active;
2505
2506            //Handle focus
2507            let focused_id = window.focused_view_id?;
2508            for view_id in this.parents(window_id, focused_id).collect::<Vec<_>>() {
2509                if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
2510                    if active {
2511                        view.on_focus_in(this, window_id, view_id, focused_id);
2512                    } else {
2513                        view.on_focus_out(this, window_id, view_id, focused_id);
2514                    }
2515                    this.cx.views.insert((window_id, view_id), view);
2516                }
2517            }
2518
2519            let mut observations = this.window_activation_observations.clone();
2520            observations.emit_and_cleanup(window_id, this, |callback, this| callback(active, this));
2521
2522            Some(())
2523        });
2524    }
2525
2526    fn handle_focus_effect(&mut self, window_id: usize, focused_id: Option<usize>) {
2527        self.pending_focus_index.take();
2528
2529        if self
2530            .cx
2531            .windows
2532            .get(&window_id)
2533            .map(|w| w.focused_view_id)
2534            .map_or(false, |cur_focused| cur_focused == focused_id)
2535        {
2536            return;
2537        }
2538
2539        self.update(|this| {
2540            let blurred_id = this.cx.windows.get_mut(&window_id).and_then(|window| {
2541                let blurred_id = window.focused_view_id;
2542                window.focused_view_id = focused_id;
2543                blurred_id
2544            });
2545
2546            let blurred_parents = blurred_id
2547                .map(|blurred_id| this.parents(window_id, blurred_id).collect::<Vec<_>>())
2548                .unwrap_or_default();
2549            let focused_parents = focused_id
2550                .map(|focused_id| this.parents(window_id, focused_id).collect::<Vec<_>>())
2551                .unwrap_or_default();
2552
2553            if let Some(blurred_id) = blurred_id {
2554                for view_id in blurred_parents.iter().copied() {
2555                    if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
2556                        view.on_focus_out(this, window_id, view_id, blurred_id);
2557                        this.cx.views.insert((window_id, view_id), view);
2558                    }
2559                }
2560
2561                let mut subscriptions = this.focus_observations.clone();
2562                subscriptions
2563                    .emit_and_cleanup(blurred_id, this, |callback, this| callback(false, this));
2564            }
2565
2566            if let Some(focused_id) = focused_id {
2567                for view_id in focused_parents {
2568                    if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
2569                        view.on_focus_in(this, window_id, view_id, focused_id);
2570                        this.cx.views.insert((window_id, view_id), view);
2571                    }
2572                }
2573
2574                let mut subscriptions = this.focus_observations.clone();
2575                subscriptions
2576                    .emit_and_cleanup(focused_id, this, |callback, this| callback(true, this));
2577            }
2578        })
2579    }
2580
2581    fn handle_dispatch_action_from_effect(
2582        &mut self,
2583        window_id: usize,
2584        view_id: Option<usize>,
2585        action: &dyn Action,
2586    ) -> bool {
2587        self.update(|this| {
2588            if let Some(view_id) = view_id {
2589                this.halt_action_dispatch = false;
2590                this.visit_dispatch_path(window_id, view_id, |view_id, capture_phase, this| {
2591                    if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
2592                        let type_id = view.as_any().type_id();
2593
2594                        if let Some((name, mut handlers)) = this
2595                            .actions_mut(capture_phase)
2596                            .get_mut(&type_id)
2597                            .and_then(|h| h.remove_entry(&action.id()))
2598                        {
2599                            for handler in handlers.iter_mut().rev() {
2600                                this.halt_action_dispatch = true;
2601                                handler(view.as_mut(), action, this, window_id, view_id);
2602                                if this.halt_action_dispatch {
2603                                    break;
2604                                }
2605                            }
2606                            this.actions_mut(capture_phase)
2607                                .get_mut(&type_id)
2608                                .unwrap()
2609                                .insert(name, handlers);
2610                        }
2611
2612                        this.cx.views.insert((window_id, view_id), view);
2613                    }
2614
2615                    !this.halt_action_dispatch
2616                });
2617            }
2618
2619            if !this.halt_action_dispatch {
2620                this.halt_action_dispatch = this.dispatch_global_action_any(action);
2621            }
2622
2623            this.pending_effects
2624                .push_back(Effect::ActionDispatchNotification {
2625                    action_id: action.id(),
2626                });
2627            this.halt_action_dispatch
2628        })
2629    }
2630
2631    fn handle_action_dispatch_notification_effect(&mut self, action_id: TypeId) {
2632        let mut callbacks = mem::take(&mut *self.action_dispatch_observations.lock());
2633        for callback in callbacks.values_mut() {
2634            callback(action_id, self);
2635        }
2636        self.action_dispatch_observations.lock().extend(callbacks);
2637    }
2638
2639    fn handle_window_should_close_subscription_effect(
2640        &mut self,
2641        window_id: usize,
2642        mut callback: WindowShouldCloseSubscriptionCallback,
2643    ) {
2644        let mut app = self.upgrade();
2645        if let Some((_, window)) = self.presenters_and_platform_windows.get_mut(&window_id) {
2646            window.on_should_close(Box::new(move || app.update(|cx| callback(cx))))
2647        }
2648    }
2649
2650    pub fn focus(&mut self, window_id: usize, view_id: Option<usize>) {
2651        if let Some(pending_focus_index) = self.pending_focus_index {
2652            self.pending_effects.remove(pending_focus_index);
2653        }
2654        self.pending_focus_index = Some(self.pending_effects.len());
2655        self.pending_effects
2656            .push_back(Effect::Focus { window_id, view_id });
2657    }
2658
2659    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
2660    where
2661        F: FnOnce(AsyncAppContext) -> Fut,
2662        Fut: 'static + Future<Output = T>,
2663        T: 'static,
2664    {
2665        let future = f(self.to_async());
2666        let cx = self.to_async();
2667        self.foreground.spawn(async move {
2668            let result = future.await;
2669            cx.0.borrow_mut().flush_effects();
2670            result
2671        })
2672    }
2673
2674    pub fn to_async(&self) -> AsyncAppContext {
2675        AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
2676    }
2677
2678    pub fn write_to_clipboard(&self, item: ClipboardItem) {
2679        self.cx.platform.write_to_clipboard(item);
2680    }
2681
2682    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
2683        self.cx.platform.read_from_clipboard()
2684    }
2685
2686    #[cfg(any(test, feature = "test-support"))]
2687    pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
2688        self.cx.ref_counts.lock().leak_detector.clone()
2689    }
2690}
2691
2692impl ReadModel for MutableAppContext {
2693    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2694        if let Some(model) = self.cx.models.get(&handle.model_id) {
2695            model
2696                .as_any()
2697                .downcast_ref()
2698                .expect("downcast is type safe")
2699        } else {
2700            panic!("circular model reference");
2701        }
2702    }
2703}
2704
2705impl UpdateModel for MutableAppContext {
2706    fn update_model<T: Entity, V>(
2707        &mut self,
2708        handle: &ModelHandle<T>,
2709        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
2710    ) -> V {
2711        if let Some(mut model) = self.cx.models.remove(&handle.model_id) {
2712            self.update(|this| {
2713                let mut cx = ModelContext::new(this, handle.model_id);
2714                let result = update(
2715                    model
2716                        .as_any_mut()
2717                        .downcast_mut()
2718                        .expect("downcast is type safe"),
2719                    &mut cx,
2720                );
2721                this.cx.models.insert(handle.model_id, model);
2722                result
2723            })
2724        } else {
2725            panic!("circular model update");
2726        }
2727    }
2728}
2729
2730impl UpgradeModelHandle for MutableAppContext {
2731    fn upgrade_model_handle<T: Entity>(
2732        &self,
2733        handle: &WeakModelHandle<T>,
2734    ) -> Option<ModelHandle<T>> {
2735        self.cx.upgrade_model_handle(handle)
2736    }
2737
2738    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2739        self.cx.model_handle_is_upgradable(handle)
2740    }
2741
2742    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2743        self.cx.upgrade_any_model_handle(handle)
2744    }
2745}
2746
2747impl UpgradeViewHandle for MutableAppContext {
2748    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2749        self.cx.upgrade_view_handle(handle)
2750    }
2751
2752    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
2753        self.cx.upgrade_any_view_handle(handle)
2754    }
2755}
2756
2757impl ReadView for MutableAppContext {
2758    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2759        if let Some(view) = self.cx.views.get(&(handle.window_id, handle.view_id)) {
2760            view.as_any().downcast_ref().expect("downcast is type safe")
2761        } else {
2762            panic!("circular view reference for type {}", type_name::<T>());
2763        }
2764    }
2765}
2766
2767impl UpdateView for MutableAppContext {
2768    fn update_view<T, S>(
2769        &mut self,
2770        handle: &ViewHandle<T>,
2771        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
2772    ) -> S
2773    where
2774        T: View,
2775    {
2776        self.update(|this| {
2777            let mut view = this
2778                .cx
2779                .views
2780                .remove(&(handle.window_id, handle.view_id))
2781                .expect("circular view update");
2782
2783            let mut cx = ViewContext::new(this, handle.window_id, handle.view_id);
2784            let result = update(
2785                view.as_any_mut()
2786                    .downcast_mut()
2787                    .expect("downcast is type safe"),
2788                &mut cx,
2789            );
2790            this.cx
2791                .views
2792                .insert((handle.window_id, handle.view_id), view);
2793            result
2794        })
2795    }
2796}
2797
2798impl AsRef<AppContext> for MutableAppContext {
2799    fn as_ref(&self) -> &AppContext {
2800        &self.cx
2801    }
2802}
2803
2804impl Deref for MutableAppContext {
2805    type Target = AppContext;
2806
2807    fn deref(&self) -> &Self::Target {
2808        &self.cx
2809    }
2810}
2811
2812#[derive(Debug)]
2813pub enum ParentId {
2814    View(usize),
2815    Root,
2816}
2817
2818pub struct AppContext {
2819    models: HashMap<usize, Box<dyn AnyModel>>,
2820    views: HashMap<(usize, usize), Box<dyn AnyView>>,
2821    pub(crate) parents: HashMap<(usize, usize), ParentId>,
2822    windows: HashMap<usize, Window>,
2823    globals: HashMap<TypeId, Box<dyn Any>>,
2824    element_states: HashMap<ElementStateId, Box<dyn Any>>,
2825    background: Arc<executor::Background>,
2826    ref_counts: Arc<Mutex<RefCounts>>,
2827    font_cache: Arc<FontCache>,
2828    platform: Arc<dyn Platform>,
2829}
2830
2831impl AppContext {
2832    pub(crate) fn root_view(&self, window_id: usize) -> Option<AnyViewHandle> {
2833        self.windows
2834            .get(&window_id)
2835            .map(|window| window.root_view.clone())
2836    }
2837
2838    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
2839        self.windows
2840            .get(&window_id)
2841            .map(|window| window.root_view.id())
2842    }
2843
2844    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
2845        self.windows
2846            .get(&window_id)
2847            .and_then(|window| window.focused_view_id)
2848    }
2849
2850    pub fn background(&self) -> &Arc<executor::Background> {
2851        &self.background
2852    }
2853
2854    pub fn font_cache(&self) -> &Arc<FontCache> {
2855        &self.font_cache
2856    }
2857
2858    pub fn platform(&self) -> &Arc<dyn Platform> {
2859        &self.platform
2860    }
2861
2862    pub fn has_global<T: 'static>(&self) -> bool {
2863        self.globals.contains_key(&TypeId::of::<T>())
2864    }
2865
2866    pub fn global<T: 'static>(&self) -> &T {
2867        if let Some(global) = self.globals.get(&TypeId::of::<T>()) {
2868            global.downcast_ref().unwrap()
2869        } else {
2870            panic!("no global has been added for {}", type_name::<T>());
2871        }
2872    }
2873}
2874
2875impl ReadModel for AppContext {
2876    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2877        if let Some(model) = self.models.get(&handle.model_id) {
2878            model
2879                .as_any()
2880                .downcast_ref()
2881                .expect("downcast should be type safe")
2882        } else {
2883            panic!("circular model reference");
2884        }
2885    }
2886}
2887
2888impl UpgradeModelHandle for AppContext {
2889    fn upgrade_model_handle<T: Entity>(
2890        &self,
2891        handle: &WeakModelHandle<T>,
2892    ) -> Option<ModelHandle<T>> {
2893        if self.models.contains_key(&handle.model_id) {
2894            Some(ModelHandle::new(handle.model_id, &self.ref_counts))
2895        } else {
2896            None
2897        }
2898    }
2899
2900    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2901        self.models.contains_key(&handle.model_id)
2902    }
2903
2904    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2905        if self.models.contains_key(&handle.model_id) {
2906            Some(AnyModelHandle::new(
2907                handle.model_id,
2908                handle.model_type,
2909                self.ref_counts.clone(),
2910            ))
2911        } else {
2912            None
2913        }
2914    }
2915}
2916
2917impl UpgradeViewHandle for AppContext {
2918    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2919        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2920            Some(ViewHandle::new(
2921                handle.window_id,
2922                handle.view_id,
2923                &self.ref_counts,
2924            ))
2925        } else {
2926            None
2927        }
2928    }
2929
2930    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
2931        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2932            Some(AnyViewHandle::new(
2933                handle.window_id,
2934                handle.view_id,
2935                handle.view_type,
2936                self.ref_counts.clone(),
2937            ))
2938        } else {
2939            None
2940        }
2941    }
2942}
2943
2944impl ReadView for AppContext {
2945    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2946        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
2947            view.as_any()
2948                .downcast_ref()
2949                .expect("downcast should be type safe")
2950        } else {
2951            panic!("circular view reference");
2952        }
2953    }
2954}
2955
2956struct Window {
2957    root_view: AnyViewHandle,
2958    focused_view_id: Option<usize>,
2959    is_active: bool,
2960    is_fullscreen: bool,
2961    invalidation: Option<WindowInvalidation>,
2962}
2963
2964#[derive(Default, Clone)]
2965pub struct WindowInvalidation {
2966    pub updated: HashSet<usize>,
2967    pub removed: Vec<usize>,
2968}
2969
2970pub enum Effect {
2971    Subscription {
2972        entity_id: usize,
2973        subscription_id: usize,
2974        callback: SubscriptionCallback,
2975    },
2976    Event {
2977        entity_id: usize,
2978        payload: Box<dyn Any>,
2979    },
2980    GlobalSubscription {
2981        type_id: TypeId,
2982        subscription_id: usize,
2983        callback: GlobalSubscriptionCallback,
2984    },
2985    GlobalEvent {
2986        payload: Box<dyn Any>,
2987    },
2988    Observation {
2989        entity_id: usize,
2990        subscription_id: usize,
2991        callback: ObservationCallback,
2992    },
2993    ModelNotification {
2994        model_id: usize,
2995    },
2996    ViewNotification {
2997        window_id: usize,
2998        view_id: usize,
2999    },
3000    Deferred {
3001        callback: Box<dyn FnOnce(&mut MutableAppContext)>,
3002        after_window_update: bool,
3003    },
3004    GlobalNotification {
3005        type_id: TypeId,
3006    },
3007    ModelRelease {
3008        model_id: usize,
3009        model: Box<dyn AnyModel>,
3010    },
3011    ViewRelease {
3012        view_id: usize,
3013        view: Box<dyn AnyView>,
3014    },
3015    Focus {
3016        window_id: usize,
3017        view_id: Option<usize>,
3018    },
3019    FocusObservation {
3020        view_id: usize,
3021        subscription_id: usize,
3022        callback: FocusObservationCallback,
3023    },
3024    ResizeWindow {
3025        window_id: usize,
3026    },
3027    FullscreenWindow {
3028        window_id: usize,
3029        is_fullscreen: bool,
3030    },
3031    ActivateWindow {
3032        window_id: usize,
3033        is_active: bool,
3034    },
3035    WindowActivationObservation {
3036        window_id: usize,
3037        subscription_id: usize,
3038        callback: WindowActivationCallback,
3039    },
3040    WindowFullscreenObservation {
3041        window_id: usize,
3042        subscription_id: usize,
3043        callback: WindowFullscreenCallback,
3044    },
3045    RefreshWindows,
3046    DispatchActionFrom {
3047        window_id: usize,
3048        view_id: usize,
3049        action: Box<dyn Action>,
3050    },
3051    ActionDispatchNotification {
3052        action_id: TypeId,
3053    },
3054    WindowShouldCloseSubscription {
3055        window_id: usize,
3056        callback: WindowShouldCloseSubscriptionCallback,
3057    },
3058}
3059
3060impl Debug for Effect {
3061    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3062        match self {
3063            Effect::Subscription {
3064                entity_id,
3065                subscription_id,
3066                ..
3067            } => f
3068                .debug_struct("Effect::Subscribe")
3069                .field("entity_id", entity_id)
3070                .field("subscription_id", subscription_id)
3071                .finish(),
3072            Effect::Event { entity_id, .. } => f
3073                .debug_struct("Effect::Event")
3074                .field("entity_id", entity_id)
3075                .finish(),
3076            Effect::GlobalSubscription {
3077                type_id,
3078                subscription_id,
3079                ..
3080            } => f
3081                .debug_struct("Effect::Subscribe")
3082                .field("type_id", type_id)
3083                .field("subscription_id", subscription_id)
3084                .finish(),
3085            Effect::GlobalEvent { payload, .. } => f
3086                .debug_struct("Effect::GlobalEvent")
3087                .field("type_id", &(&*payload).type_id())
3088                .finish(),
3089            Effect::Observation {
3090                entity_id,
3091                subscription_id,
3092                ..
3093            } => f
3094                .debug_struct("Effect::Observation")
3095                .field("entity_id", entity_id)
3096                .field("subscription_id", subscription_id)
3097                .finish(),
3098            Effect::ModelNotification { model_id } => f
3099                .debug_struct("Effect::ModelNotification")
3100                .field("model_id", model_id)
3101                .finish(),
3102            Effect::ViewNotification { window_id, view_id } => f
3103                .debug_struct("Effect::ViewNotification")
3104                .field("window_id", window_id)
3105                .field("view_id", view_id)
3106                .finish(),
3107            Effect::GlobalNotification { type_id } => f
3108                .debug_struct("Effect::GlobalNotification")
3109                .field("type_id", type_id)
3110                .finish(),
3111            Effect::Deferred { .. } => f.debug_struct("Effect::Deferred").finish(),
3112            Effect::ModelRelease { model_id, .. } => f
3113                .debug_struct("Effect::ModelRelease")
3114                .field("model_id", model_id)
3115                .finish(),
3116            Effect::ViewRelease { view_id, .. } => f
3117                .debug_struct("Effect::ViewRelease")
3118                .field("view_id", view_id)
3119                .finish(),
3120            Effect::Focus { window_id, view_id } => f
3121                .debug_struct("Effect::Focus")
3122                .field("window_id", window_id)
3123                .field("view_id", view_id)
3124                .finish(),
3125            Effect::FocusObservation {
3126                view_id,
3127                subscription_id,
3128                ..
3129            } => f
3130                .debug_struct("Effect::FocusObservation")
3131                .field("view_id", view_id)
3132                .field("subscription_id", subscription_id)
3133                .finish(),
3134            Effect::DispatchActionFrom {
3135                window_id, view_id, ..
3136            } => f
3137                .debug_struct("Effect::DispatchActionFrom")
3138                .field("window_id", window_id)
3139                .field("view_id", view_id)
3140                .finish(),
3141            Effect::ActionDispatchNotification { action_id, .. } => f
3142                .debug_struct("Effect::ActionDispatchNotification")
3143                .field("action_id", action_id)
3144                .finish(),
3145            Effect::ResizeWindow { window_id } => f
3146                .debug_struct("Effect::RefreshWindow")
3147                .field("window_id", window_id)
3148                .finish(),
3149            Effect::WindowActivationObservation {
3150                window_id,
3151                subscription_id,
3152                ..
3153            } => f
3154                .debug_struct("Effect::WindowActivationObservation")
3155                .field("window_id", window_id)
3156                .field("subscription_id", subscription_id)
3157                .finish(),
3158            Effect::ActivateWindow {
3159                window_id,
3160                is_active,
3161            } => f
3162                .debug_struct("Effect::ActivateWindow")
3163                .field("window_id", window_id)
3164                .field("is_active", is_active)
3165                .finish(),
3166            Effect::FullscreenWindow {
3167                window_id,
3168                is_fullscreen,
3169            } => f
3170                .debug_struct("Effect::FullscreenWindow")
3171                .field("window_id", window_id)
3172                .field("is_fullscreen", is_fullscreen)
3173                .finish(),
3174            Effect::WindowFullscreenObservation {
3175                window_id,
3176                subscription_id,
3177                callback: _,
3178            } => f
3179                .debug_struct("Effect::WindowFullscreenObservation")
3180                .field("window_id", window_id)
3181                .field("subscription_id", subscription_id)
3182                .finish(),
3183            Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
3184            Effect::WindowShouldCloseSubscription { window_id, .. } => f
3185                .debug_struct("Effect::WindowShouldCloseSubscription")
3186                .field("window_id", window_id)
3187                .finish(),
3188        }
3189    }
3190}
3191
3192pub trait AnyModel {
3193    fn as_any(&self) -> &dyn Any;
3194    fn as_any_mut(&mut self) -> &mut dyn Any;
3195    fn release(&mut self, cx: &mut MutableAppContext);
3196    fn app_will_quit(
3197        &mut self,
3198        cx: &mut MutableAppContext,
3199    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
3200}
3201
3202impl<T> AnyModel for T
3203where
3204    T: Entity,
3205{
3206    fn as_any(&self) -> &dyn Any {
3207        self
3208    }
3209
3210    fn as_any_mut(&mut self) -> &mut dyn Any {
3211        self
3212    }
3213
3214    fn release(&mut self, cx: &mut MutableAppContext) {
3215        self.release(cx);
3216    }
3217
3218    fn app_will_quit(
3219        &mut self,
3220        cx: &mut MutableAppContext,
3221    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
3222        self.app_will_quit(cx)
3223    }
3224}
3225
3226pub trait AnyView {
3227    fn as_any(&self) -> &dyn Any;
3228    fn as_any_mut(&mut self) -> &mut dyn Any;
3229    fn release(&mut self, cx: &mut MutableAppContext);
3230    fn app_will_quit(
3231        &mut self,
3232        cx: &mut MutableAppContext,
3233    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
3234    fn ui_name(&self) -> &'static str;
3235    fn render(&mut self, params: RenderParams, cx: &mut MutableAppContext) -> ElementBox;
3236    fn on_focus_in(
3237        &mut self,
3238        cx: &mut MutableAppContext,
3239        window_id: usize,
3240        view_id: usize,
3241        focused_id: usize,
3242    );
3243    fn on_focus_out(
3244        &mut self,
3245        cx: &mut MutableAppContext,
3246        window_id: usize,
3247        view_id: usize,
3248        focused_id: usize,
3249    );
3250    fn keymap_context(&self, cx: &AppContext) -> keymap::Context;
3251    fn debug_json(&self, cx: &AppContext) -> serde_json::Value;
3252
3253    fn text_for_range(&self, range: Range<usize>, cx: &AppContext) -> Option<String>;
3254    fn selected_text_range(&self, cx: &AppContext) -> Option<Range<usize>>;
3255    fn marked_text_range(&self, cx: &AppContext) -> Option<Range<usize>>;
3256    fn unmark_text(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
3257    fn replace_text_in_range(
3258        &mut self,
3259        range: Option<Range<usize>>,
3260        text: &str,
3261        cx: &mut MutableAppContext,
3262        window_id: usize,
3263        view_id: usize,
3264    );
3265    fn replace_and_mark_text_in_range(
3266        &mut self,
3267        range: Option<Range<usize>>,
3268        new_text: &str,
3269        new_selected_range: Option<Range<usize>>,
3270        cx: &mut MutableAppContext,
3271        window_id: usize,
3272        view_id: usize,
3273    );
3274    fn any_handle(&self, window_id: usize, view_id: usize, cx: &AppContext) -> AnyViewHandle {
3275        AnyViewHandle::new(
3276            window_id,
3277            view_id,
3278            self.as_any().type_id(),
3279            cx.ref_counts.clone(),
3280        )
3281    }
3282}
3283
3284impl<T> AnyView for T
3285where
3286    T: View,
3287{
3288    fn as_any(&self) -> &dyn Any {
3289        self
3290    }
3291
3292    fn as_any_mut(&mut self) -> &mut dyn Any {
3293        self
3294    }
3295
3296    fn release(&mut self, cx: &mut MutableAppContext) {
3297        self.release(cx);
3298    }
3299
3300    fn app_will_quit(
3301        &mut self,
3302        cx: &mut MutableAppContext,
3303    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
3304        self.app_will_quit(cx)
3305    }
3306
3307    fn ui_name(&self) -> &'static str {
3308        T::ui_name()
3309    }
3310
3311    fn render(&mut self, params: RenderParams, cx: &mut MutableAppContext) -> ElementBox {
3312        View::render(self, &mut RenderContext::new(params, cx))
3313    }
3314
3315    fn on_focus_in(
3316        &mut self,
3317        cx: &mut MutableAppContext,
3318        window_id: usize,
3319        view_id: usize,
3320        focused_id: usize,
3321    ) {
3322        let mut cx = ViewContext::new(cx, window_id, view_id);
3323        let focused_view_handle: AnyViewHandle = if view_id == focused_id {
3324            cx.handle().into()
3325        } else {
3326            let focused_type = cx
3327                .views
3328                .get(&(window_id, focused_id))
3329                .unwrap()
3330                .as_any()
3331                .type_id();
3332            AnyViewHandle::new(window_id, focused_id, focused_type, cx.ref_counts.clone())
3333        };
3334        View::on_focus_in(self, focused_view_handle, &mut cx);
3335    }
3336
3337    fn on_focus_out(
3338        &mut self,
3339        cx: &mut MutableAppContext,
3340        window_id: usize,
3341        view_id: usize,
3342        blurred_id: usize,
3343    ) {
3344        let mut cx = ViewContext::new(cx, window_id, view_id);
3345        let blurred_view_handle: AnyViewHandle = if view_id == blurred_id {
3346            cx.handle().into()
3347        } else {
3348            let blurred_type = cx
3349                .views
3350                .get(&(window_id, blurred_id))
3351                .unwrap()
3352                .as_any()
3353                .type_id();
3354            AnyViewHandle::new(window_id, blurred_id, blurred_type, cx.ref_counts.clone())
3355        };
3356        View::on_focus_out(self, blurred_view_handle, &mut cx);
3357    }
3358
3359    fn keymap_context(&self, cx: &AppContext) -> keymap::Context {
3360        View::keymap_context(self, cx)
3361    }
3362
3363    fn debug_json(&self, cx: &AppContext) -> serde_json::Value {
3364        View::debug_json(self, cx)
3365    }
3366
3367    fn text_for_range(&self, range: Range<usize>, cx: &AppContext) -> Option<String> {
3368        View::text_for_range(self, range, cx)
3369    }
3370
3371    fn selected_text_range(&self, cx: &AppContext) -> Option<Range<usize>> {
3372        View::selected_text_range(self, cx)
3373    }
3374
3375    fn marked_text_range(&self, cx: &AppContext) -> Option<Range<usize>> {
3376        View::marked_text_range(self, cx)
3377    }
3378
3379    fn unmark_text(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
3380        let mut cx = ViewContext::new(cx, window_id, view_id);
3381        View::unmark_text(self, &mut cx)
3382    }
3383
3384    fn replace_text_in_range(
3385        &mut self,
3386        range: Option<Range<usize>>,
3387        text: &str,
3388        cx: &mut MutableAppContext,
3389        window_id: usize,
3390        view_id: usize,
3391    ) {
3392        let mut cx = ViewContext::new(cx, window_id, view_id);
3393        View::replace_text_in_range(self, range, text, &mut cx)
3394    }
3395
3396    fn replace_and_mark_text_in_range(
3397        &mut self,
3398        range: Option<Range<usize>>,
3399        new_text: &str,
3400        new_selected_range: Option<Range<usize>>,
3401        cx: &mut MutableAppContext,
3402        window_id: usize,
3403        view_id: usize,
3404    ) {
3405        let mut cx = ViewContext::new(cx, window_id, view_id);
3406        View::replace_and_mark_text_in_range(self, range, new_text, new_selected_range, &mut cx)
3407    }
3408}
3409
3410pub struct ModelContext<'a, T: ?Sized> {
3411    app: &'a mut MutableAppContext,
3412    model_id: usize,
3413    model_type: PhantomData<T>,
3414    halt_stream: bool,
3415}
3416
3417impl<'a, T: Entity> ModelContext<'a, T> {
3418    fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
3419        Self {
3420            app,
3421            model_id,
3422            model_type: PhantomData,
3423            halt_stream: false,
3424        }
3425    }
3426
3427    pub fn background(&self) -> &Arc<executor::Background> {
3428        &self.app.cx.background
3429    }
3430
3431    pub fn halt_stream(&mut self) {
3432        self.halt_stream = true;
3433    }
3434
3435    pub fn model_id(&self) -> usize {
3436        self.model_id
3437    }
3438
3439    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
3440    where
3441        S: Entity,
3442        F: FnOnce(&mut ModelContext<S>) -> S,
3443    {
3444        self.app.add_model(build_model)
3445    }
3446
3447    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ModelContext<T>)) {
3448        let handle = self.handle();
3449        self.app.defer(move |cx| {
3450            handle.update(cx, |model, cx| {
3451                callback(model, cx);
3452            })
3453        })
3454    }
3455
3456    pub fn emit(&mut self, payload: T::Event) {
3457        self.app.pending_effects.push_back(Effect::Event {
3458            entity_id: self.model_id,
3459            payload: Box::new(payload),
3460        });
3461    }
3462
3463    pub fn notify(&mut self) {
3464        self.app.notify_model(self.model_id);
3465    }
3466
3467    pub fn subscribe<S: Entity, F>(
3468        &mut self,
3469        handle: &ModelHandle<S>,
3470        mut callback: F,
3471    ) -> Subscription
3472    where
3473        S::Event: 'static,
3474        F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
3475    {
3476        let subscriber = self.weak_handle();
3477        self.app
3478            .subscribe_internal(handle, move |emitter, event, cx| {
3479                if let Some(subscriber) = subscriber.upgrade(cx) {
3480                    subscriber.update(cx, |subscriber, cx| {
3481                        callback(subscriber, emitter, event, cx);
3482                    });
3483                    true
3484                } else {
3485                    false
3486                }
3487            })
3488    }
3489
3490    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
3491    where
3492        S: Entity,
3493        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
3494    {
3495        let observer = self.weak_handle();
3496        self.app.observe_internal(handle, move |observed, cx| {
3497            if let Some(observer) = observer.upgrade(cx) {
3498                observer.update(cx, |observer, cx| {
3499                    callback(observer, observed, cx);
3500                });
3501                true
3502            } else {
3503                false
3504            }
3505        })
3506    }
3507
3508    pub fn observe_global<G, F>(&mut self, mut callback: F) -> Subscription
3509    where
3510        G: Any,
3511        F: 'static + FnMut(&mut T, &mut ModelContext<T>),
3512    {
3513        let observer = self.weak_handle();
3514        self.app.observe_global::<G, _>(move |cx| {
3515            if let Some(observer) = observer.upgrade(cx) {
3516                observer.update(cx, |observer, cx| callback(observer, cx));
3517            }
3518        })
3519    }
3520
3521    pub fn observe_release<S, F>(
3522        &mut self,
3523        handle: &ModelHandle<S>,
3524        mut callback: F,
3525    ) -> Subscription
3526    where
3527        S: Entity,
3528        F: 'static + FnMut(&mut T, &S, &mut ModelContext<T>),
3529    {
3530        let observer = self.weak_handle();
3531        self.app.observe_release(handle, move |released, cx| {
3532            if let Some(observer) = observer.upgrade(cx) {
3533                observer.update(cx, |observer, cx| {
3534                    callback(observer, released, cx);
3535                });
3536            }
3537        })
3538    }
3539
3540    pub fn handle(&self) -> ModelHandle<T> {
3541        ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
3542    }
3543
3544    pub fn weak_handle(&self) -> WeakModelHandle<T> {
3545        WeakModelHandle::new(self.model_id)
3546    }
3547
3548    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
3549    where
3550        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
3551        Fut: 'static + Future<Output = S>,
3552        S: 'static,
3553    {
3554        let handle = self.handle();
3555        self.app.spawn(|cx| f(handle, cx))
3556    }
3557
3558    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
3559    where
3560        F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
3561        Fut: 'static + Future<Output = S>,
3562        S: 'static,
3563    {
3564        let handle = self.weak_handle();
3565        self.app.spawn(|cx| f(handle, cx))
3566    }
3567}
3568
3569impl<M> AsRef<AppContext> for ModelContext<'_, M> {
3570    fn as_ref(&self) -> &AppContext {
3571        &self.app.cx
3572    }
3573}
3574
3575impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
3576    fn as_mut(&mut self) -> &mut MutableAppContext {
3577        self.app
3578    }
3579}
3580
3581impl<M> ReadModel for ModelContext<'_, M> {
3582    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
3583        self.app.read_model(handle)
3584    }
3585}
3586
3587impl<M> UpdateModel for ModelContext<'_, M> {
3588    fn update_model<T: Entity, V>(
3589        &mut self,
3590        handle: &ModelHandle<T>,
3591        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
3592    ) -> V {
3593        self.app.update_model(handle, update)
3594    }
3595}
3596
3597impl<M> UpgradeModelHandle for ModelContext<'_, M> {
3598    fn upgrade_model_handle<T: Entity>(
3599        &self,
3600        handle: &WeakModelHandle<T>,
3601    ) -> Option<ModelHandle<T>> {
3602        self.cx.upgrade_model_handle(handle)
3603    }
3604
3605    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
3606        self.cx.model_handle_is_upgradable(handle)
3607    }
3608
3609    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
3610        self.cx.upgrade_any_model_handle(handle)
3611    }
3612}
3613
3614impl<M> Deref for ModelContext<'_, M> {
3615    type Target = MutableAppContext;
3616
3617    fn deref(&self) -> &Self::Target {
3618        self.app
3619    }
3620}
3621
3622impl<M> DerefMut for ModelContext<'_, M> {
3623    fn deref_mut(&mut self) -> &mut Self::Target {
3624        &mut self.app
3625    }
3626}
3627
3628pub struct ViewContext<'a, T: ?Sized> {
3629    app: &'a mut MutableAppContext,
3630    window_id: usize,
3631    view_id: usize,
3632    view_type: PhantomData<T>,
3633}
3634
3635impl<'a, T: View> ViewContext<'a, T> {
3636    fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
3637        Self {
3638            app,
3639            window_id,
3640            view_id,
3641            view_type: PhantomData,
3642        }
3643    }
3644
3645    pub fn handle(&self) -> ViewHandle<T> {
3646        ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
3647    }
3648
3649    pub fn weak_handle(&self) -> WeakViewHandle<T> {
3650        WeakViewHandle::new(self.window_id, self.view_id)
3651    }
3652
3653    pub fn window_id(&self) -> usize {
3654        self.window_id
3655    }
3656
3657    pub fn view_id(&self) -> usize {
3658        self.view_id
3659    }
3660
3661    pub fn foreground(&self) -> &Rc<executor::Foreground> {
3662        self.app.foreground()
3663    }
3664
3665    pub fn background_executor(&self) -> &Arc<executor::Background> {
3666        &self.app.cx.background
3667    }
3668
3669    pub fn platform(&self) -> Arc<dyn Platform> {
3670        self.app.platform()
3671    }
3672
3673    pub fn show_character_palette(&self) {
3674        self.app.show_character_palette(self.window_id);
3675    }
3676
3677    pub fn minimize_window(&self) {
3678        self.app.minimize_window(self.window_id)
3679    }
3680
3681    pub fn zoom_window(&self) {
3682        self.app.zoom_window(self.window_id)
3683    }
3684
3685    pub fn prompt(
3686        &self,
3687        level: PromptLevel,
3688        msg: &str,
3689        answers: &[&str],
3690    ) -> oneshot::Receiver<usize> {
3691        self.app.prompt(self.window_id, level, msg, answers)
3692    }
3693
3694    pub fn prompt_for_paths(
3695        &self,
3696        options: PathPromptOptions,
3697    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
3698        self.app.prompt_for_paths(options)
3699    }
3700
3701    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
3702        self.app.prompt_for_new_path(directory)
3703    }
3704
3705    pub fn debug_elements(&self) -> crate::json::Value {
3706        self.app.debug_elements(self.window_id).unwrap()
3707    }
3708
3709    pub fn focus<S>(&mut self, handle: S)
3710    where
3711        S: Into<AnyViewHandle>,
3712    {
3713        let handle = handle.into();
3714        self.app.focus(handle.window_id, Some(handle.view_id));
3715    }
3716
3717    pub fn focus_self(&mut self) {
3718        self.app.focus(self.window_id, Some(self.view_id));
3719    }
3720
3721    pub fn is_self_focused(&self) -> bool {
3722        self.app.focused_view_id(self.window_id) == Some(self.view_id)
3723    }
3724
3725    pub fn blur(&mut self) {
3726        self.app.focus(self.window_id, None);
3727    }
3728
3729    pub fn set_window_title(&mut self, title: &str) {
3730        let window_id = self.window_id();
3731        if let Some((_, window)) = self.presenters_and_platform_windows.get_mut(&window_id) {
3732            window.set_title(title);
3733        }
3734    }
3735
3736    pub fn set_window_edited(&mut self, edited: bool) {
3737        let window_id = self.window_id();
3738        if let Some((_, window)) = self.presenters_and_platform_windows.get_mut(&window_id) {
3739            window.set_edited(edited);
3740        }
3741    }
3742
3743    pub fn on_window_should_close<F>(&mut self, mut callback: F)
3744    where
3745        F: 'static + FnMut(&mut T, &mut ViewContext<T>) -> bool,
3746    {
3747        let window_id = self.window_id();
3748        let view = self.weak_handle();
3749        self.pending_effects
3750            .push_back(Effect::WindowShouldCloseSubscription {
3751                window_id,
3752                callback: Box::new(move |cx| {
3753                    if let Some(view) = view.upgrade(cx) {
3754                        view.update(cx, |view, cx| callback(view, cx))
3755                    } else {
3756                        true
3757                    }
3758                }),
3759            });
3760    }
3761
3762    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
3763    where
3764        S: Entity,
3765        F: FnOnce(&mut ModelContext<S>) -> S,
3766    {
3767        self.app.add_model(build_model)
3768    }
3769
3770    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
3771    where
3772        S: View,
3773        F: FnOnce(&mut ViewContext<S>) -> S,
3774    {
3775        self.app
3776            .build_and_insert_view(self.window_id, ParentId::View(self.view_id), |cx| {
3777                Some(build_view(cx))
3778            })
3779            .unwrap()
3780    }
3781
3782    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
3783    where
3784        S: View,
3785        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
3786    {
3787        self.app
3788            .build_and_insert_view(self.window_id, ParentId::View(self.view_id), build_view)
3789    }
3790
3791    pub fn reparent(&mut self, view_handle: impl Into<AnyViewHandle>) {
3792        let view_handle = view_handle.into();
3793        if self.window_id != view_handle.window_id {
3794            panic!("Can't reparent view to a view from a different window");
3795        }
3796        self.cx
3797            .parents
3798            .remove(&(view_handle.window_id, view_handle.view_id));
3799        let new_parent_id = self.view_id;
3800        self.cx.parents.insert(
3801            (view_handle.window_id, view_handle.view_id),
3802            ParentId::View(new_parent_id),
3803        );
3804    }
3805
3806    pub fn replace_root_view<V, F>(&mut self, build_root_view: F) -> ViewHandle<V>
3807    where
3808        V: View,
3809        F: FnOnce(&mut ViewContext<V>) -> V,
3810    {
3811        let window_id = self.window_id;
3812        self.update(|this| {
3813            let root_view = this
3814                .build_and_insert_view(window_id, ParentId::Root, |cx| Some(build_root_view(cx)))
3815                .unwrap();
3816            let window = this.cx.windows.get_mut(&window_id).unwrap();
3817            window.root_view = root_view.clone().into();
3818            window.focused_view_id = Some(root_view.id());
3819            root_view
3820        })
3821    }
3822
3823    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
3824    where
3825        E: Entity,
3826        E::Event: 'static,
3827        H: Handle<E>,
3828        F: 'static + FnMut(&mut T, H, &E::Event, &mut ViewContext<T>),
3829    {
3830        let subscriber = self.weak_handle();
3831        self.app
3832            .subscribe_internal(handle, move |emitter, event, cx| {
3833                if let Some(subscriber) = subscriber.upgrade(cx) {
3834                    subscriber.update(cx, |subscriber, cx| {
3835                        callback(subscriber, emitter, event, cx);
3836                    });
3837                    true
3838                } else {
3839                    false
3840                }
3841            })
3842    }
3843
3844    pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3845    where
3846        E: Entity,
3847        H: Handle<E>,
3848        F: 'static + FnMut(&mut T, H, &mut ViewContext<T>),
3849    {
3850        let observer = self.weak_handle();
3851        self.app.observe_internal(handle, move |observed, cx| {
3852            if let Some(observer) = observer.upgrade(cx) {
3853                observer.update(cx, |observer, cx| {
3854                    callback(observer, observed, cx);
3855                });
3856                true
3857            } else {
3858                false
3859            }
3860        })
3861    }
3862
3863    pub fn observe_focus<F, V>(&mut self, handle: &ViewHandle<V>, mut callback: F) -> Subscription
3864    where
3865        F: 'static + FnMut(&mut T, ViewHandle<V>, bool, &mut ViewContext<T>),
3866        V: View,
3867    {
3868        let observer = self.weak_handle();
3869        self.app
3870            .observe_focus(handle, move |observed, focused, cx| {
3871                if let Some(observer) = observer.upgrade(cx) {
3872                    observer.update(cx, |observer, cx| {
3873                        callback(observer, observed, focused, cx);
3874                    });
3875                    true
3876                } else {
3877                    false
3878                }
3879            })
3880    }
3881
3882    pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3883    where
3884        E: Entity,
3885        H: Handle<E>,
3886        F: 'static + FnMut(&mut T, &E, &mut ViewContext<T>),
3887    {
3888        let observer = self.weak_handle();
3889        self.app.observe_release(handle, move |released, cx| {
3890            if let Some(observer) = observer.upgrade(cx) {
3891                observer.update(cx, |observer, cx| {
3892                    callback(observer, released, cx);
3893                });
3894            }
3895        })
3896    }
3897
3898    pub fn observe_actions<F>(&mut self, mut callback: F) -> Subscription
3899    where
3900        F: 'static + FnMut(&mut T, TypeId, &mut ViewContext<T>),
3901    {
3902        let observer = self.weak_handle();
3903        self.app.observe_actions(move |action_id, cx| {
3904            if let Some(observer) = observer.upgrade(cx) {
3905                observer.update(cx, |observer, cx| {
3906                    callback(observer, action_id, cx);
3907                });
3908            }
3909        })
3910    }
3911
3912    pub fn observe_window_activation<F>(&mut self, mut callback: F) -> Subscription
3913    where
3914        F: 'static + FnMut(&mut T, bool, &mut ViewContext<T>),
3915    {
3916        let observer = self.weak_handle();
3917        self.app
3918            .observe_window_activation(self.window_id(), move |active, cx| {
3919                if let Some(observer) = observer.upgrade(cx) {
3920                    observer.update(cx, |observer, cx| {
3921                        callback(observer, active, cx);
3922                    });
3923                    true
3924                } else {
3925                    false
3926                }
3927            })
3928    }
3929
3930    pub fn observe_fullscreen<F>(&mut self, mut callback: F) -> Subscription
3931    where
3932        F: 'static + FnMut(&mut T, bool, &mut ViewContext<T>),
3933    {
3934        let observer = self.weak_handle();
3935        self.app
3936            .observe_fullscreen(self.window_id(), move |active, cx| {
3937                if let Some(observer) = observer.upgrade(cx) {
3938                    observer.update(cx, |observer, cx| {
3939                        callback(observer, active, cx);
3940                    });
3941                    true
3942                } else {
3943                    false
3944                }
3945            })
3946    }
3947
3948    pub fn emit(&mut self, payload: T::Event) {
3949        self.app.pending_effects.push_back(Effect::Event {
3950            entity_id: self.view_id,
3951            payload: Box::new(payload),
3952        });
3953    }
3954
3955    pub fn notify(&mut self) {
3956        self.app.notify_view(self.window_id, self.view_id);
3957    }
3958
3959    pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
3960        self.app
3961            .dispatch_any_action_at(self.window_id, self.view_id, action)
3962    }
3963
3964    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>)) {
3965        let handle = self.handle();
3966        self.app.defer(move |cx| {
3967            handle.update(cx, |view, cx| {
3968                callback(view, cx);
3969            })
3970        })
3971    }
3972
3973    pub fn after_window_update(
3974        &mut self,
3975        callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>),
3976    ) {
3977        let handle = self.handle();
3978        self.app.after_window_update(move |cx| {
3979            handle.update(cx, |view, cx| {
3980                callback(view, cx);
3981            })
3982        })
3983    }
3984
3985    pub fn propagate_action(&mut self) {
3986        self.app.halt_action_dispatch = false;
3987    }
3988
3989    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
3990    where
3991        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
3992        Fut: 'static + Future<Output = S>,
3993        S: 'static,
3994    {
3995        let handle = self.handle();
3996        self.app.spawn(|cx| f(handle, cx))
3997    }
3998
3999    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
4000    where
4001        F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut,
4002        Fut: 'static + Future<Output = S>,
4003        S: 'static,
4004    {
4005        let handle = self.weak_handle();
4006        self.app.spawn(|cx| f(handle, cx))
4007    }
4008}
4009
4010pub struct RenderParams {
4011    pub window_id: usize,
4012    pub view_id: usize,
4013    pub titlebar_height: f32,
4014    pub hovered_region_ids: HashSet<MouseRegionId>,
4015    pub clicked_region_ids: Option<(Vec<MouseRegionId>, MouseButton)>,
4016    pub refreshing: bool,
4017}
4018
4019pub struct RenderContext<'a, T: View> {
4020    pub(crate) window_id: usize,
4021    pub(crate) view_id: usize,
4022    pub(crate) view_type: PhantomData<T>,
4023    pub(crate) hovered_region_ids: HashSet<MouseRegionId>,
4024    pub(crate) clicked_region_ids: Option<(Vec<MouseRegionId>, MouseButton)>,
4025    pub app: &'a mut MutableAppContext,
4026    pub titlebar_height: f32,
4027    pub refreshing: bool,
4028}
4029
4030#[derive(Clone, Copy, Default)]
4031pub struct MouseState {
4032    pub hovered: bool,
4033    pub clicked: Option<MouseButton>,
4034}
4035
4036impl<'a, V: View> RenderContext<'a, V> {
4037    fn new(params: RenderParams, app: &'a mut MutableAppContext) -> Self {
4038        Self {
4039            app,
4040            window_id: params.window_id,
4041            view_id: params.view_id,
4042            view_type: PhantomData,
4043            titlebar_height: params.titlebar_height,
4044            hovered_region_ids: params.hovered_region_ids.clone(),
4045            clicked_region_ids: params.clicked_region_ids.clone(),
4046            refreshing: params.refreshing,
4047        }
4048    }
4049
4050    pub fn handle(&self) -> WeakViewHandle<V> {
4051        WeakViewHandle::new(self.window_id, self.view_id)
4052    }
4053
4054    pub fn window_id(&self) -> usize {
4055        self.window_id
4056    }
4057
4058    pub fn view_id(&self) -> usize {
4059        self.view_id
4060    }
4061
4062    pub fn mouse_state<Tag: 'static>(&self, region_id: usize) -> MouseState {
4063        let region_id = MouseRegionId {
4064            view_id: self.view_id,
4065            discriminant: (TypeId::of::<Tag>(), region_id),
4066        };
4067        MouseState {
4068            hovered: self.hovered_region_ids.contains(&region_id),
4069            clicked: self.clicked_region_ids.as_ref().and_then(|(ids, button)| {
4070                if ids.contains(&region_id) {
4071                    Some(*button)
4072                } else {
4073                    None
4074                }
4075            }),
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            false,
6029            cx,
6030        );
6031        assert_eq!(mouse_down_count.load(SeqCst), 1);
6032    }
6033
6034    #[crate::test(self)]
6035    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
6036        struct Model {
6037            released: Rc<Cell<bool>>,
6038        }
6039
6040        struct View {
6041            released: Rc<Cell<bool>>,
6042        }
6043
6044        impl Entity for Model {
6045            type Event = ();
6046
6047            fn release(&mut self, _: &mut MutableAppContext) {
6048                self.released.set(true);
6049            }
6050        }
6051
6052        impl Entity for View {
6053            type Event = ();
6054
6055            fn release(&mut self, _: &mut MutableAppContext) {
6056                self.released.set(true);
6057            }
6058        }
6059
6060        impl super::View for View {
6061            fn ui_name() -> &'static str {
6062                "View"
6063            }
6064
6065            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6066                Empty::new().boxed()
6067            }
6068        }
6069
6070        let model_released = Rc::new(Cell::new(false));
6071        let model_release_observed = Rc::new(Cell::new(false));
6072        let view_released = Rc::new(Cell::new(false));
6073        let view_release_observed = Rc::new(Cell::new(false));
6074
6075        let model = cx.add_model(|_| Model {
6076            released: model_released.clone(),
6077        });
6078        let (window_id, view) = cx.add_window(Default::default(), |_| View {
6079            released: view_released.clone(),
6080        });
6081        assert!(!model_released.get());
6082        assert!(!view_released.get());
6083
6084        cx.observe_release(&model, {
6085            let model_release_observed = model_release_observed.clone();
6086            move |_, _| model_release_observed.set(true)
6087        })
6088        .detach();
6089        cx.observe_release(&view, {
6090            let view_release_observed = view_release_observed.clone();
6091            move |_, _| view_release_observed.set(true)
6092        })
6093        .detach();
6094
6095        cx.update(move |_| {
6096            drop(model);
6097        });
6098        assert!(model_released.get());
6099        assert!(model_release_observed.get());
6100
6101        drop(view);
6102        cx.remove_window(window_id);
6103        assert!(view_released.get());
6104        assert!(view_release_observed.get());
6105    }
6106
6107    #[crate::test(self)]
6108    fn test_view_events(cx: &mut MutableAppContext) {
6109        #[derive(Default)]
6110        struct View {
6111            events: Vec<usize>,
6112        }
6113
6114        impl Entity for View {
6115            type Event = usize;
6116        }
6117
6118        impl super::View for View {
6119            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6120                Empty::new().boxed()
6121            }
6122
6123            fn ui_name() -> &'static str {
6124                "View"
6125            }
6126        }
6127
6128        struct Model;
6129
6130        impl Entity for Model {
6131            type Event = usize;
6132        }
6133
6134        let (_, handle_1) = cx.add_window(Default::default(), |_| View::default());
6135        let handle_2 = cx.add_view(&handle_1, |_| View::default());
6136        let handle_3 = cx.add_model(|_| Model);
6137
6138        handle_1.update(cx, |_, cx| {
6139            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
6140                me.events.push(*event);
6141
6142                cx.subscribe(&emitter, |me, _, event, _| {
6143                    me.events.push(*event * 2);
6144                })
6145                .detach();
6146            })
6147            .detach();
6148
6149            cx.subscribe(&handle_3, |me, _, event, _| {
6150                me.events.push(*event);
6151            })
6152            .detach();
6153        });
6154
6155        handle_2.update(cx, |_, c| c.emit(7));
6156        assert_eq!(handle_1.read(cx).events, vec![7]);
6157
6158        handle_2.update(cx, |_, c| c.emit(5));
6159        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
6160
6161        handle_3.update(cx, |_, c| c.emit(9));
6162        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
6163    }
6164
6165    #[crate::test(self)]
6166    fn test_global_events(cx: &mut MutableAppContext) {
6167        #[derive(Clone, Debug, Eq, PartialEq)]
6168        struct GlobalEvent(u64);
6169
6170        let events = Rc::new(RefCell::new(Vec::new()));
6171        let first_subscription;
6172        let second_subscription;
6173
6174        {
6175            let events = events.clone();
6176            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
6177                events.borrow_mut().push(("First", e.clone()));
6178            });
6179        }
6180
6181        {
6182            let events = events.clone();
6183            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
6184                events.borrow_mut().push(("Second", e.clone()));
6185            });
6186        }
6187
6188        cx.update(|cx| {
6189            cx.emit_global(GlobalEvent(1));
6190            cx.emit_global(GlobalEvent(2));
6191        });
6192
6193        drop(first_subscription);
6194
6195        cx.update(|cx| {
6196            cx.emit_global(GlobalEvent(3));
6197        });
6198
6199        drop(second_subscription);
6200
6201        cx.update(|cx| {
6202            cx.emit_global(GlobalEvent(4));
6203        });
6204
6205        assert_eq!(
6206            &*events.borrow(),
6207            &[
6208                ("First", GlobalEvent(1)),
6209                ("Second", GlobalEvent(1)),
6210                ("First", GlobalEvent(2)),
6211                ("Second", GlobalEvent(2)),
6212                ("Second", GlobalEvent(3)),
6213            ]
6214        );
6215    }
6216
6217    #[crate::test(self)]
6218    fn test_global_events_emitted_before_subscription_in_same_update_cycle(
6219        cx: &mut MutableAppContext,
6220    ) {
6221        let events = Rc::new(RefCell::new(Vec::new()));
6222        cx.update(|cx| {
6223            {
6224                let events = events.clone();
6225                drop(cx.subscribe_global(move |_: &(), _| {
6226                    events.borrow_mut().push("dropped before emit");
6227                }));
6228            }
6229
6230            {
6231                let events = events.clone();
6232                cx.subscribe_global(move |_: &(), _| {
6233                    events.borrow_mut().push("before emit");
6234                })
6235                .detach();
6236            }
6237
6238            cx.emit_global(());
6239
6240            {
6241                let events = events.clone();
6242                cx.subscribe_global(move |_: &(), _| {
6243                    events.borrow_mut().push("after emit");
6244                })
6245                .detach();
6246            }
6247        });
6248
6249        assert_eq!(*events.borrow(), ["before emit"]);
6250    }
6251
6252    #[crate::test(self)]
6253    fn test_global_nested_events(cx: &mut MutableAppContext) {
6254        #[derive(Clone, Debug, Eq, PartialEq)]
6255        struct GlobalEvent(u64);
6256
6257        let events = Rc::new(RefCell::new(Vec::new()));
6258
6259        {
6260            let events = events.clone();
6261            cx.subscribe_global(move |e: &GlobalEvent, cx| {
6262                events.borrow_mut().push(("Outer", e.clone()));
6263
6264                if e.0 == 1 {
6265                    let events = events.clone();
6266                    cx.subscribe_global(move |e: &GlobalEvent, _| {
6267                        events.borrow_mut().push(("Inner", e.clone()));
6268                    })
6269                    .detach();
6270                }
6271            })
6272            .detach();
6273        }
6274
6275        cx.update(|cx| {
6276            cx.emit_global(GlobalEvent(1));
6277            cx.emit_global(GlobalEvent(2));
6278            cx.emit_global(GlobalEvent(3));
6279        });
6280        cx.update(|cx| {
6281            cx.emit_global(GlobalEvent(4));
6282        });
6283
6284        assert_eq!(
6285            &*events.borrow(),
6286            &[
6287                ("Outer", GlobalEvent(1)),
6288                ("Outer", GlobalEvent(2)),
6289                ("Outer", GlobalEvent(3)),
6290                ("Outer", GlobalEvent(4)),
6291                ("Inner", GlobalEvent(4)),
6292            ]
6293        );
6294    }
6295
6296    #[crate::test(self)]
6297    fn test_global(cx: &mut MutableAppContext) {
6298        type Global = usize;
6299
6300        let observation_count = Rc::new(RefCell::new(0));
6301        let subscription = cx.observe_global::<Global, _>({
6302            let observation_count = observation_count.clone();
6303            move |_| {
6304                *observation_count.borrow_mut() += 1;
6305            }
6306        });
6307
6308        assert!(!cx.has_global::<Global>());
6309        assert_eq!(cx.default_global::<Global>(), &0);
6310        assert_eq!(*observation_count.borrow(), 1);
6311        assert!(cx.has_global::<Global>());
6312        assert_eq!(
6313            cx.update_global::<Global, _, _>(|global, _| {
6314                *global = 1;
6315                "Update Result"
6316            }),
6317            "Update Result"
6318        );
6319        assert_eq!(*observation_count.borrow(), 2);
6320        assert_eq!(cx.global::<Global>(), &1);
6321
6322        drop(subscription);
6323        cx.update_global::<Global, _, _>(|global, _| {
6324            *global = 2;
6325        });
6326        assert_eq!(*observation_count.borrow(), 2);
6327
6328        type OtherGlobal = f32;
6329
6330        let observation_count = Rc::new(RefCell::new(0));
6331        cx.observe_global::<OtherGlobal, _>({
6332            let observation_count = observation_count.clone();
6333            move |_| {
6334                *observation_count.borrow_mut() += 1;
6335            }
6336        })
6337        .detach();
6338
6339        assert_eq!(
6340            cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
6341                assert_eq!(global, &0.0);
6342                *global = 2.0;
6343                "Default update result"
6344            }),
6345            "Default update result"
6346        );
6347        assert_eq!(cx.global::<OtherGlobal>(), &2.0);
6348        assert_eq!(*observation_count.borrow(), 1);
6349    }
6350
6351    #[crate::test(self)]
6352    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
6353        struct View;
6354
6355        impl Entity for View {
6356            type Event = ();
6357        }
6358
6359        impl super::View for View {
6360            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6361                Empty::new().boxed()
6362            }
6363
6364            fn ui_name() -> &'static str {
6365                "View"
6366            }
6367        }
6368
6369        struct Model;
6370
6371        impl Entity for Model {
6372            type Event = ();
6373        }
6374
6375        let (_, root_view) = cx.add_window(Default::default(), |_| View);
6376        let observing_view = cx.add_view(&root_view, |_| View);
6377        let emitting_view = cx.add_view(&root_view, |_| View);
6378        let observing_model = cx.add_model(|_| Model);
6379        let observed_model = cx.add_model(|_| Model);
6380
6381        observing_view.update(cx, |_, cx| {
6382            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
6383            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
6384        });
6385        observing_model.update(cx, |_, cx| {
6386            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
6387        });
6388
6389        cx.update(|_| {
6390            drop(observing_view);
6391            drop(observing_model);
6392        });
6393
6394        emitting_view.update(cx, |_, cx| cx.emit(()));
6395        observed_model.update(cx, |_, cx| cx.emit(()));
6396    }
6397
6398    #[crate::test(self)]
6399    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
6400        #[derive(Default)]
6401        struct TestView;
6402
6403        impl Entity for TestView {
6404            type Event = ();
6405        }
6406
6407        impl View for TestView {
6408            fn ui_name() -> &'static str {
6409                "TestView"
6410            }
6411
6412            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6413                Empty::new().boxed()
6414            }
6415        }
6416
6417        let events = Rc::new(RefCell::new(Vec::new()));
6418        cx.add_window(Default::default(), |cx| {
6419            drop(cx.subscribe(&cx.handle(), {
6420                let events = events.clone();
6421                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
6422            }));
6423            cx.subscribe(&cx.handle(), {
6424                let events = events.clone();
6425                move |_, _, _, _| events.borrow_mut().push("before emit")
6426            })
6427            .detach();
6428            cx.emit(());
6429            cx.subscribe(&cx.handle(), {
6430                let events = events.clone();
6431                move |_, _, _, _| events.borrow_mut().push("after emit")
6432            })
6433            .detach();
6434            TestView
6435        });
6436        assert_eq!(*events.borrow(), ["before emit"]);
6437    }
6438
6439    #[crate::test(self)]
6440    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
6441        #[derive(Default)]
6442        struct View {
6443            events: Vec<usize>,
6444        }
6445
6446        impl Entity for View {
6447            type Event = usize;
6448        }
6449
6450        impl super::View for View {
6451            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6452                Empty::new().boxed()
6453            }
6454
6455            fn ui_name() -> &'static str {
6456                "View"
6457            }
6458        }
6459
6460        #[derive(Default)]
6461        struct Model {
6462            count: usize,
6463        }
6464
6465        impl Entity for Model {
6466            type Event = ();
6467        }
6468
6469        let (_, view) = cx.add_window(Default::default(), |_| View::default());
6470        let model = cx.add_model(|_| Model::default());
6471
6472        view.update(cx, |_, c| {
6473            c.observe(&model, |me, observed, c| {
6474                me.events.push(observed.read(c).count)
6475            })
6476            .detach();
6477        });
6478
6479        model.update(cx, |model, c| {
6480            model.count = 11;
6481            c.notify();
6482        });
6483        assert_eq!(view.read(cx).events, vec![11]);
6484    }
6485
6486    #[crate::test(self)]
6487    fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
6488        #[derive(Default)]
6489        struct TestView;
6490
6491        impl Entity for TestView {
6492            type Event = ();
6493        }
6494
6495        impl View for TestView {
6496            fn ui_name() -> &'static str {
6497                "TestView"
6498            }
6499
6500            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6501                Empty::new().boxed()
6502            }
6503        }
6504
6505        let events = Rc::new(RefCell::new(Vec::new()));
6506        cx.add_window(Default::default(), |cx| {
6507            drop(cx.observe(&cx.handle(), {
6508                let events = events.clone();
6509                move |_, _, _| events.borrow_mut().push("dropped before flush")
6510            }));
6511            cx.observe(&cx.handle(), {
6512                let events = events.clone();
6513                move |_, _, _| events.borrow_mut().push("before notify")
6514            })
6515            .detach();
6516            cx.notify();
6517            cx.observe(&cx.handle(), {
6518                let events = events.clone();
6519                move |_, _, _| events.borrow_mut().push("after notify")
6520            })
6521            .detach();
6522            TestView
6523        });
6524        assert_eq!(*events.borrow(), ["before notify"]);
6525    }
6526
6527    #[crate::test(self)]
6528    fn test_dropping_observers(cx: &mut MutableAppContext) {
6529        struct View;
6530
6531        impl Entity for View {
6532            type Event = ();
6533        }
6534
6535        impl super::View for View {
6536            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6537                Empty::new().boxed()
6538            }
6539
6540            fn ui_name() -> &'static str {
6541                "View"
6542            }
6543        }
6544
6545        struct Model;
6546
6547        impl Entity for Model {
6548            type Event = ();
6549        }
6550
6551        let (_, root_view) = cx.add_window(Default::default(), |_| View);
6552        let observing_view = cx.add_view(root_view, |_| View);
6553        let observing_model = cx.add_model(|_| Model);
6554        let observed_model = cx.add_model(|_| Model);
6555
6556        observing_view.update(cx, |_, cx| {
6557            cx.observe(&observed_model, |_, _, _| {}).detach();
6558        });
6559        observing_model.update(cx, |_, cx| {
6560            cx.observe(&observed_model, |_, _, _| {}).detach();
6561        });
6562
6563        cx.update(|_| {
6564            drop(observing_view);
6565            drop(observing_model);
6566        });
6567
6568        observed_model.update(cx, |_, cx| cx.notify());
6569    }
6570
6571    #[crate::test(self)]
6572    fn test_dropping_subscriptions_during_callback(cx: &mut MutableAppContext) {
6573        struct Model;
6574
6575        impl Entity for Model {
6576            type Event = u64;
6577        }
6578
6579        // Events
6580        let observing_model = cx.add_model(|_| Model);
6581        let observed_model = cx.add_model(|_| Model);
6582
6583        let events = Rc::new(RefCell::new(Vec::new()));
6584
6585        observing_model.update(cx, |_, cx| {
6586            let events = events.clone();
6587            let subscription = Rc::new(RefCell::new(None));
6588            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
6589                let subscription = subscription.clone();
6590                move |_, _, e, _| {
6591                    subscription.borrow_mut().take();
6592                    events.borrow_mut().push(*e);
6593                }
6594            }));
6595        });
6596
6597        observed_model.update(cx, |_, cx| {
6598            cx.emit(1);
6599            cx.emit(2);
6600        });
6601
6602        assert_eq!(*events.borrow(), [1]);
6603
6604        // Global Events
6605        #[derive(Clone, Debug, Eq, PartialEq)]
6606        struct GlobalEvent(u64);
6607
6608        let events = Rc::new(RefCell::new(Vec::new()));
6609
6610        {
6611            let events = events.clone();
6612            let subscription = Rc::new(RefCell::new(None));
6613            *subscription.borrow_mut() = Some(cx.subscribe_global({
6614                let subscription = subscription.clone();
6615                move |e: &GlobalEvent, _| {
6616                    subscription.borrow_mut().take();
6617                    events.borrow_mut().push(e.clone());
6618                }
6619            }));
6620        }
6621
6622        cx.update(|cx| {
6623            cx.emit_global(GlobalEvent(1));
6624            cx.emit_global(GlobalEvent(2));
6625        });
6626
6627        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
6628
6629        // Model Observation
6630        let observing_model = cx.add_model(|_| Model);
6631        let observed_model = cx.add_model(|_| Model);
6632
6633        let observation_count = Rc::new(RefCell::new(0));
6634
6635        observing_model.update(cx, |_, cx| {
6636            let observation_count = observation_count.clone();
6637            let subscription = Rc::new(RefCell::new(None));
6638            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
6639                let subscription = subscription.clone();
6640                move |_, _, _| {
6641                    subscription.borrow_mut().take();
6642                    *observation_count.borrow_mut() += 1;
6643                }
6644            }));
6645        });
6646
6647        observed_model.update(cx, |_, cx| {
6648            cx.notify();
6649        });
6650
6651        observed_model.update(cx, |_, cx| {
6652            cx.notify();
6653        });
6654
6655        assert_eq!(*observation_count.borrow(), 1);
6656
6657        // View Observation
6658        struct View;
6659
6660        impl Entity for View {
6661            type Event = ();
6662        }
6663
6664        impl super::View for View {
6665            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6666                Empty::new().boxed()
6667            }
6668
6669            fn ui_name() -> &'static str {
6670                "View"
6671            }
6672        }
6673
6674        let (_, root_view) = cx.add_window(Default::default(), |_| View);
6675        let observing_view = cx.add_view(&root_view, |_| View);
6676        let observed_view = cx.add_view(&root_view, |_| View);
6677
6678        let observation_count = Rc::new(RefCell::new(0));
6679        observing_view.update(cx, |_, cx| {
6680            let observation_count = observation_count.clone();
6681            let subscription = Rc::new(RefCell::new(None));
6682            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
6683                let subscription = subscription.clone();
6684                move |_, _, _| {
6685                    subscription.borrow_mut().take();
6686                    *observation_count.borrow_mut() += 1;
6687                }
6688            }));
6689        });
6690
6691        observed_view.update(cx, |_, cx| {
6692            cx.notify();
6693        });
6694
6695        observed_view.update(cx, |_, cx| {
6696            cx.notify();
6697        });
6698
6699        assert_eq!(*observation_count.borrow(), 1);
6700
6701        // Global Observation
6702        let observation_count = Rc::new(RefCell::new(0));
6703        let subscription = Rc::new(RefCell::new(None));
6704        *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
6705            let observation_count = observation_count.clone();
6706            let subscription = subscription.clone();
6707            move |_| {
6708                subscription.borrow_mut().take();
6709                *observation_count.borrow_mut() += 1;
6710            }
6711        }));
6712
6713        cx.default_global::<()>();
6714        cx.set_global(());
6715        assert_eq!(*observation_count.borrow(), 1);
6716    }
6717
6718    #[crate::test(self)]
6719    fn test_focus(cx: &mut MutableAppContext) {
6720        struct View {
6721            name: String,
6722            events: Arc<Mutex<Vec<String>>>,
6723        }
6724
6725        impl Entity for View {
6726            type Event = ();
6727        }
6728
6729        impl super::View for View {
6730            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6731                Empty::new().boxed()
6732            }
6733
6734            fn ui_name() -> &'static str {
6735                "View"
6736            }
6737
6738            fn on_focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
6739                if cx.handle().id() == focused.id() {
6740                    self.events.lock().push(format!("{} focused", &self.name));
6741                }
6742            }
6743
6744            fn on_focus_out(&mut self, blurred: AnyViewHandle, cx: &mut ViewContext<Self>) {
6745                if cx.handle().id() == blurred.id() {
6746                    self.events.lock().push(format!("{} blurred", &self.name));
6747                }
6748            }
6749        }
6750
6751        let view_events: Arc<Mutex<Vec<String>>> = Default::default();
6752        let (_, view_1) = cx.add_window(Default::default(), |_| View {
6753            events: view_events.clone(),
6754            name: "view 1".to_string(),
6755        });
6756        let view_2 = cx.add_view(&view_1, |_| View {
6757            events: view_events.clone(),
6758            name: "view 2".to_string(),
6759        });
6760
6761        let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
6762        view_1.update(cx, |_, cx| {
6763            cx.observe_focus(&view_2, {
6764                let observed_events = observed_events.clone();
6765                move |this, view, focused, cx| {
6766                    let label = if focused { "focus" } else { "blur" };
6767                    observed_events.lock().push(format!(
6768                        "{} observed {}'s {}",
6769                        this.name,
6770                        view.read(cx).name,
6771                        label
6772                    ))
6773                }
6774            })
6775            .detach();
6776        });
6777        view_2.update(cx, |_, cx| {
6778            cx.observe_focus(&view_1, {
6779                let observed_events = observed_events.clone();
6780                move |this, view, focused, cx| {
6781                    let label = if focused { "focus" } else { "blur" };
6782                    observed_events.lock().push(format!(
6783                        "{} observed {}'s {}",
6784                        this.name,
6785                        view.read(cx).name,
6786                        label
6787                    ))
6788                }
6789            })
6790            .detach();
6791        });
6792        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6793        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6794
6795        view_1.update(cx, |_, cx| {
6796            // Ensure only the latest focus is honored.
6797            cx.focus(&view_2);
6798            cx.focus(&view_1);
6799            cx.focus(&view_2);
6800        });
6801        assert_eq!(
6802            mem::take(&mut *view_events.lock()),
6803            ["view 1 blurred", "view 2 focused"],
6804        );
6805        assert_eq!(
6806            mem::take(&mut *observed_events.lock()),
6807            [
6808                "view 2 observed view 1's blur",
6809                "view 1 observed view 2's focus"
6810            ]
6811        );
6812
6813        view_1.update(cx, |_, cx| cx.focus(&view_1));
6814        assert_eq!(
6815            mem::take(&mut *view_events.lock()),
6816            ["view 2 blurred", "view 1 focused"],
6817        );
6818        assert_eq!(
6819            mem::take(&mut *observed_events.lock()),
6820            [
6821                "view 1 observed view 2's blur",
6822                "view 2 observed view 1's focus"
6823            ]
6824        );
6825
6826        view_1.update(cx, |_, cx| cx.focus(&view_2));
6827        assert_eq!(
6828            mem::take(&mut *view_events.lock()),
6829            ["view 1 blurred", "view 2 focused"],
6830        );
6831        assert_eq!(
6832            mem::take(&mut *observed_events.lock()),
6833            [
6834                "view 2 observed view 1's blur",
6835                "view 1 observed view 2's focus"
6836            ]
6837        );
6838
6839        view_1.update(cx, |_, _| drop(view_2));
6840        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6841        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6842    }
6843
6844    #[crate::test(self)]
6845    fn test_deserialize_actions(cx: &mut MutableAppContext) {
6846        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6847        pub struct ComplexAction {
6848            arg: String,
6849            count: usize,
6850        }
6851
6852        actions!(test::something, [SimpleAction]);
6853        impl_actions!(test::something, [ComplexAction]);
6854
6855        cx.add_global_action(move |_: &SimpleAction, _: &mut MutableAppContext| {});
6856        cx.add_global_action(move |_: &ComplexAction, _: &mut MutableAppContext| {});
6857
6858        let action1 = cx
6859            .deserialize_action(
6860                "test::something::ComplexAction",
6861                Some(r#"{"arg": "a", "count": 5}"#),
6862            )
6863            .unwrap();
6864        let action2 = cx
6865            .deserialize_action("test::something::SimpleAction", None)
6866            .unwrap();
6867        assert_eq!(
6868            action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
6869            &ComplexAction {
6870                arg: "a".to_string(),
6871                count: 5,
6872            }
6873        );
6874        assert_eq!(
6875            action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
6876            &SimpleAction
6877        );
6878    }
6879
6880    #[crate::test(self)]
6881    fn test_dispatch_action(cx: &mut MutableAppContext) {
6882        struct ViewA {
6883            id: usize,
6884        }
6885
6886        impl Entity for ViewA {
6887            type Event = ();
6888        }
6889
6890        impl View for ViewA {
6891            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6892                Empty::new().boxed()
6893            }
6894
6895            fn ui_name() -> &'static str {
6896                "View"
6897            }
6898        }
6899
6900        struct ViewB {
6901            id: usize,
6902        }
6903
6904        impl Entity for ViewB {
6905            type Event = ();
6906        }
6907
6908        impl View for ViewB {
6909            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6910                Empty::new().boxed()
6911            }
6912
6913            fn ui_name() -> &'static str {
6914                "View"
6915            }
6916        }
6917
6918        #[derive(Clone, Default, Deserialize, PartialEq)]
6919        pub struct Action(pub String);
6920
6921        impl_actions!(test, [Action]);
6922
6923        let actions = Rc::new(RefCell::new(Vec::new()));
6924
6925        cx.add_global_action({
6926            let actions = actions.clone();
6927            move |_: &Action, _: &mut MutableAppContext| {
6928                actions.borrow_mut().push("global".to_string());
6929            }
6930        });
6931
6932        cx.add_action({
6933            let actions = actions.clone();
6934            move |view: &mut ViewA, action: &Action, cx| {
6935                assert_eq!(action.0, "bar");
6936                cx.propagate_action();
6937                actions.borrow_mut().push(format!("{} a", view.id));
6938            }
6939        });
6940
6941        cx.add_action({
6942            let actions = actions.clone();
6943            move |view: &mut ViewA, _: &Action, cx| {
6944                if view.id != 1 {
6945                    cx.add_view(|cx| {
6946                        cx.propagate_action(); // Still works on a nested ViewContext
6947                        ViewB { id: 5 }
6948                    });
6949                }
6950                actions.borrow_mut().push(format!("{} b", view.id));
6951            }
6952        });
6953
6954        cx.add_action({
6955            let actions = actions.clone();
6956            move |view: &mut ViewB, _: &Action, cx| {
6957                cx.propagate_action();
6958                actions.borrow_mut().push(format!("{} c", view.id));
6959            }
6960        });
6961
6962        cx.add_action({
6963            let actions = actions.clone();
6964            move |view: &mut ViewB, _: &Action, cx| {
6965                cx.propagate_action();
6966                actions.borrow_mut().push(format!("{} d", view.id));
6967            }
6968        });
6969
6970        cx.capture_action({
6971            let actions = actions.clone();
6972            move |view: &mut ViewA, _: &Action, cx| {
6973                cx.propagate_action();
6974                actions.borrow_mut().push(format!("{} capture", view.id));
6975            }
6976        });
6977
6978        let observed_actions = Rc::new(RefCell::new(Vec::new()));
6979        cx.observe_actions({
6980            let observed_actions = observed_actions.clone();
6981            move |action_id, _| observed_actions.borrow_mut().push(action_id)
6982        })
6983        .detach();
6984
6985        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
6986        let view_2 = cx.add_view(&view_1, |_| ViewB { id: 2 });
6987        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
6988        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
6989
6990        cx.handle_dispatch_action_from_effect(
6991            window_id,
6992            Some(view_4.id()),
6993            &Action("bar".to_string()),
6994        );
6995
6996        assert_eq!(
6997            *actions.borrow(),
6998            vec![
6999                "1 capture",
7000                "3 capture",
7001                "4 d",
7002                "4 c",
7003                "3 b",
7004                "3 a",
7005                "2 d",
7006                "2 c",
7007                "1 b"
7008            ]
7009        );
7010        assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
7011
7012        // Remove view_1, which doesn't propagate the action
7013
7014        let (window_id, view_2) = cx.add_window(Default::default(), |_| ViewB { id: 2 });
7015        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
7016        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
7017
7018        actions.borrow_mut().clear();
7019        cx.handle_dispatch_action_from_effect(
7020            window_id,
7021            Some(view_4.id()),
7022            &Action("bar".to_string()),
7023        );
7024
7025        assert_eq!(
7026            *actions.borrow(),
7027            vec![
7028                "3 capture",
7029                "4 d",
7030                "4 c",
7031                "3 b",
7032                "3 a",
7033                "2 d",
7034                "2 c",
7035                "global"
7036            ]
7037        );
7038        assert_eq!(
7039            *observed_actions.borrow(),
7040            [Action::default().id(), Action::default().id()]
7041        );
7042    }
7043
7044    #[crate::test(self)]
7045    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
7046        #[derive(Clone, Deserialize, PartialEq)]
7047        pub struct Action(String);
7048
7049        impl_actions!(test, [Action]);
7050
7051        struct View {
7052            id: usize,
7053            keymap_context: keymap::Context,
7054        }
7055
7056        impl Entity for View {
7057            type Event = ();
7058        }
7059
7060        impl super::View for View {
7061            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7062                Empty::new().boxed()
7063            }
7064
7065            fn ui_name() -> &'static str {
7066                "View"
7067            }
7068
7069            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
7070                self.keymap_context.clone()
7071            }
7072        }
7073
7074        impl View {
7075            fn new(id: usize) -> Self {
7076                View {
7077                    id,
7078                    keymap_context: keymap::Context::default(),
7079                }
7080            }
7081        }
7082
7083        let mut view_1 = View::new(1);
7084        let mut view_2 = View::new(2);
7085        let mut view_3 = View::new(3);
7086        view_1.keymap_context.set.insert("a".into());
7087        view_2.keymap_context.set.insert("a".into());
7088        view_2.keymap_context.set.insert("b".into());
7089        view_3.keymap_context.set.insert("a".into());
7090        view_3.keymap_context.set.insert("b".into());
7091        view_3.keymap_context.set.insert("c".into());
7092
7093        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
7094        let view_2 = cx.add_view(&view_1, |_| view_2);
7095        let _view_3 = cx.add_view(&view_2, |cx| {
7096            cx.focus_self();
7097            view_3
7098        });
7099
7100        // This keymap's only binding dispatches an action on view 2 because that view will have
7101        // "a" and "b" in its context, but not "c".
7102        cx.add_bindings(vec![keymap::Binding::new(
7103            "a",
7104            Action("a".to_string()),
7105            Some("a && b && !c"),
7106        )]);
7107
7108        cx.add_bindings(vec![keymap::Binding::new(
7109            "b",
7110            Action("b".to_string()),
7111            None,
7112        )]);
7113
7114        let actions = Rc::new(RefCell::new(Vec::new()));
7115        cx.add_action({
7116            let actions = actions.clone();
7117            move |view: &mut View, action: &Action, cx| {
7118                if action.0 == "a" {
7119                    actions.borrow_mut().push(format!("{} a", view.id));
7120                } else {
7121                    actions
7122                        .borrow_mut()
7123                        .push(format!("{} {}", view.id, action.0));
7124                    cx.propagate_action();
7125                }
7126            }
7127        });
7128
7129        cx.add_global_action({
7130            let actions = actions.clone();
7131            move |action: &Action, _| {
7132                actions.borrow_mut().push(format!("global {}", action.0));
7133            }
7134        });
7135
7136        cx.dispatch_keystroke(window_id, &Keystroke::parse("a").unwrap());
7137
7138        assert_eq!(&*actions.borrow(), &["2 a"]);
7139
7140        actions.borrow_mut().clear();
7141
7142        cx.dispatch_keystroke(window_id, &Keystroke::parse("b").unwrap());
7143
7144        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
7145    }
7146
7147    #[crate::test(self)]
7148    async fn test_model_condition(cx: &mut TestAppContext) {
7149        struct Counter(usize);
7150
7151        impl super::Entity for Counter {
7152            type Event = ();
7153        }
7154
7155        impl Counter {
7156            fn inc(&mut self, cx: &mut ModelContext<Self>) {
7157                self.0 += 1;
7158                cx.notify();
7159            }
7160        }
7161
7162        let model = cx.add_model(|_| Counter(0));
7163
7164        let condition1 = model.condition(cx, |model, _| model.0 == 2);
7165        let condition2 = model.condition(cx, |model, _| model.0 == 3);
7166        smol::pin!(condition1, condition2);
7167
7168        model.update(cx, |model, cx| model.inc(cx));
7169        assert_eq!(poll_once(&mut condition1).await, None);
7170        assert_eq!(poll_once(&mut condition2).await, None);
7171
7172        model.update(cx, |model, cx| model.inc(cx));
7173        assert_eq!(poll_once(&mut condition1).await, Some(()));
7174        assert_eq!(poll_once(&mut condition2).await, None);
7175
7176        model.update(cx, |model, cx| model.inc(cx));
7177        assert_eq!(poll_once(&mut condition2).await, Some(()));
7178
7179        model.update(cx, |_, cx| cx.notify());
7180    }
7181
7182    #[crate::test(self)]
7183    #[should_panic]
7184    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
7185        struct Model;
7186
7187        impl super::Entity for Model {
7188            type Event = ();
7189        }
7190
7191        let model = cx.add_model(|_| Model);
7192        model.condition(cx, |_, _| false).await;
7193    }
7194
7195    #[crate::test(self)]
7196    #[should_panic(expected = "model dropped with pending condition")]
7197    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
7198        struct Model;
7199
7200        impl super::Entity for Model {
7201            type Event = ();
7202        }
7203
7204        let model = cx.add_model(|_| Model);
7205        let condition = model.condition(cx, |_, _| false);
7206        cx.update(|_| drop(model));
7207        condition.await;
7208    }
7209
7210    #[crate::test(self)]
7211    async fn test_view_condition(cx: &mut TestAppContext) {
7212        struct Counter(usize);
7213
7214        impl super::Entity for Counter {
7215            type Event = ();
7216        }
7217
7218        impl super::View for Counter {
7219            fn ui_name() -> &'static str {
7220                "test view"
7221            }
7222
7223            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7224                Empty::new().boxed()
7225            }
7226        }
7227
7228        impl Counter {
7229            fn inc(&mut self, cx: &mut ViewContext<Self>) {
7230                self.0 += 1;
7231                cx.notify();
7232            }
7233        }
7234
7235        let (_, view) = cx.add_window(|_| Counter(0));
7236
7237        let condition1 = view.condition(cx, |view, _| view.0 == 2);
7238        let condition2 = view.condition(cx, |view, _| view.0 == 3);
7239        smol::pin!(condition1, condition2);
7240
7241        view.update(cx, |view, cx| view.inc(cx));
7242        assert_eq!(poll_once(&mut condition1).await, None);
7243        assert_eq!(poll_once(&mut condition2).await, None);
7244
7245        view.update(cx, |view, cx| view.inc(cx));
7246        assert_eq!(poll_once(&mut condition1).await, Some(()));
7247        assert_eq!(poll_once(&mut condition2).await, None);
7248
7249        view.update(cx, |view, cx| view.inc(cx));
7250        assert_eq!(poll_once(&mut condition2).await, Some(()));
7251        view.update(cx, |_, cx| cx.notify());
7252    }
7253
7254    #[crate::test(self)]
7255    #[should_panic]
7256    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
7257        struct View;
7258
7259        impl super::Entity for View {
7260            type Event = ();
7261        }
7262
7263        impl super::View for View {
7264            fn ui_name() -> &'static str {
7265                "test view"
7266            }
7267
7268            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7269                Empty::new().boxed()
7270            }
7271        }
7272
7273        let (_, view) = cx.add_window(|_| View);
7274        view.condition(cx, |_, _| false).await;
7275    }
7276
7277    #[crate::test(self)]
7278    #[should_panic(expected = "view dropped with pending condition")]
7279    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
7280        struct View;
7281
7282        impl super::Entity for View {
7283            type Event = ();
7284        }
7285
7286        impl super::View for View {
7287            fn ui_name() -> &'static str {
7288                "test view"
7289            }
7290
7291            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7292                Empty::new().boxed()
7293            }
7294        }
7295
7296        let (_, root_view) = cx.add_window(|_| View);
7297        let view = cx.add_view(&root_view, |_| View);
7298
7299        let condition = view.condition(cx, |_, _| false);
7300        cx.update(|_| drop(view));
7301        condition.await;
7302    }
7303
7304    #[crate::test(self)]
7305    fn test_refresh_windows(cx: &mut MutableAppContext) {
7306        struct View(usize);
7307
7308        impl super::Entity for View {
7309            type Event = ();
7310        }
7311
7312        impl super::View for View {
7313            fn ui_name() -> &'static str {
7314                "test view"
7315            }
7316
7317            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7318                Empty::new().named(format!("render count: {}", post_inc(&mut self.0)))
7319            }
7320        }
7321
7322        let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
7323        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
7324
7325        assert_eq!(
7326            presenter.borrow().rendered_views[&root_view.id()].name(),
7327            Some("render count: 0")
7328        );
7329
7330        let view = cx.add_view(&root_view, |cx| {
7331            cx.refresh_windows();
7332            View(0)
7333        });
7334
7335        assert_eq!(
7336            presenter.borrow().rendered_views[&root_view.id()].name(),
7337            Some("render count: 1")
7338        );
7339        assert_eq!(
7340            presenter.borrow().rendered_views[&view.id()].name(),
7341            Some("render count: 0")
7342        );
7343
7344        cx.update(|cx| cx.refresh_windows());
7345        assert_eq!(
7346            presenter.borrow().rendered_views[&root_view.id()].name(),
7347            Some("render count: 2")
7348        );
7349        assert_eq!(
7350            presenter.borrow().rendered_views[&view.id()].name(),
7351            Some("render count: 1")
7352        );
7353
7354        cx.update(|cx| {
7355            cx.refresh_windows();
7356            drop(view);
7357        });
7358        assert_eq!(
7359            presenter.borrow().rendered_views[&root_view.id()].name(),
7360            Some("render count: 3")
7361        );
7362        assert_eq!(presenter.borrow().rendered_views.len(), 1);
7363    }
7364
7365    #[crate::test(self)]
7366    async fn test_window_activation(cx: &mut TestAppContext) {
7367        struct View(&'static str);
7368
7369        impl super::Entity for View {
7370            type Event = ();
7371        }
7372
7373        impl super::View for View {
7374            fn ui_name() -> &'static str {
7375                "test view"
7376            }
7377
7378            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7379                Empty::new().boxed()
7380            }
7381        }
7382
7383        let events = Rc::new(RefCell::new(Vec::new()));
7384        let (window_1, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7385            cx.observe_window_activation({
7386                let events = events.clone();
7387                move |this, active, _| events.borrow_mut().push((this.0, active))
7388            })
7389            .detach();
7390            View("window 1")
7391        });
7392        assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
7393
7394        let (window_2, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7395            cx.observe_window_activation({
7396                let events = events.clone();
7397                move |this, active, _| events.borrow_mut().push((this.0, active))
7398            })
7399            .detach();
7400            View("window 2")
7401        });
7402        assert_eq!(
7403            mem::take(&mut *events.borrow_mut()),
7404            [("window 1", false), ("window 2", true)]
7405        );
7406
7407        let (window_3, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7408            cx.observe_window_activation({
7409                let events = events.clone();
7410                move |this, active, _| events.borrow_mut().push((this.0, active))
7411            })
7412            .detach();
7413            View("window 3")
7414        });
7415        assert_eq!(
7416            mem::take(&mut *events.borrow_mut()),
7417            [("window 2", false), ("window 3", true)]
7418        );
7419
7420        cx.simulate_window_activation(Some(window_2));
7421        assert_eq!(
7422            mem::take(&mut *events.borrow_mut()),
7423            [("window 3", false), ("window 2", true)]
7424        );
7425
7426        cx.simulate_window_activation(Some(window_1));
7427        assert_eq!(
7428            mem::take(&mut *events.borrow_mut()),
7429            [("window 2", false), ("window 1", true)]
7430        );
7431
7432        cx.simulate_window_activation(Some(window_3));
7433        assert_eq!(
7434            mem::take(&mut *events.borrow_mut()),
7435            [("window 1", false), ("window 3", true)]
7436        );
7437
7438        cx.simulate_window_activation(Some(window_3));
7439        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
7440    }
7441}