app.rs

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