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