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