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