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