window.rs

   1use crate::{
   2    key_dispatch::DispatchActionListener, px, size, Action, AnyDrag, AnyView, AppContext,
   3    AsyncWindowContext, AvailableSpace, Bounds, BoxShadow, Context, Corners, CursorStyle,
   4    DevicePixels, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity, EntityId,
   5    EventEmitter, FileDropEvent, Flatten, FocusEvent, FontId, GlobalElementId, GlyphId, Hsla,
   6    ImageData, InputEvent, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeystrokeEvent, LayoutId,
   7    Model, ModelContext, Modifiers, MonochromeSprite, MouseButton, MouseMoveEvent, MouseUpEvent,
   8    Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInputHandler, PlatformWindow, Point,
   9    PolychromeSprite, PromptLevel, Quad, Render, RenderGlyphParams, RenderImageParams,
  10    RenderSvgParams, ScaledPixels, Scene, SceneBuilder, Shadow, SharedString, Size, Style,
  11    SubscriberSet, Subscription, Surface, TaffyLayoutEngine, Task, Underline, UnderlineStyle, View,
  12    VisualContext, WeakView, WindowBounds, WindowOptions, SUBPIXEL_VARIANTS,
  13};
  14use anyhow::{anyhow, Context as _, Result};
  15use collections::HashMap;
  16use derive_more::{Deref, DerefMut};
  17use futures::{
  18    channel::{mpsc, oneshot},
  19    StreamExt,
  20};
  21use media::core_video::CVImageBuffer;
  22use parking_lot::RwLock;
  23use slotmap::SlotMap;
  24use smallvec::SmallVec;
  25use std::{
  26    any::{Any, TypeId},
  27    borrow::{Borrow, BorrowMut, Cow},
  28    fmt::Debug,
  29    future::Future,
  30    hash::{Hash, Hasher},
  31    marker::PhantomData,
  32    mem,
  33    rc::Rc,
  34    sync::{
  35        atomic::{AtomicUsize, Ordering::SeqCst},
  36        Arc,
  37    },
  38};
  39use util::ResultExt;
  40
  41const ACTIVE_DRAG_Z_INDEX: u32 = 1;
  42
  43/// A global stacking order, which is created by stacking successive z-index values.
  44/// Each z-index will always be interpreted in the context of its parent z-index.
  45#[derive(Deref, DerefMut, Ord, PartialOrd, Eq, PartialEq, Clone, Default, Debug)]
  46pub struct StackingOrder(pub(crate) SmallVec<[u32; 16]>);
  47
  48/// Represents the two different phases when dispatching events.
  49#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
  50pub enum DispatchPhase {
  51    /// After the capture phase comes the bubble phase, in which mouse event listeners are
  52    /// invoked front to back and keyboard event listeners are invoked from the focused element
  53    /// to the root of the element tree. This is the phase you'll most commonly want to use when
  54    /// registering event listeners.
  55    #[default]
  56    Bubble,
  57    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
  58    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
  59    /// is used for special purposes such as clearing the "pressed" state for click events. If
  60    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
  61    /// outside of the immediate region may rely on detecting non-local events during this phase.
  62    Capture,
  63}
  64
  65impl DispatchPhase {
  66    pub fn bubble(self) -> bool {
  67        self == DispatchPhase::Bubble
  68    }
  69
  70    pub fn capture(self) -> bool {
  71        self == DispatchPhase::Capture
  72    }
  73}
  74
  75type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
  76type AnyMouseListener = Box<dyn FnMut(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
  77type AnyFocusListener = Box<dyn Fn(&FocusEvent, &mut WindowContext) + 'static>;
  78type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>;
  79
  80slotmap::new_key_type! { pub struct FocusId; }
  81
  82impl FocusId {
  83    /// Obtains whether the element associated with this handle is currently focused.
  84    pub fn is_focused(&self, cx: &WindowContext) -> bool {
  85        cx.window.focus == Some(*self)
  86    }
  87
  88    /// Obtains whether the element associated with this handle contains the focused
  89    /// element or is itself focused.
  90    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
  91        cx.focused()
  92            .map_or(false, |focused| self.contains(focused.id, cx))
  93    }
  94
  95    /// Obtains whether the element associated with this handle is contained within the
  96    /// focused element or is itself focused.
  97    pub fn within_focused(&self, cx: &WindowContext) -> bool {
  98        let focused = cx.focused();
  99        focused.map_or(false, |focused| focused.id.contains(*self, cx))
 100    }
 101
 102    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 103    pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
 104        cx.window
 105            .rendered_frame
 106            .dispatch_tree
 107            .focus_contains(*self, other)
 108    }
 109}
 110
 111/// A handle which can be used to track and manipulate the focused element in a window.
 112pub struct FocusHandle {
 113    pub(crate) id: FocusId,
 114    handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 115}
 116
 117impl std::fmt::Debug for FocusHandle {
 118    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 119        f.write_fmt(format_args!("FocusHandle({:?})", self.id))
 120    }
 121}
 122
 123impl FocusHandle {
 124    pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
 125        let id = handles.write().insert(AtomicUsize::new(1));
 126        Self {
 127            id,
 128            handles: handles.clone(),
 129        }
 130    }
 131
 132    pub(crate) fn for_id(
 133        id: FocusId,
 134        handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 135    ) -> Option<Self> {
 136        let lock = handles.read();
 137        let ref_count = lock.get(id)?;
 138        if ref_count.load(SeqCst) == 0 {
 139            None
 140        } else {
 141            ref_count.fetch_add(1, SeqCst);
 142            Some(Self {
 143                id,
 144                handles: handles.clone(),
 145            })
 146        }
 147    }
 148
 149    /// Moves the focus to the element associated with this handle.
 150    pub fn focus(&self, cx: &mut WindowContext) {
 151        cx.focus(self)
 152    }
 153
 154    /// Obtains whether the element associated with this handle is currently focused.
 155    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 156        self.id.is_focused(cx)
 157    }
 158
 159    /// Obtains whether the element associated with this handle contains the focused
 160    /// element or is itself focused.
 161    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
 162        self.id.contains_focused(cx)
 163    }
 164
 165    /// Obtains whether the element associated with this handle is contained within the
 166    /// focused element or is itself focused.
 167    pub fn within_focused(&self, cx: &WindowContext) -> bool {
 168        self.id.within_focused(cx)
 169    }
 170
 171    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 172    pub fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
 173        self.id.contains(other.id, cx)
 174    }
 175}
 176
 177impl Clone for FocusHandle {
 178    fn clone(&self) -> Self {
 179        Self::for_id(self.id, &self.handles).unwrap()
 180    }
 181}
 182
 183impl PartialEq for FocusHandle {
 184    fn eq(&self, other: &Self) -> bool {
 185        self.id == other.id
 186    }
 187}
 188
 189impl Eq for FocusHandle {}
 190
 191impl Drop for FocusHandle {
 192    fn drop(&mut self) {
 193        self.handles
 194            .read()
 195            .get(self.id)
 196            .unwrap()
 197            .fetch_sub(1, SeqCst);
 198    }
 199}
 200
 201/// FocusableView allows users of your view to easily
 202/// focus it (using cx.focus_view(view))
 203pub trait FocusableView: 'static + Render {
 204    fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
 205}
 206
 207/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
 208/// where the lifecycle of the view is handled by another view.
 209pub trait ManagedView: FocusableView + EventEmitter<DismissEvent> {}
 210
 211impl<M: FocusableView + EventEmitter<DismissEvent>> ManagedView for M {}
 212
 213pub struct DismissEvent;
 214
 215// Holds the state for a specific window.
 216pub struct Window {
 217    pub(crate) handle: AnyWindowHandle,
 218    pub(crate) removed: bool,
 219    pub(crate) platform_window: Box<dyn PlatformWindow>,
 220    display_id: DisplayId,
 221    sprite_atlas: Arc<dyn PlatformAtlas>,
 222    rem_size: Pixels,
 223    viewport_size: Size<Pixels>,
 224    layout_engine: Option<TaffyLayoutEngine>,
 225    pub(crate) root_view: Option<AnyView>,
 226    pub(crate) element_id_stack: GlobalElementId,
 227    pub(crate) rendered_frame: Frame,
 228    pub(crate) next_frame: Frame,
 229    pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 230    pub(crate) focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
 231    pub(crate) blur_listeners: SubscriberSet<(), AnyObserver>,
 232    default_prevented: bool,
 233    mouse_position: Point<Pixels>,
 234    requested_cursor_style: Option<CursorStyle>,
 235    scale_factor: f32,
 236    bounds: WindowBounds,
 237    bounds_observers: SubscriberSet<(), AnyObserver>,
 238    active: bool,
 239    pub(crate) dirty: bool,
 240    activation_observers: SubscriberSet<(), AnyObserver>,
 241    pub(crate) last_blur: Option<Option<FocusId>>,
 242    pub(crate) focus: Option<FocusId>,
 243}
 244
 245pub(crate) struct ElementStateBox {
 246    inner: Box<dyn Any>,
 247    #[cfg(debug_assertions)]
 248    type_name: &'static str,
 249}
 250
 251// #[derive(Default)]
 252pub(crate) struct Frame {
 253    pub(crate) element_states: HashMap<GlobalElementId, ElementStateBox>,
 254    mouse_listeners: HashMap<TypeId, Vec<(StackingOrder, AnyMouseListener)>>,
 255    pub(crate) dispatch_tree: DispatchTree,
 256    pub(crate) focus_listeners: Vec<AnyFocusListener>,
 257    pub(crate) scene_builder: SceneBuilder,
 258    pub(crate) depth_map: Vec<(StackingOrder, Bounds<Pixels>)>,
 259    pub(crate) z_index_stack: StackingOrder,
 260    content_mask_stack: Vec<ContentMask<Pixels>>,
 261    element_offset_stack: Vec<Point<Pixels>>,
 262}
 263
 264impl Frame {
 265    fn new(dispatch_tree: DispatchTree) -> Self {
 266        Frame {
 267            element_states: HashMap::default(),
 268            mouse_listeners: HashMap::default(),
 269            dispatch_tree,
 270            focus_listeners: Vec::new(),
 271            scene_builder: SceneBuilder::default(),
 272            z_index_stack: StackingOrder::default(),
 273            depth_map: Default::default(),
 274            content_mask_stack: Vec::new(),
 275            element_offset_stack: Vec::new(),
 276        }
 277    }
 278
 279    fn clear(&mut self) {
 280        self.element_states.clear();
 281        self.mouse_listeners.values_mut().for_each(Vec::clear);
 282        self.focus_listeners.clear();
 283        self.dispatch_tree.clear();
 284        self.depth_map.clear();
 285    }
 286}
 287
 288impl Window {
 289    pub(crate) fn new(
 290        handle: AnyWindowHandle,
 291        options: WindowOptions,
 292        cx: &mut AppContext,
 293    ) -> Self {
 294        let platform_window = cx.platform.open_window(
 295            handle,
 296            options,
 297            Box::new({
 298                let mut cx = cx.to_async();
 299                move || handle.update(&mut cx, |_, cx| cx.draw())
 300            }),
 301        );
 302        let display_id = platform_window.display().id();
 303        let sprite_atlas = platform_window.sprite_atlas();
 304        let mouse_position = platform_window.mouse_position();
 305        let content_size = platform_window.content_size();
 306        let scale_factor = platform_window.scale_factor();
 307        let bounds = platform_window.bounds();
 308
 309        platform_window.on_resize(Box::new({
 310            let mut cx = cx.to_async();
 311            move |_, _| {
 312                handle
 313                    .update(&mut cx, |_, cx| cx.window_bounds_changed())
 314                    .log_err();
 315            }
 316        }));
 317        platform_window.on_moved(Box::new({
 318            let mut cx = cx.to_async();
 319            move || {
 320                handle
 321                    .update(&mut cx, |_, cx| cx.window_bounds_changed())
 322                    .log_err();
 323            }
 324        }));
 325        platform_window.on_active_status_change(Box::new({
 326            let mut cx = cx.to_async();
 327            move |active| {
 328                handle
 329                    .update(&mut cx, |_, cx| {
 330                        cx.window.active = active;
 331                        cx.window
 332                            .activation_observers
 333                            .clone()
 334                            .retain(&(), |callback| callback(cx));
 335                    })
 336                    .log_err();
 337            }
 338        }));
 339
 340        platform_window.on_input({
 341            let mut cx = cx.to_async();
 342            Box::new(move |event| {
 343                handle
 344                    .update(&mut cx, |_, cx| cx.dispatch_event(event))
 345                    .log_err()
 346                    .unwrap_or(false)
 347            })
 348        });
 349
 350        Window {
 351            handle,
 352            removed: false,
 353            platform_window,
 354            display_id,
 355            sprite_atlas,
 356            rem_size: px(16.),
 357            viewport_size: content_size,
 358            layout_engine: Some(TaffyLayoutEngine::new()),
 359            root_view: None,
 360            element_id_stack: GlobalElementId::default(),
 361            rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 362            next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 363            focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
 364            focus_listeners: SubscriberSet::new(),
 365            blur_listeners: SubscriberSet::new(),
 366            default_prevented: true,
 367            mouse_position,
 368            requested_cursor_style: None,
 369            scale_factor,
 370            bounds,
 371            bounds_observers: SubscriberSet::new(),
 372            active: false,
 373            dirty: false,
 374            activation_observers: SubscriberSet::new(),
 375            last_blur: None,
 376            focus: None,
 377        }
 378    }
 379}
 380
 381/// Indicates which region of the window is visible. Content falling outside of this mask will not be
 382/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
 383/// to leave room to support more complex shapes in the future.
 384#[derive(Clone, Debug, Default, PartialEq, Eq)]
 385#[repr(C)]
 386pub struct ContentMask<P: Clone + Default + Debug> {
 387    pub bounds: Bounds<P>,
 388}
 389
 390impl ContentMask<Pixels> {
 391    /// Scale the content mask's pixel units by the given scaling factor.
 392    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
 393        ContentMask {
 394            bounds: self.bounds.scale(factor),
 395        }
 396    }
 397
 398    /// Intersect the content mask with the given content mask.
 399    pub fn intersect(&self, other: &Self) -> Self {
 400        let bounds = self.bounds.intersect(&other.bounds);
 401        ContentMask { bounds }
 402    }
 403}
 404
 405/// Provides access to application state in the context of a single window. Derefs
 406/// to an `AppContext`, so you can also pass a `WindowContext` to any method that takes
 407/// an `AppContext` and call any `AppContext` methods.
 408pub struct WindowContext<'a> {
 409    pub(crate) app: &'a mut AppContext,
 410    pub(crate) window: &'a mut Window,
 411}
 412
 413impl<'a> WindowContext<'a> {
 414    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
 415        Self { app, window }
 416    }
 417
 418    /// Obtain a handle to the window that belongs to this context.
 419    pub fn window_handle(&self) -> AnyWindowHandle {
 420        self.window.handle
 421    }
 422
 423    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
 424    pub fn notify(&mut self) {
 425        self.window.dirty = true;
 426    }
 427
 428    /// Close this window.
 429    pub fn remove_window(&mut self) {
 430        self.window.removed = true;
 431    }
 432
 433    /// Obtain a new `FocusHandle`, which allows you to track and manipulate the keyboard focus
 434    /// for elements rendered within this window.
 435    pub fn focus_handle(&mut self) -> FocusHandle {
 436        FocusHandle::new(&self.window.focus_handles)
 437    }
 438
 439    /// Obtain the currently focused `FocusHandle`. If no elements are focused, returns `None`.
 440    pub fn focused(&self) -> Option<FocusHandle> {
 441        self.window
 442            .focus
 443            .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
 444    }
 445
 446    /// Move focus to the element associated with the given `FocusHandle`.
 447    pub fn focus(&mut self, handle: &FocusHandle) {
 448        if self.window.focus == Some(handle.id) {
 449            return;
 450        }
 451
 452        let focus_id = handle.id;
 453
 454        if self.window.last_blur.is_none() {
 455            self.window.last_blur = Some(self.window.focus);
 456        }
 457
 458        self.window.focus = Some(focus_id);
 459        self.window
 460            .rendered_frame
 461            .dispatch_tree
 462            .clear_pending_keystrokes();
 463        self.app.push_effect(Effect::FocusChanged {
 464            window_handle: self.window.handle,
 465            focused: Some(focus_id),
 466        });
 467        self.notify();
 468    }
 469
 470    /// Remove focus from all elements within this context's window.
 471    pub fn blur(&mut self) {
 472        if self.window.last_blur.is_none() {
 473            self.window.last_blur = Some(self.window.focus);
 474        }
 475
 476        self.window.focus = None;
 477        self.app.push_effect(Effect::FocusChanged {
 478            window_handle: self.window.handle,
 479            focused: None,
 480        });
 481        self.notify();
 482    }
 483
 484    pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
 485        let focus_handle = self.focused();
 486
 487        self.defer(move |cx| {
 488            let node_id = focus_handle
 489                .and_then(|handle| {
 490                    cx.window
 491                        .rendered_frame
 492                        .dispatch_tree
 493                        .focusable_node_id(handle.id)
 494                })
 495                .unwrap_or_else(|| cx.window.rendered_frame.dispatch_tree.root_node_id());
 496
 497            cx.propagate_event = true;
 498            cx.dispatch_action_on_node(node_id, action);
 499        })
 500    }
 501
 502    pub(crate) fn dispatch_keystroke_observers(
 503        &mut self,
 504        event: &dyn Any,
 505        action: Option<Box<dyn Action>>,
 506    ) {
 507        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
 508            return;
 509        };
 510
 511        self.keystroke_observers
 512            .clone()
 513            .retain(&(), move |callback| {
 514                (callback)(
 515                    &KeystrokeEvent {
 516                        keystroke: key_down_event.keystroke.clone(),
 517                        action: action.as_ref().map(|action| action.boxed_clone()),
 518                    },
 519                    self,
 520                );
 521                true
 522            });
 523    }
 524
 525    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
 526    /// that are currently on the stack to be returned to the app.
 527    pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
 528        let handle = self.window.handle;
 529        self.app.defer(move |cx| {
 530            handle.update(cx, |_, cx| f(cx)).ok();
 531        });
 532    }
 533
 534    pub fn subscribe<Emitter, E, Evt>(
 535        &mut self,
 536        entity: &E,
 537        mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
 538    ) -> Subscription
 539    where
 540        Emitter: EventEmitter<Evt>,
 541        E: Entity<Emitter>,
 542        Evt: 'static,
 543    {
 544        let entity_id = entity.entity_id();
 545        let entity = entity.downgrade();
 546        let window_handle = self.window.handle;
 547        let (subscription, activate) = self.app.event_listeners.insert(
 548            entity_id,
 549            (
 550                TypeId::of::<Evt>(),
 551                Box::new(move |event, cx| {
 552                    window_handle
 553                        .update(cx, |_, cx| {
 554                            if let Some(handle) = E::upgrade_from(&entity) {
 555                                let event = event.downcast_ref().expect("invalid event type");
 556                                on_event(handle, event, cx);
 557                                true
 558                            } else {
 559                                false
 560                            }
 561                        })
 562                        .unwrap_or(false)
 563                }),
 564            ),
 565        );
 566        self.app.defer(move |_| activate());
 567        subscription
 568    }
 569
 570    /// Create an `AsyncWindowContext`, which has a static lifetime and can be held across
 571    /// await points in async code.
 572    pub fn to_async(&self) -> AsyncWindowContext {
 573        AsyncWindowContext::new(self.app.to_async(), self.window.handle)
 574    }
 575
 576    /// Schedule the given closure to be run directly after the current frame is rendered.
 577    pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
 578        let handle = self.window.handle;
 579        let display_id = self.window.display_id;
 580
 581        if !self.frame_consumers.contains_key(&display_id) {
 582            let (tx, mut rx) = mpsc::unbounded::<()>();
 583            self.platform.set_display_link_output_callback(
 584                display_id,
 585                Box::new(move |_current_time, _output_time| _ = tx.unbounded_send(())),
 586            );
 587
 588            let consumer_task = self.app.spawn(|cx| async move {
 589                while rx.next().await.is_some() {
 590                    cx.update(|cx| {
 591                        for callback in cx
 592                            .next_frame_callbacks
 593                            .get_mut(&display_id)
 594                            .unwrap()
 595                            .drain(..)
 596                            .collect::<SmallVec<[_; 32]>>()
 597                        {
 598                            callback(cx);
 599                        }
 600                    })
 601                    .ok();
 602
 603                    // Flush effects, then stop the display link if no new next_frame_callbacks have been added.
 604
 605                    cx.update(|cx| {
 606                        if cx.next_frame_callbacks.is_empty() {
 607                            cx.platform.stop_display_link(display_id);
 608                        }
 609                    })
 610                    .ok();
 611                }
 612            });
 613            self.frame_consumers.insert(display_id, consumer_task);
 614        }
 615
 616        if self.next_frame_callbacks.is_empty() {
 617            self.platform.start_display_link(display_id);
 618        }
 619
 620        self.next_frame_callbacks
 621            .entry(display_id)
 622            .or_default()
 623            .push(Box::new(move |cx: &mut AppContext| {
 624                cx.update_window(handle, |_root_view, cx| callback(cx)).ok();
 625            }));
 626    }
 627
 628    /// Spawn the future returned by the given closure on the application thread pool.
 629    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
 630    /// use within your future.
 631    pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
 632    where
 633        R: 'static,
 634        Fut: Future<Output = R> + 'static,
 635    {
 636        self.app
 637            .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
 638    }
 639
 640    /// Update the global of the given type. The given closure is given simultaneous mutable
 641    /// access both to the global and the context.
 642    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
 643    where
 644        G: 'static,
 645    {
 646        let mut global = self.app.lease_global::<G>();
 647        let result = f(&mut global, self);
 648        self.app.end_global_lease(global);
 649        result
 650    }
 651
 652    #[must_use]
 653    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
 654    /// layout is being requested, along with the layout ids of any children. This method is called during
 655    /// calls to the `Element::layout` trait method and enables any element to participate in layout.
 656    pub fn request_layout(
 657        &mut self,
 658        style: &Style,
 659        children: impl IntoIterator<Item = LayoutId>,
 660    ) -> LayoutId {
 661        self.app.layout_id_buffer.clear();
 662        self.app.layout_id_buffer.extend(children.into_iter());
 663        let rem_size = self.rem_size();
 664
 665        self.window.layout_engine.as_mut().unwrap().request_layout(
 666            style,
 667            rem_size,
 668            &self.app.layout_id_buffer,
 669        )
 670    }
 671
 672    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
 673    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
 674    /// determine the element's size. One place this is used internally is when measuring text.
 675    ///
 676    /// The given closure is invoked at layout time with the known dimensions and available space and
 677    /// returns a `Size`.
 678    pub fn request_measured_layout<
 679        F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
 680            + 'static,
 681    >(
 682        &mut self,
 683        style: Style,
 684        measure: F,
 685    ) -> LayoutId {
 686        let rem_size = self.rem_size();
 687        self.window
 688            .layout_engine
 689            .as_mut()
 690            .unwrap()
 691            .request_measured_layout(style, rem_size, measure)
 692    }
 693
 694    pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
 695        let mut layout_engine = self.window.layout_engine.take().unwrap();
 696        layout_engine.compute_layout(layout_id, available_space, self);
 697        self.window.layout_engine = Some(layout_engine);
 698    }
 699
 700    /// Obtain the bounds computed for the given LayoutId relative to the window. This method should not
 701    /// be invoked until the paint phase begins, and will usually be invoked by GPUI itself automatically
 702    /// in order to pass your element its `Bounds` automatically.
 703    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
 704        let mut bounds = self
 705            .window
 706            .layout_engine
 707            .as_mut()
 708            .unwrap()
 709            .layout_bounds(layout_id)
 710            .map(Into::into);
 711        bounds.origin += self.element_offset();
 712        bounds
 713    }
 714
 715    fn window_bounds_changed(&mut self) {
 716        self.window.scale_factor = self.window.platform_window.scale_factor();
 717        self.window.viewport_size = self.window.platform_window.content_size();
 718        self.window.bounds = self.window.platform_window.bounds();
 719        self.window.display_id = self.window.platform_window.display().id();
 720        self.notify();
 721
 722        self.window
 723            .bounds_observers
 724            .clone()
 725            .retain(&(), |callback| callback(self));
 726    }
 727
 728    pub fn window_bounds(&self) -> WindowBounds {
 729        self.window.bounds
 730    }
 731
 732    pub fn viewport_size(&self) -> Size<Pixels> {
 733        self.window.viewport_size
 734    }
 735
 736    pub fn is_window_active(&self) -> bool {
 737        self.window.active
 738    }
 739
 740    pub fn zoom_window(&self) {
 741        self.window.platform_window.zoom();
 742    }
 743
 744    pub fn set_window_title(&mut self, title: &str) {
 745        self.window.platform_window.set_title(title);
 746    }
 747
 748    pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 749        self.platform
 750            .displays()
 751            .into_iter()
 752            .find(|display| display.id() == self.window.display_id)
 753    }
 754
 755    pub fn show_character_palette(&self) {
 756        self.window.platform_window.show_character_palette();
 757    }
 758
 759    /// The scale factor of the display associated with the window. For example, it could
 760    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
 761    /// be rendered as two pixels on screen.
 762    pub fn scale_factor(&self) -> f32 {
 763        self.window.scale_factor
 764    }
 765
 766    /// The size of an em for the base font of the application. Adjusting this value allows the
 767    /// UI to scale, just like zooming a web page.
 768    pub fn rem_size(&self) -> Pixels {
 769        self.window.rem_size
 770    }
 771
 772    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
 773    /// UI to scale, just like zooming a web page.
 774    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
 775        self.window.rem_size = rem_size.into();
 776    }
 777
 778    /// The line height associated with the current text style.
 779    pub fn line_height(&self) -> Pixels {
 780        let rem_size = self.rem_size();
 781        let text_style = self.text_style();
 782        text_style
 783            .line_height
 784            .to_pixels(text_style.font_size.into(), rem_size)
 785    }
 786
 787    /// Call to prevent the default action of an event. Currently only used to prevent
 788    /// parent elements from becoming focused on mouse down.
 789    pub fn prevent_default(&mut self) {
 790        self.window.default_prevented = true;
 791    }
 792
 793    /// Obtain whether default has been prevented for the event currently being dispatched.
 794    pub fn default_prevented(&self) -> bool {
 795        self.window.default_prevented
 796    }
 797
 798    /// Register a mouse event listener on the window for the next frame. The type of event
 799    /// is determined by the first parameter of the given listener. When the next frame is rendered
 800    /// the listener will be cleared.
 801    ///
 802    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
 803    /// a specific need to register a global listener.
 804    pub fn on_mouse_event<Event: 'static>(
 805        &mut self,
 806        handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
 807    ) {
 808        let order = self.window.next_frame.z_index_stack.clone();
 809        self.window
 810            .next_frame
 811            .mouse_listeners
 812            .entry(TypeId::of::<Event>())
 813            .or_default()
 814            .push((
 815                order,
 816                Box::new(move |event: &dyn Any, phase, cx| {
 817                    handler(event.downcast_ref().unwrap(), phase, cx)
 818                }),
 819            ))
 820    }
 821
 822    /// Register a key event listener on the window for the next frame. The type of event
 823    /// is determined by the first parameter of the given listener. When the next frame is rendered
 824    /// the listener will be cleared.
 825    ///
 826    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
 827    /// a specific need to register a global listener.
 828    pub fn on_key_event<Event: 'static>(
 829        &mut self,
 830        handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
 831    ) {
 832        self.window
 833            .next_frame
 834            .dispatch_tree
 835            .on_key_event(Rc::new(move |event, phase, cx| {
 836                if let Some(event) = event.downcast_ref::<Event>() {
 837                    handler(event, phase, cx)
 838                }
 839            }));
 840    }
 841
 842    /// Register an action listener on the window for the next frame. The type of action
 843    /// is determined by the first parameter of the given listener. When the next frame is rendered
 844    /// the listener will be cleared.
 845    ///
 846    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
 847    /// a specific need to register a global listener.
 848    pub fn on_action(
 849        &mut self,
 850        action_type: TypeId,
 851        handler: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
 852    ) {
 853        self.window.next_frame.dispatch_tree.on_action(
 854            action_type,
 855            Rc::new(move |action, phase, cx| handler(action, phase, cx)),
 856        );
 857    }
 858
 859    pub fn is_action_available(&self, action: &dyn Action) -> bool {
 860        let target = self
 861            .focused()
 862            .and_then(|focused_handle| {
 863                self.window
 864                    .rendered_frame
 865                    .dispatch_tree
 866                    .focusable_node_id(focused_handle.id)
 867            })
 868            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
 869        self.window
 870            .rendered_frame
 871            .dispatch_tree
 872            .is_action_available(action, target)
 873    }
 874
 875    /// The position of the mouse relative to the window.
 876    pub fn mouse_position(&self) -> Point<Pixels> {
 877        self.window.mouse_position
 878    }
 879
 880    pub fn set_cursor_style(&mut self, style: CursorStyle) {
 881        self.window.requested_cursor_style = Some(style)
 882    }
 883
 884    /// Called during painting to invoke the given closure in a new stacking context. The given
 885    /// z-index is interpreted relative to the previous call to `stack`.
 886    pub fn with_z_index<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
 887        self.window.next_frame.z_index_stack.push(z_index);
 888        let result = f(self);
 889        self.window.next_frame.z_index_stack.pop();
 890        result
 891    }
 892
 893    /// Called during painting to track which z-index is on top at each pixel position
 894    pub fn add_opaque_layer(&mut self, bounds: Bounds<Pixels>) {
 895        let stacking_order = self.window.next_frame.z_index_stack.clone();
 896        let depth_map = &mut self.window.next_frame.depth_map;
 897        match depth_map.binary_search_by(|(level, _)| stacking_order.cmp(&level)) {
 898            Ok(i) | Err(i) => depth_map.insert(i, (stacking_order, bounds)),
 899        }
 900    }
 901
 902    /// Returns true if the top-most opaque layer painted over this point was part of the
 903    /// same layer as the given stacking order.
 904    pub fn was_top_layer(&self, point: &Point<Pixels>, level: &StackingOrder) -> bool {
 905        for (stack, bounds) in self.window.rendered_frame.depth_map.iter() {
 906            if bounds.contains(point) {
 907                return level.starts_with(stack) || stack.starts_with(level);
 908            }
 909        }
 910
 911        false
 912    }
 913
 914    pub fn was_top_layer_under_active_drag(
 915        &self,
 916        point: &Point<Pixels>,
 917        level: &StackingOrder,
 918    ) -> bool {
 919        for (stack, bounds) in self.window.rendered_frame.depth_map.iter() {
 920            if stack.starts_with(&[ACTIVE_DRAG_Z_INDEX]) {
 921                continue;
 922            }
 923            if bounds.contains(point) {
 924                return level.starts_with(stack) || stack.starts_with(level);
 925            }
 926        }
 927
 928        false
 929    }
 930
 931    /// Called during painting to get the current stacking order.
 932    pub fn stacking_order(&self) -> &StackingOrder {
 933        &self.window.next_frame.z_index_stack
 934    }
 935
 936    /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
 937    pub fn paint_shadows(
 938        &mut self,
 939        bounds: Bounds<Pixels>,
 940        corner_radii: Corners<Pixels>,
 941        shadows: &[BoxShadow],
 942    ) {
 943        let scale_factor = self.scale_factor();
 944        let content_mask = self.content_mask();
 945        let window = &mut *self.window;
 946        for shadow in shadows {
 947            let mut shadow_bounds = bounds;
 948            shadow_bounds.origin += shadow.offset;
 949            shadow_bounds.dilate(shadow.spread_radius);
 950            window.next_frame.scene_builder.insert(
 951                &window.next_frame.z_index_stack,
 952                Shadow {
 953                    order: 0,
 954                    bounds: shadow_bounds.scale(scale_factor),
 955                    content_mask: content_mask.scale(scale_factor),
 956                    corner_radii: corner_radii.scale(scale_factor),
 957                    color: shadow.color,
 958                    blur_radius: shadow.blur_radius.scale(scale_factor),
 959                },
 960            );
 961        }
 962    }
 963
 964    /// Paint one or more quads into the scene for the next frame at the current stacking context.
 965    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
 966    pub fn paint_quad(
 967        &mut self,
 968        bounds: Bounds<Pixels>,
 969        corner_radii: Corners<Pixels>,
 970        background: impl Into<Hsla>,
 971        border_widths: Edges<Pixels>,
 972        border_color: impl Into<Hsla>,
 973    ) {
 974        let scale_factor = self.scale_factor();
 975        let content_mask = self.content_mask();
 976
 977        let window = &mut *self.window;
 978        window.next_frame.scene_builder.insert(
 979            &window.next_frame.z_index_stack,
 980            Quad {
 981                order: 0,
 982                bounds: bounds.scale(scale_factor),
 983                content_mask: content_mask.scale(scale_factor),
 984                background: background.into(),
 985                border_color: border_color.into(),
 986                corner_radii: corner_radii.scale(scale_factor),
 987                border_widths: border_widths.scale(scale_factor),
 988            },
 989        );
 990    }
 991
 992    /// Paint the given `Path` into the scene for the next frame at the current z-index.
 993    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
 994        let scale_factor = self.scale_factor();
 995        let content_mask = self.content_mask();
 996        path.content_mask = content_mask;
 997        path.color = color.into();
 998        let window = &mut *self.window;
 999        window
1000            .next_frame
1001            .scene_builder
1002            .insert(&window.next_frame.z_index_stack, path.scale(scale_factor));
1003    }
1004
1005    /// Paint an underline into the scene for the next frame at the current z-index.
1006    pub fn paint_underline(
1007        &mut self,
1008        origin: Point<Pixels>,
1009        width: Pixels,
1010        style: &UnderlineStyle,
1011    ) {
1012        let scale_factor = self.scale_factor();
1013        let height = if style.wavy {
1014            style.thickness * 3.
1015        } else {
1016            style.thickness
1017        };
1018        let bounds = Bounds {
1019            origin,
1020            size: size(width, height),
1021        };
1022        let content_mask = self.content_mask();
1023        let window = &mut *self.window;
1024        window.next_frame.scene_builder.insert(
1025            &window.next_frame.z_index_stack,
1026            Underline {
1027                order: 0,
1028                bounds: bounds.scale(scale_factor),
1029                content_mask: content_mask.scale(scale_factor),
1030                thickness: style.thickness.scale(scale_factor),
1031                color: style.color.unwrap_or_default(),
1032                wavy: style.wavy,
1033            },
1034        );
1035    }
1036
1037    /// Paint a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
1038    /// The y component of the origin is the baseline of the glyph.
1039    pub fn paint_glyph(
1040        &mut self,
1041        origin: Point<Pixels>,
1042        font_id: FontId,
1043        glyph_id: GlyphId,
1044        font_size: Pixels,
1045        color: Hsla,
1046    ) -> Result<()> {
1047        let scale_factor = self.scale_factor();
1048        let glyph_origin = origin.scale(scale_factor);
1049        let subpixel_variant = Point {
1050            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
1051            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
1052        };
1053        let params = RenderGlyphParams {
1054            font_id,
1055            glyph_id,
1056            font_size,
1057            subpixel_variant,
1058            scale_factor,
1059            is_emoji: false,
1060        };
1061
1062        let raster_bounds = self.text_system().raster_bounds(&params)?;
1063        if !raster_bounds.is_zero() {
1064            let tile =
1065                self.window
1066                    .sprite_atlas
1067                    .get_or_insert_with(&params.clone().into(), &mut || {
1068                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
1069                        Ok((size, Cow::Owned(bytes)))
1070                    })?;
1071            let bounds = Bounds {
1072                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
1073                size: tile.bounds.size.map(Into::into),
1074            };
1075            let content_mask = self.content_mask().scale(scale_factor);
1076            let window = &mut *self.window;
1077            window.next_frame.scene_builder.insert(
1078                &window.next_frame.z_index_stack,
1079                MonochromeSprite {
1080                    order: 0,
1081                    bounds,
1082                    content_mask,
1083                    color,
1084                    tile,
1085                },
1086            );
1087        }
1088        Ok(())
1089    }
1090
1091    /// Paint an emoji glyph into the scene for the next frame at the current z-index.
1092    /// The y component of the origin is the baseline of the glyph.
1093    pub fn paint_emoji(
1094        &mut self,
1095        origin: Point<Pixels>,
1096        font_id: FontId,
1097        glyph_id: GlyphId,
1098        font_size: Pixels,
1099    ) -> Result<()> {
1100        let scale_factor = self.scale_factor();
1101        let glyph_origin = origin.scale(scale_factor);
1102        let params = RenderGlyphParams {
1103            font_id,
1104            glyph_id,
1105            font_size,
1106            // We don't render emojis with subpixel variants.
1107            subpixel_variant: Default::default(),
1108            scale_factor,
1109            is_emoji: true,
1110        };
1111
1112        let raster_bounds = self.text_system().raster_bounds(&params)?;
1113        if !raster_bounds.is_zero() {
1114            let tile =
1115                self.window
1116                    .sprite_atlas
1117                    .get_or_insert_with(&params.clone().into(), &mut || {
1118                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
1119                        Ok((size, Cow::Owned(bytes)))
1120                    })?;
1121            let bounds = Bounds {
1122                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
1123                size: tile.bounds.size.map(Into::into),
1124            };
1125            let content_mask = self.content_mask().scale(scale_factor);
1126            let window = &mut *self.window;
1127
1128            window.next_frame.scene_builder.insert(
1129                &window.next_frame.z_index_stack,
1130                PolychromeSprite {
1131                    order: 0,
1132                    bounds,
1133                    corner_radii: Default::default(),
1134                    content_mask,
1135                    tile,
1136                    grayscale: false,
1137                },
1138            );
1139        }
1140        Ok(())
1141    }
1142
1143    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
1144    pub fn paint_svg(
1145        &mut self,
1146        bounds: Bounds<Pixels>,
1147        path: SharedString,
1148        color: Hsla,
1149    ) -> Result<()> {
1150        let scale_factor = self.scale_factor();
1151        let bounds = bounds.scale(scale_factor);
1152        // Render the SVG at twice the size to get a higher quality result.
1153        let params = RenderSvgParams {
1154            path,
1155            size: bounds
1156                .size
1157                .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
1158        };
1159
1160        let tile =
1161            self.window
1162                .sprite_atlas
1163                .get_or_insert_with(&params.clone().into(), &mut || {
1164                    let bytes = self.svg_renderer.render(&params)?;
1165                    Ok((params.size, Cow::Owned(bytes)))
1166                })?;
1167        let content_mask = self.content_mask().scale(scale_factor);
1168
1169        let window = &mut *self.window;
1170        window.next_frame.scene_builder.insert(
1171            &window.next_frame.z_index_stack,
1172            MonochromeSprite {
1173                order: 0,
1174                bounds,
1175                content_mask,
1176                color,
1177                tile,
1178            },
1179        );
1180
1181        Ok(())
1182    }
1183
1184    /// Paint an image into the scene for the next frame at the current z-index.
1185    pub fn paint_image(
1186        &mut self,
1187        bounds: Bounds<Pixels>,
1188        corner_radii: Corners<Pixels>,
1189        data: Arc<ImageData>,
1190        grayscale: bool,
1191    ) -> Result<()> {
1192        let scale_factor = self.scale_factor();
1193        let bounds = bounds.scale(scale_factor);
1194        let params = RenderImageParams { image_id: data.id };
1195
1196        let tile = self
1197            .window
1198            .sprite_atlas
1199            .get_or_insert_with(&params.clone().into(), &mut || {
1200                Ok((data.size(), Cow::Borrowed(data.as_bytes())))
1201            })?;
1202        let content_mask = self.content_mask().scale(scale_factor);
1203        let corner_radii = corner_radii.scale(scale_factor);
1204
1205        let window = &mut *self.window;
1206        window.next_frame.scene_builder.insert(
1207            &window.next_frame.z_index_stack,
1208            PolychromeSprite {
1209                order: 0,
1210                bounds,
1211                content_mask,
1212                corner_radii,
1213                tile,
1214                grayscale,
1215            },
1216        );
1217        Ok(())
1218    }
1219
1220    /// Paint a surface into the scene for the next frame at the current z-index.
1221    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
1222        let scale_factor = self.scale_factor();
1223        let bounds = bounds.scale(scale_factor);
1224        let content_mask = self.content_mask().scale(scale_factor);
1225        let window = &mut *self.window;
1226        window.next_frame.scene_builder.insert(
1227            &window.next_frame.z_index_stack,
1228            Surface {
1229                order: 0,
1230                bounds,
1231                content_mask,
1232                image_buffer,
1233            },
1234        );
1235    }
1236
1237    /// Draw pixels to the display for this window based on the contents of its scene.
1238    pub(crate) fn draw(&mut self) -> Scene {
1239        let window_was_focused = self
1240            .window
1241            .focus
1242            .and_then(|focus_id| {
1243                self.window
1244                    .rendered_frame
1245                    .dispatch_tree
1246                    .focusable_node_id(focus_id)
1247            })
1248            .is_some();
1249        self.text_system().start_frame();
1250        self.window.platform_window.clear_input_handler();
1251        self.window.layout_engine.as_mut().unwrap().clear();
1252        self.window.next_frame.clear();
1253        let root_view = self.window.root_view.take().unwrap();
1254
1255        self.with_z_index(0, |cx| {
1256            cx.with_key_dispatch(Some(KeyContext::default()), None, |_, cx| {
1257                for (action_type, action_listeners) in &cx.app.global_action_listeners {
1258                    for action_listener in action_listeners.iter().cloned() {
1259                        cx.window.next_frame.dispatch_tree.on_action(
1260                            *action_type,
1261                            Rc::new(move |action, phase, cx| action_listener(action, phase, cx)),
1262                        )
1263                    }
1264                }
1265
1266                let available_space = cx.window.viewport_size.map(Into::into);
1267                root_view.draw(Point::default(), available_space, cx);
1268            })
1269        });
1270
1271        if let Some(active_drag) = self.app.active_drag.take() {
1272            self.with_z_index(ACTIVE_DRAG_Z_INDEX, |cx| {
1273                let offset = cx.mouse_position() - active_drag.cursor_offset;
1274                let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1275                active_drag.view.draw(offset, available_space, cx);
1276            });
1277            self.active_drag = Some(active_drag);
1278        } else if let Some(active_tooltip) = self.app.active_tooltip.take() {
1279            self.with_z_index(1, |cx| {
1280                let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1281                active_tooltip
1282                    .view
1283                    .draw(active_tooltip.cursor_offset, available_space, cx);
1284            });
1285        }
1286
1287        let window_is_focused = self
1288            .window
1289            .focus
1290            .and_then(|focus_id| {
1291                self.window
1292                    .next_frame
1293                    .dispatch_tree
1294                    .focusable_node_id(focus_id)
1295            })
1296            .is_some();
1297        if window_was_focused && !window_is_focused {
1298            self.window
1299                .blur_listeners
1300                .clone()
1301                .retain(&(), |listener| listener(self));
1302        }
1303
1304        self.window
1305            .next_frame
1306            .dispatch_tree
1307            .preserve_pending_keystrokes(
1308                &mut self.window.rendered_frame.dispatch_tree,
1309                self.window.focus,
1310            );
1311        self.window.root_view = Some(root_view);
1312
1313        let window = &mut self.window;
1314        mem::swap(&mut window.rendered_frame, &mut window.next_frame);
1315
1316        let scene = self.window.rendered_frame.scene_builder.build();
1317
1318        // Set the cursor only if we're the active window.
1319        let cursor_style = self
1320            .window
1321            .requested_cursor_style
1322            .take()
1323            .unwrap_or(CursorStyle::Arrow);
1324        if self.is_window_active() {
1325            self.platform.set_cursor_style(cursor_style);
1326        }
1327
1328        self.window.dirty = false;
1329
1330        scene
1331    }
1332
1333    /// Dispatch a mouse or keyboard event on the window.
1334    pub fn dispatch_event(&mut self, event: InputEvent) -> bool {
1335        // Handlers may set this to false by calling `stop_propagation`.
1336        self.app.propagate_event = true;
1337        // Handlers may set this to true by calling `prevent_default`.
1338        self.window.default_prevented = false;
1339
1340        let event = match event {
1341            // Track the mouse position with our own state, since accessing the platform
1342            // API for the mouse position can only occur on the main thread.
1343            InputEvent::MouseMove(mouse_move) => {
1344                self.window.mouse_position = mouse_move.position;
1345                InputEvent::MouseMove(mouse_move)
1346            }
1347            InputEvent::MouseDown(mouse_down) => {
1348                self.window.mouse_position = mouse_down.position;
1349                InputEvent::MouseDown(mouse_down)
1350            }
1351            InputEvent::MouseUp(mouse_up) => {
1352                self.window.mouse_position = mouse_up.position;
1353                InputEvent::MouseUp(mouse_up)
1354            }
1355            // Translate dragging and dropping of external files from the operating system
1356            // to internal drag and drop events.
1357            InputEvent::FileDrop(file_drop) => match file_drop {
1358                FileDropEvent::Entered { position, files } => {
1359                    self.window.mouse_position = position;
1360                    if self.active_drag.is_none() {
1361                        self.active_drag = Some(AnyDrag {
1362                            view: self.build_view(|_| files).into(),
1363                            cursor_offset: position,
1364                        });
1365                    }
1366                    InputEvent::MouseMove(MouseMoveEvent {
1367                        position,
1368                        pressed_button: Some(MouseButton::Left),
1369                        modifiers: Modifiers::default(),
1370                    })
1371                }
1372                FileDropEvent::Pending { position } => {
1373                    self.window.mouse_position = position;
1374                    InputEvent::MouseMove(MouseMoveEvent {
1375                        position,
1376                        pressed_button: Some(MouseButton::Left),
1377                        modifiers: Modifiers::default(),
1378                    })
1379                }
1380                FileDropEvent::Submit { position } => {
1381                    self.activate(true);
1382                    self.window.mouse_position = position;
1383                    InputEvent::MouseUp(MouseUpEvent {
1384                        button: MouseButton::Left,
1385                        position,
1386                        modifiers: Modifiers::default(),
1387                        click_count: 1,
1388                    })
1389                }
1390                FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1391                    button: MouseButton::Left,
1392                    position: Point::default(),
1393                    modifiers: Modifiers::default(),
1394                    click_count: 1,
1395                }),
1396            },
1397            _ => event,
1398        };
1399
1400        if let Some(any_mouse_event) = event.mouse_event() {
1401            self.dispatch_mouse_event(any_mouse_event);
1402        } else if let Some(any_key_event) = event.keyboard_event() {
1403            self.dispatch_key_event(any_key_event);
1404        }
1405
1406        !self.app.propagate_event
1407    }
1408
1409    fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1410        if let Some(mut handlers) = self
1411            .window
1412            .rendered_frame
1413            .mouse_listeners
1414            .remove(&event.type_id())
1415        {
1416            // Because handlers may add other handlers, we sort every time.
1417            handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1418
1419            // Capture phase, events bubble from back to front. Handlers for this phase are used for
1420            // special purposes, such as detecting events outside of a given Bounds.
1421            for (_, handler) in &mut handlers {
1422                handler(event, DispatchPhase::Capture, self);
1423                if !self.app.propagate_event {
1424                    break;
1425                }
1426            }
1427
1428            // Bubble phase, where most normal handlers do their work.
1429            if self.app.propagate_event {
1430                for (_, handler) in handlers.iter_mut().rev() {
1431                    handler(event, DispatchPhase::Bubble, self);
1432                    if !self.app.propagate_event {
1433                        break;
1434                    }
1435                }
1436            }
1437
1438            if self.app.propagate_event && event.downcast_ref::<MouseUpEvent>().is_some() {
1439                self.active_drag = None;
1440            }
1441
1442            self.window
1443                .rendered_frame
1444                .mouse_listeners
1445                .insert(event.type_id(), handlers);
1446        }
1447    }
1448
1449    fn dispatch_key_event(&mut self, event: &dyn Any) {
1450        let node_id = self
1451            .window
1452            .focus
1453            .and_then(|focus_id| {
1454                self.window
1455                    .rendered_frame
1456                    .dispatch_tree
1457                    .focusable_node_id(focus_id)
1458            })
1459            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1460
1461        let dispatch_path = self
1462            .window
1463            .rendered_frame
1464            .dispatch_tree
1465            .dispatch_path(node_id);
1466
1467        let mut actions: Vec<Box<dyn Action>> = Vec::new();
1468
1469        // Capture phase
1470        let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
1471        self.propagate_event = true;
1472
1473        for node_id in &dispatch_path {
1474            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1475
1476            if let Some(context) = node.context.clone() {
1477                context_stack.push(context);
1478            }
1479
1480            for key_listener in node.key_listeners.clone() {
1481                key_listener(event, DispatchPhase::Capture, self);
1482                if !self.propagate_event {
1483                    return;
1484                }
1485            }
1486        }
1487
1488        // Bubble phase
1489        for node_id in dispatch_path.iter().rev() {
1490            // Handle low level key events
1491            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1492            for key_listener in node.key_listeners.clone() {
1493                key_listener(event, DispatchPhase::Bubble, self);
1494                if !self.propagate_event {
1495                    return;
1496                }
1497            }
1498
1499            // Match keystrokes
1500            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1501            if node.context.is_some() {
1502                if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1503                    let mut new_actions = self
1504                        .window
1505                        .rendered_frame
1506                        .dispatch_tree
1507                        .dispatch_key(&key_down_event.keystroke, &context_stack);
1508                    actions.append(&mut new_actions);
1509                }
1510
1511                context_stack.pop();
1512            }
1513        }
1514
1515        for action in actions {
1516            self.dispatch_action_on_node(node_id, action.boxed_clone());
1517            if !self.propagate_event {
1518                self.dispatch_keystroke_observers(event, Some(action));
1519                return;
1520            }
1521        }
1522        self.dispatch_keystroke_observers(event, None);
1523    }
1524
1525    pub fn has_pending_keystrokes(&self) -> bool {
1526        self.window
1527            .rendered_frame
1528            .dispatch_tree
1529            .has_pending_keystrokes()
1530    }
1531
1532    fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
1533        let dispatch_path = self
1534            .window
1535            .rendered_frame
1536            .dispatch_tree
1537            .dispatch_path(node_id);
1538
1539        // Capture phase
1540        for node_id in &dispatch_path {
1541            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1542            for DispatchActionListener {
1543                action_type,
1544                listener,
1545            } in node.action_listeners.clone()
1546            {
1547                let any_action = action.as_any();
1548                if action_type == any_action.type_id() {
1549                    listener(any_action, DispatchPhase::Capture, self);
1550                    if !self.propagate_event {
1551                        return;
1552                    }
1553                }
1554            }
1555        }
1556        // Bubble phase
1557        for node_id in dispatch_path.iter().rev() {
1558            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1559            for DispatchActionListener {
1560                action_type,
1561                listener,
1562            } in node.action_listeners.clone()
1563            {
1564                let any_action = action.as_any();
1565                if action_type == any_action.type_id() {
1566                    self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1567                    listener(any_action, DispatchPhase::Bubble, self);
1568                    if !self.propagate_event {
1569                        return;
1570                    }
1571                }
1572            }
1573        }
1574    }
1575
1576    /// Register the given handler to be invoked whenever the global of the given type
1577    /// is updated.
1578    pub fn observe_global<G: 'static>(
1579        &mut self,
1580        f: impl Fn(&mut WindowContext<'_>) + 'static,
1581    ) -> Subscription {
1582        let window_handle = self.window.handle;
1583        let (subscription, activate) = self.global_observers.insert(
1584            TypeId::of::<G>(),
1585            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1586        );
1587        self.app.defer(move |_| activate());
1588        subscription
1589    }
1590
1591    pub fn activate_window(&self) {
1592        self.window.platform_window.activate();
1593    }
1594
1595    pub fn minimize_window(&self) {
1596        self.window.platform_window.minimize();
1597    }
1598
1599    pub fn toggle_full_screen(&self) {
1600        self.window.platform_window.toggle_full_screen();
1601    }
1602
1603    pub fn prompt(
1604        &self,
1605        level: PromptLevel,
1606        msg: &str,
1607        answers: &[&str],
1608    ) -> oneshot::Receiver<usize> {
1609        self.window.platform_window.prompt(level, msg, answers)
1610    }
1611
1612    pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1613        let node_id = self
1614            .window
1615            .focus
1616            .and_then(|focus_id| {
1617                self.window
1618                    .rendered_frame
1619                    .dispatch_tree
1620                    .focusable_node_id(focus_id)
1621            })
1622            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1623
1624        self.window
1625            .rendered_frame
1626            .dispatch_tree
1627            .available_actions(node_id)
1628    }
1629
1630    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1631        self.window
1632            .rendered_frame
1633            .dispatch_tree
1634            .bindings_for_action(
1635                action,
1636                &self.window.rendered_frame.dispatch_tree.context_stack,
1637            )
1638    }
1639
1640    pub fn bindings_for_action_in(
1641        &self,
1642        action: &dyn Action,
1643        focus_handle: &FocusHandle,
1644    ) -> Vec<KeyBinding> {
1645        let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1646
1647        let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1648            return vec![];
1649        };
1650        let context_stack = dispatch_tree
1651            .dispatch_path(node_id)
1652            .into_iter()
1653            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1654            .collect();
1655        dispatch_tree.bindings_for_action(action, &context_stack)
1656    }
1657
1658    pub fn listener_for<V: Render, E>(
1659        &self,
1660        view: &View<V>,
1661        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1662    ) -> impl Fn(&E, &mut WindowContext) + 'static {
1663        let view = view.downgrade();
1664        move |e: &E, cx: &mut WindowContext| {
1665            view.update(cx, |view, cx| f(view, e, cx)).ok();
1666        }
1667    }
1668
1669    pub fn handler_for<V: Render>(
1670        &self,
1671        view: &View<V>,
1672        f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1673    ) -> impl Fn(&mut WindowContext) {
1674        let view = view.downgrade();
1675        move |cx: &mut WindowContext| {
1676            view.update(cx, |view, cx| f(view, cx)).ok();
1677        }
1678    }
1679
1680    //========== ELEMENT RELATED FUNCTIONS ===========
1681    pub fn with_key_dispatch<R>(
1682        &mut self,
1683        context: Option<KeyContext>,
1684        focus_handle: Option<FocusHandle>,
1685        f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
1686    ) -> R {
1687        let window = &mut self.window;
1688        window.next_frame.dispatch_tree.push_node(context.clone());
1689        if let Some(focus_handle) = focus_handle.as_ref() {
1690            window
1691                .next_frame
1692                .dispatch_tree
1693                .make_focusable(focus_handle.id);
1694        }
1695        let result = f(focus_handle, self);
1696
1697        self.window.next_frame.dispatch_tree.pop_node();
1698
1699        result
1700    }
1701
1702    /// Register a focus listener for the next frame only. It will be cleared
1703    /// on the next frame render. You should use this method only from within elements,
1704    /// and we may want to enforce that better via a different context type.
1705    // todo!() Move this to `FrameContext` to emphasize its individuality?
1706    pub fn on_focus_changed(
1707        &mut self,
1708        listener: impl Fn(&FocusEvent, &mut WindowContext) + 'static,
1709    ) {
1710        self.window
1711            .next_frame
1712            .focus_listeners
1713            .push(Box::new(move |event, cx| {
1714                listener(event, cx);
1715            }));
1716    }
1717
1718    /// Set an input handler, such as [ElementInputHandler], which interfaces with the
1719    /// platform to receive textual input with proper integration with concerns such
1720    /// as IME interactions.
1721    pub fn handle_input(
1722        &mut self,
1723        focus_handle: &FocusHandle,
1724        input_handler: impl PlatformInputHandler,
1725    ) {
1726        if focus_handle.is_focused(self) {
1727            self.window
1728                .platform_window
1729                .set_input_handler(Box::new(input_handler));
1730        }
1731    }
1732
1733    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1734        let mut this = self.to_async();
1735        self.window
1736            .platform_window
1737            .on_should_close(Box::new(move || this.update(|_, cx| f(cx)).unwrap_or(true)))
1738    }
1739}
1740
1741impl Context for WindowContext<'_> {
1742    type Result<T> = T;
1743
1744    fn build_model<T>(
1745        &mut self,
1746        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1747    ) -> Model<T>
1748    where
1749        T: 'static,
1750    {
1751        let slot = self.app.entities.reserve();
1752        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1753        self.entities.insert(slot, model)
1754    }
1755
1756    fn update_model<T: 'static, R>(
1757        &mut self,
1758        model: &Model<T>,
1759        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1760    ) -> R {
1761        let mut entity = self.entities.lease(model);
1762        let result = update(
1763            &mut *entity,
1764            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1765        );
1766        self.entities.end_lease(entity);
1767        result
1768    }
1769
1770    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1771    where
1772        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1773    {
1774        if window == self.window.handle {
1775            let root_view = self.window.root_view.clone().unwrap();
1776            Ok(update(root_view, self))
1777        } else {
1778            window.update(self.app, update)
1779        }
1780    }
1781
1782    fn read_model<T, R>(
1783        &self,
1784        handle: &Model<T>,
1785        read: impl FnOnce(&T, &AppContext) -> R,
1786    ) -> Self::Result<R>
1787    where
1788        T: 'static,
1789    {
1790        let entity = self.entities.read(handle);
1791        read(&*entity, &*self.app)
1792    }
1793
1794    fn read_window<T, R>(
1795        &self,
1796        window: &WindowHandle<T>,
1797        read: impl FnOnce(View<T>, &AppContext) -> R,
1798    ) -> Result<R>
1799    where
1800        T: 'static,
1801    {
1802        if window.any_handle == self.window.handle {
1803            let root_view = self
1804                .window
1805                .root_view
1806                .clone()
1807                .unwrap()
1808                .downcast::<T>()
1809                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1810            Ok(read(root_view, self))
1811        } else {
1812            self.app.read_window(window, read)
1813        }
1814    }
1815}
1816
1817impl VisualContext for WindowContext<'_> {
1818    fn build_view<V>(
1819        &mut self,
1820        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1821    ) -> Self::Result<View<V>>
1822    where
1823        V: 'static + Render,
1824    {
1825        let slot = self.app.entities.reserve();
1826        let view = View {
1827            model: slot.clone(),
1828        };
1829        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1830        let entity = build_view_state(&mut cx);
1831        cx.entities.insert(slot, entity);
1832
1833        cx.new_view_observers
1834            .clone()
1835            .retain(&TypeId::of::<V>(), |observer| {
1836                let any_view = AnyView::from(view.clone());
1837                (observer)(any_view, self);
1838                true
1839            });
1840
1841        view
1842    }
1843
1844    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1845    fn update_view<T: 'static, R>(
1846        &mut self,
1847        view: &View<T>,
1848        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1849    ) -> Self::Result<R> {
1850        let mut lease = self.app.entities.lease(&view.model);
1851        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1852        let result = update(&mut *lease, &mut cx);
1853        cx.app.entities.end_lease(lease);
1854        result
1855    }
1856
1857    fn replace_root_view<V>(
1858        &mut self,
1859        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1860    ) -> Self::Result<View<V>>
1861    where
1862        V: 'static + Render,
1863    {
1864        let slot = self.app.entities.reserve();
1865        let view = View {
1866            model: slot.clone(),
1867        };
1868        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1869        let entity = build_view(&mut cx);
1870        self.entities.insert(slot, entity);
1871        self.window.root_view = Some(view.clone().into());
1872        view
1873    }
1874
1875    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1876        self.update_view(view, |view, cx| {
1877            view.focus_handle(cx).clone().focus(cx);
1878        })
1879    }
1880
1881    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1882    where
1883        V: ManagedView,
1884    {
1885        self.update_view(view, |_, cx| cx.emit(DismissEvent))
1886    }
1887}
1888
1889impl<'a> std::ops::Deref for WindowContext<'a> {
1890    type Target = AppContext;
1891
1892    fn deref(&self) -> &Self::Target {
1893        &self.app
1894    }
1895}
1896
1897impl<'a> std::ops::DerefMut for WindowContext<'a> {
1898    fn deref_mut(&mut self) -> &mut Self::Target {
1899        &mut self.app
1900    }
1901}
1902
1903impl<'a> Borrow<AppContext> for WindowContext<'a> {
1904    fn borrow(&self) -> &AppContext {
1905        &self.app
1906    }
1907}
1908
1909impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1910    fn borrow_mut(&mut self) -> &mut AppContext {
1911        &mut self.app
1912    }
1913}
1914
1915pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1916    fn app_mut(&mut self) -> &mut AppContext {
1917        self.borrow_mut()
1918    }
1919
1920    fn app(&self) -> &AppContext {
1921        self.borrow()
1922    }
1923
1924    fn window(&self) -> &Window {
1925        self.borrow()
1926    }
1927
1928    fn window_mut(&mut self) -> &mut Window {
1929        self.borrow_mut()
1930    }
1931
1932    /// Pushes the given element id onto the global stack and invokes the given closure
1933    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1934    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1935    /// used to associate state with identified elements across separate frames.
1936    fn with_element_id<R>(
1937        &mut self,
1938        id: Option<impl Into<ElementId>>,
1939        f: impl FnOnce(&mut Self) -> R,
1940    ) -> R {
1941        if let Some(id) = id.map(Into::into) {
1942            let window = self.window_mut();
1943            window.element_id_stack.push(id.into());
1944            let result = f(self);
1945            let window: &mut Window = self.borrow_mut();
1946            window.element_id_stack.pop();
1947            result
1948        } else {
1949            f(self)
1950        }
1951    }
1952
1953    /// Invoke the given function with the given content mask after intersecting it
1954    /// with the current mask.
1955    fn with_content_mask<R>(
1956        &mut self,
1957        mask: Option<ContentMask<Pixels>>,
1958        f: impl FnOnce(&mut Self) -> R,
1959    ) -> R {
1960        if let Some(mask) = mask {
1961            let mask = mask.intersect(&self.content_mask());
1962            self.window_mut().next_frame.content_mask_stack.push(mask);
1963            let result = f(self);
1964            self.window_mut().next_frame.content_mask_stack.pop();
1965            result
1966        } else {
1967            f(self)
1968        }
1969    }
1970
1971    /// Invoke the given function with the content mask reset to that
1972    /// of the window.
1973    fn break_content_mask<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
1974        let mask = ContentMask {
1975            bounds: Bounds {
1976                origin: Point::default(),
1977                size: self.window().viewport_size,
1978            },
1979        };
1980        self.window_mut().next_frame.content_mask_stack.push(mask);
1981        let result = f(self);
1982        self.window_mut().next_frame.content_mask_stack.pop();
1983        result
1984    }
1985
1986    /// Update the global element offset relative to the current offset. This is used to implement
1987    /// scrolling.
1988    fn with_element_offset<R>(
1989        &mut self,
1990        offset: Point<Pixels>,
1991        f: impl FnOnce(&mut Self) -> R,
1992    ) -> R {
1993        if offset.is_zero() {
1994            return f(self);
1995        };
1996
1997        let abs_offset = self.element_offset() + offset;
1998        self.with_absolute_element_offset(abs_offset, f)
1999    }
2000
2001    /// Update the global element offset based on the given offset. This is used to implement
2002    /// drag handles and other manual painting of elements.
2003    fn with_absolute_element_offset<R>(
2004        &mut self,
2005        offset: Point<Pixels>,
2006        f: impl FnOnce(&mut Self) -> R,
2007    ) -> R {
2008        self.window_mut()
2009            .next_frame
2010            .element_offset_stack
2011            .push(offset);
2012        let result = f(self);
2013        self.window_mut().next_frame.element_offset_stack.pop();
2014        result
2015    }
2016
2017    /// Obtain the current element offset.
2018    fn element_offset(&self) -> Point<Pixels> {
2019        self.window()
2020            .next_frame
2021            .element_offset_stack
2022            .last()
2023            .copied()
2024            .unwrap_or_default()
2025    }
2026
2027    /// Update or initialize state for an element with the given id that lives across multiple
2028    /// frames. If an element with this id existed in the rendered frame, its state will be passed
2029    /// to the given closure. The state returned by the closure will be stored so it can be referenced
2030    /// when drawing the next frame.
2031    fn with_element_state<S, R>(
2032        &mut self,
2033        id: ElementId,
2034        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2035    ) -> R
2036    where
2037        S: 'static,
2038    {
2039        self.with_element_id(Some(id), |cx| {
2040            let global_id = cx.window().element_id_stack.clone();
2041
2042            if let Some(any) = cx
2043                .window_mut()
2044                .next_frame
2045                .element_states
2046                .remove(&global_id)
2047                .or_else(|| {
2048                    cx.window_mut()
2049                        .rendered_frame
2050                        .element_states
2051                        .remove(&global_id)
2052                })
2053            {
2054                let ElementStateBox {
2055                    inner,
2056
2057                    #[cfg(debug_assertions)]
2058                    type_name
2059                } = any;
2060                // Using the extra inner option to avoid needing to reallocate a new box.
2061                let mut state_box = inner
2062                    .downcast::<Option<S>>()
2063                    .map_err(|_| {
2064                        #[cfg(debug_assertions)]
2065                        {
2066                            anyhow!(
2067                                "invalid element state type for id, requested_type {:?}, actual type: {:?}",
2068                                std::any::type_name::<S>(),
2069                                type_name
2070                            )
2071                        }
2072
2073                        #[cfg(not(debug_assertions))]
2074                        {
2075                            anyhow!(
2076                                "invalid element state type for id, requested_type {:?}",
2077                                std::any::type_name::<S>(),
2078                            )
2079                        }
2080                    })
2081                    .unwrap();
2082
2083                // Actual: Option<AnyElement> <- View
2084                // Requested: () <- AnyElemet
2085                let state = state_box
2086                    .take()
2087                    .expect("element state is already on the stack");
2088                let (result, state) = f(Some(state), cx);
2089                state_box.replace(state);
2090                cx.window_mut()
2091                    .next_frame
2092                    .element_states
2093                    .insert(global_id, ElementStateBox {
2094                        inner: state_box,
2095
2096                        #[cfg(debug_assertions)]
2097                        type_name
2098                    });
2099                result
2100            } else {
2101                let (result, state) = f(None, cx);
2102                cx.window_mut()
2103                    .next_frame
2104                    .element_states
2105                    .insert(global_id,
2106                        ElementStateBox {
2107                            inner: Box::new(Some(state)),
2108
2109                            #[cfg(debug_assertions)]
2110                            type_name: std::any::type_name::<S>()
2111                        }
2112
2113                    );
2114                result
2115            }
2116        })
2117    }
2118
2119    /// Obtain the current content mask.
2120    fn content_mask(&self) -> ContentMask<Pixels> {
2121        self.window()
2122            .next_frame
2123            .content_mask_stack
2124            .last()
2125            .cloned()
2126            .unwrap_or_else(|| ContentMask {
2127                bounds: Bounds {
2128                    origin: Point::default(),
2129                    size: self.window().viewport_size,
2130                },
2131            })
2132    }
2133
2134    /// The size of an em for the base font of the application. Adjusting this value allows the
2135    /// UI to scale, just like zooming a web page.
2136    fn rem_size(&self) -> Pixels {
2137        self.window().rem_size
2138    }
2139}
2140
2141impl Borrow<Window> for WindowContext<'_> {
2142    fn borrow(&self) -> &Window {
2143        &self.window
2144    }
2145}
2146
2147impl BorrowMut<Window> for WindowContext<'_> {
2148    fn borrow_mut(&mut self) -> &mut Window {
2149        &mut self.window
2150    }
2151}
2152
2153impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
2154
2155pub struct ViewContext<'a, V> {
2156    window_cx: WindowContext<'a>,
2157    view: &'a View<V>,
2158}
2159
2160impl<V> Borrow<AppContext> for ViewContext<'_, V> {
2161    fn borrow(&self) -> &AppContext {
2162        &*self.window_cx.app
2163    }
2164}
2165
2166impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
2167    fn borrow_mut(&mut self) -> &mut AppContext {
2168        &mut *self.window_cx.app
2169    }
2170}
2171
2172impl<V> Borrow<Window> for ViewContext<'_, V> {
2173    fn borrow(&self) -> &Window {
2174        &*self.window_cx.window
2175    }
2176}
2177
2178impl<V> BorrowMut<Window> for ViewContext<'_, V> {
2179    fn borrow_mut(&mut self) -> &mut Window {
2180        &mut *self.window_cx.window
2181    }
2182}
2183
2184impl<'a, V: 'static> ViewContext<'a, V> {
2185    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
2186        Self {
2187            window_cx: WindowContext::new(app, window),
2188            view,
2189        }
2190    }
2191
2192    pub fn entity_id(&self) -> EntityId {
2193        self.view.entity_id()
2194    }
2195
2196    pub fn view(&self) -> &View<V> {
2197        self.view
2198    }
2199
2200    pub fn model(&self) -> &Model<V> {
2201        &self.view.model
2202    }
2203
2204    /// Access the underlying window context.
2205    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2206        &mut self.window_cx
2207    }
2208
2209    pub fn with_z_index<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
2210        self.window.next_frame.z_index_stack.push(z_index);
2211        let result = f(self);
2212        self.window.next_frame.z_index_stack.pop();
2213        result
2214    }
2215
2216    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2217    where
2218        V: 'static,
2219    {
2220        let view = self.view().clone();
2221        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2222    }
2223
2224    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2225    /// that are currently on the stack to be returned to the app.
2226    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2227        let view = self.view().downgrade();
2228        self.window_cx.defer(move |cx| {
2229            view.update(cx, f).ok();
2230        });
2231    }
2232
2233    pub fn observe<V2, E>(
2234        &mut self,
2235        entity: &E,
2236        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2237    ) -> Subscription
2238    where
2239        V2: 'static,
2240        V: 'static,
2241        E: Entity<V2>,
2242    {
2243        let view = self.view().downgrade();
2244        let entity_id = entity.entity_id();
2245        let entity = entity.downgrade();
2246        let window_handle = self.window.handle;
2247        let (subscription, activate) = self.app.observers.insert(
2248            entity_id,
2249            Box::new(move |cx| {
2250                window_handle
2251                    .update(cx, |_, cx| {
2252                        if let Some(handle) = E::upgrade_from(&entity) {
2253                            view.update(cx, |this, cx| on_notify(this, handle, cx))
2254                                .is_ok()
2255                        } else {
2256                            false
2257                        }
2258                    })
2259                    .unwrap_or(false)
2260            }),
2261        );
2262        self.app.defer(move |_| activate());
2263        subscription
2264    }
2265
2266    pub fn subscribe<V2, E, Evt>(
2267        &mut self,
2268        entity: &E,
2269        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2270    ) -> Subscription
2271    where
2272        V2: EventEmitter<Evt>,
2273        E: Entity<V2>,
2274        Evt: 'static,
2275    {
2276        let view = self.view().downgrade();
2277        let entity_id = entity.entity_id();
2278        let handle = entity.downgrade();
2279        let window_handle = self.window.handle;
2280        let (subscription, activate) = self.app.event_listeners.insert(
2281            entity_id,
2282            (
2283                TypeId::of::<Evt>(),
2284                Box::new(move |event, cx| {
2285                    window_handle
2286                        .update(cx, |_, cx| {
2287                            if let Some(handle) = E::upgrade_from(&handle) {
2288                                let event = event.downcast_ref().expect("invalid event type");
2289                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
2290                                    .is_ok()
2291                            } else {
2292                                false
2293                            }
2294                        })
2295                        .unwrap_or(false)
2296                }),
2297            ),
2298        );
2299        self.app.defer(move |_| activate());
2300        subscription
2301    }
2302
2303    pub fn on_release(
2304        &mut self,
2305        on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
2306    ) -> Subscription {
2307        let window_handle = self.window.handle;
2308        let (subscription, activate) = self.app.release_listeners.insert(
2309            self.view.model.entity_id,
2310            Box::new(move |this, cx| {
2311                let this = this.downcast_mut().expect("invalid entity type");
2312                let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
2313            }),
2314        );
2315        activate();
2316        subscription
2317    }
2318
2319    pub fn observe_release<V2, E>(
2320        &mut self,
2321        entity: &E,
2322        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2323    ) -> Subscription
2324    where
2325        V: 'static,
2326        V2: 'static,
2327        E: Entity<V2>,
2328    {
2329        let view = self.view().downgrade();
2330        let entity_id = entity.entity_id();
2331        let window_handle = self.window.handle;
2332        let (subscription, activate) = self.app.release_listeners.insert(
2333            entity_id,
2334            Box::new(move |entity, cx| {
2335                let entity = entity.downcast_mut().expect("invalid entity type");
2336                let _ = window_handle.update(cx, |_, cx| {
2337                    view.update(cx, |this, cx| on_release(this, entity, cx))
2338                });
2339            }),
2340        );
2341        activate();
2342        subscription
2343    }
2344
2345    pub fn notify(&mut self) {
2346        self.window_cx.notify();
2347        self.window_cx.app.push_effect(Effect::Notify {
2348            emitter: self.view.model.entity_id,
2349        });
2350    }
2351
2352    pub fn observe_window_bounds(
2353        &mut self,
2354        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2355    ) -> Subscription {
2356        let view = self.view.downgrade();
2357        let (subscription, activate) = self.window.bounds_observers.insert(
2358            (),
2359            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2360        );
2361        activate();
2362        subscription
2363    }
2364
2365    pub fn observe_window_activation(
2366        &mut self,
2367        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2368    ) -> Subscription {
2369        let view = self.view.downgrade();
2370        let (subscription, activate) = self.window.activation_observers.insert(
2371            (),
2372            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2373        );
2374        activate();
2375        subscription
2376    }
2377
2378    /// Register a listener to be called when the given focus handle receives focus.
2379    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2380    /// is dropped.
2381    pub fn on_focus(
2382        &mut self,
2383        handle: &FocusHandle,
2384        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2385    ) -> Subscription {
2386        let view = self.view.downgrade();
2387        let focus_id = handle.id;
2388        let (subscription, activate) = self.window.focus_listeners.insert(
2389            (),
2390            Box::new(move |event, cx| {
2391                view.update(cx, |view, cx| {
2392                    if event.focused.as_ref().map(|focused| focused.id) == Some(focus_id) {
2393                        listener(view, cx)
2394                    }
2395                })
2396                .is_ok()
2397            }),
2398        );
2399        self.app.defer(move |_| activate());
2400        subscription
2401    }
2402
2403    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2404    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2405    /// is dropped.
2406    pub fn on_focus_in(
2407        &mut self,
2408        handle: &FocusHandle,
2409        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2410    ) -> Subscription {
2411        let view = self.view.downgrade();
2412        let focus_id = handle.id;
2413        let (subscription, activate) = self.window.focus_listeners.insert(
2414            (),
2415            Box::new(move |event, cx| {
2416                view.update(cx, |view, cx| {
2417                    if event
2418                        .focused
2419                        .as_ref()
2420                        .map_or(false, |focused| focus_id.contains(focused.id, cx))
2421                    {
2422                        listener(view, cx)
2423                    }
2424                })
2425                .is_ok()
2426            }),
2427        );
2428        self.app.defer(move |_| activate());
2429        subscription
2430    }
2431
2432    /// Register a listener to be called when the given focus handle loses focus.
2433    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2434    /// is dropped.
2435    pub fn on_blur(
2436        &mut self,
2437        handle: &FocusHandle,
2438        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2439    ) -> Subscription {
2440        let view = self.view.downgrade();
2441        let focus_id = handle.id;
2442        let (subscription, activate) = self.window.focus_listeners.insert(
2443            (),
2444            Box::new(move |event, cx| {
2445                view.update(cx, |view, cx| {
2446                    if event.blurred.as_ref().map(|blurred| blurred.id) == Some(focus_id) {
2447                        listener(view, cx)
2448                    }
2449                })
2450                .is_ok()
2451            }),
2452        );
2453        self.app.defer(move |_| activate());
2454        subscription
2455    }
2456
2457    /// Register a listener to be called when the window loses focus.
2458    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2459    /// is dropped.
2460    pub fn on_blur_window(
2461        &mut self,
2462        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2463    ) -> Subscription {
2464        let view = self.view.downgrade();
2465        let (subscription, activate) = self.window.blur_listeners.insert(
2466            (),
2467            Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2468        );
2469        activate();
2470        subscription
2471    }
2472
2473    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2474    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2475    /// is dropped.
2476    pub fn on_focus_out(
2477        &mut self,
2478        handle: &FocusHandle,
2479        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2480    ) -> Subscription {
2481        let view = self.view.downgrade();
2482        let focus_id = handle.id;
2483        let (subscription, activate) = self.window.focus_listeners.insert(
2484            (),
2485            Box::new(move |event, cx| {
2486                view.update(cx, |view, cx| {
2487                    if event
2488                        .blurred
2489                        .as_ref()
2490                        .map_or(false, |blurred| focus_id.contains(blurred.id, cx))
2491                    {
2492                        listener(view, cx)
2493                    }
2494                })
2495                .is_ok()
2496            }),
2497        );
2498        self.app.defer(move |_| activate());
2499        subscription
2500    }
2501
2502    pub fn spawn<Fut, R>(
2503        &mut self,
2504        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2505    ) -> Task<R>
2506    where
2507        R: 'static,
2508        Fut: Future<Output = R> + 'static,
2509    {
2510        let view = self.view().downgrade();
2511        self.window_cx.spawn(|cx| f(view, cx))
2512    }
2513
2514    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2515    where
2516        G: 'static,
2517    {
2518        let mut global = self.app.lease_global::<G>();
2519        let result = f(&mut global, self);
2520        self.app.end_global_lease(global);
2521        result
2522    }
2523
2524    pub fn observe_global<G: 'static>(
2525        &mut self,
2526        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2527    ) -> Subscription {
2528        let window_handle = self.window.handle;
2529        let view = self.view().downgrade();
2530        let (subscription, activate) = self.global_observers.insert(
2531            TypeId::of::<G>(),
2532            Box::new(move |cx| {
2533                window_handle
2534                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2535                    .unwrap_or(false)
2536            }),
2537        );
2538        self.app.defer(move |_| activate());
2539        subscription
2540    }
2541
2542    pub fn on_mouse_event<Event: 'static>(
2543        &mut self,
2544        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2545    ) {
2546        let handle = self.view().clone();
2547        self.window_cx.on_mouse_event(move |event, phase, cx| {
2548            handle.update(cx, |view, cx| {
2549                handler(view, event, phase, cx);
2550            })
2551        });
2552    }
2553
2554    pub fn on_key_event<Event: 'static>(
2555        &mut self,
2556        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2557    ) {
2558        let handle = self.view().clone();
2559        self.window_cx.on_key_event(move |event, phase, cx| {
2560            handle.update(cx, |view, cx| {
2561                handler(view, event, phase, cx);
2562            })
2563        });
2564    }
2565
2566    pub fn on_action(
2567        &mut self,
2568        action_type: TypeId,
2569        handler: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2570    ) {
2571        let handle = self.view().clone();
2572        self.window_cx
2573            .on_action(action_type, move |action, phase, cx| {
2574                handle.update(cx, |view, cx| {
2575                    handler(view, action, phase, cx);
2576                })
2577            });
2578    }
2579
2580    pub fn emit<Evt>(&mut self, event: Evt)
2581    where
2582        Evt: 'static,
2583        V: EventEmitter<Evt>,
2584    {
2585        let emitter = self.view.model.entity_id;
2586        self.app.push_effect(Effect::Emit {
2587            emitter,
2588            event_type: TypeId::of::<Evt>(),
2589            event: Box::new(event),
2590        });
2591    }
2592
2593    pub fn focus_self(&mut self)
2594    where
2595        V: FocusableView,
2596    {
2597        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2598    }
2599
2600    pub fn dismiss_self(&mut self)
2601    where
2602        V: ManagedView,
2603    {
2604        self.defer(|_, cx| cx.emit(DismissEvent))
2605    }
2606
2607    pub fn listener<E>(
2608        &self,
2609        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2610    ) -> impl Fn(&E, &mut WindowContext) + 'static {
2611        let view = self.view().downgrade();
2612        move |e: &E, cx: &mut WindowContext| {
2613            view.update(cx, |view, cx| f(view, e, cx)).ok();
2614        }
2615    }
2616}
2617
2618impl<V> Context for ViewContext<'_, V> {
2619    type Result<U> = U;
2620
2621    fn build_model<T: 'static>(
2622        &mut self,
2623        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2624    ) -> Model<T> {
2625        self.window_cx.build_model(build_model)
2626    }
2627
2628    fn update_model<T: 'static, R>(
2629        &mut self,
2630        model: &Model<T>,
2631        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2632    ) -> R {
2633        self.window_cx.update_model(model, update)
2634    }
2635
2636    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2637    where
2638        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2639    {
2640        self.window_cx.update_window(window, update)
2641    }
2642
2643    fn read_model<T, R>(
2644        &self,
2645        handle: &Model<T>,
2646        read: impl FnOnce(&T, &AppContext) -> R,
2647    ) -> Self::Result<R>
2648    where
2649        T: 'static,
2650    {
2651        self.window_cx.read_model(handle, read)
2652    }
2653
2654    fn read_window<T, R>(
2655        &self,
2656        window: &WindowHandle<T>,
2657        read: impl FnOnce(View<T>, &AppContext) -> R,
2658    ) -> Result<R>
2659    where
2660        T: 'static,
2661    {
2662        self.window_cx.read_window(window, read)
2663    }
2664}
2665
2666impl<V: 'static> VisualContext for ViewContext<'_, V> {
2667    fn build_view<W: Render + 'static>(
2668        &mut self,
2669        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2670    ) -> Self::Result<View<W>> {
2671        self.window_cx.build_view(build_view_state)
2672    }
2673
2674    fn update_view<V2: 'static, R>(
2675        &mut self,
2676        view: &View<V2>,
2677        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2678    ) -> Self::Result<R> {
2679        self.window_cx.update_view(view, update)
2680    }
2681
2682    fn replace_root_view<W>(
2683        &mut self,
2684        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2685    ) -> Self::Result<View<W>>
2686    where
2687        W: 'static + Render,
2688    {
2689        self.window_cx.replace_root_view(build_view)
2690    }
2691
2692    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2693        self.window_cx.focus_view(view)
2694    }
2695
2696    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2697        self.window_cx.dismiss_view(view)
2698    }
2699}
2700
2701impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2702    type Target = WindowContext<'a>;
2703
2704    fn deref(&self) -> &Self::Target {
2705        &self.window_cx
2706    }
2707}
2708
2709impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2710    fn deref_mut(&mut self) -> &mut Self::Target {
2711        &mut self.window_cx
2712    }
2713}
2714
2715// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2716slotmap::new_key_type! { pub struct WindowId; }
2717
2718impl WindowId {
2719    pub fn as_u64(&self) -> u64 {
2720        self.0.as_ffi()
2721    }
2722}
2723
2724#[derive(Deref, DerefMut)]
2725pub struct WindowHandle<V> {
2726    #[deref]
2727    #[deref_mut]
2728    pub(crate) any_handle: AnyWindowHandle,
2729    state_type: PhantomData<V>,
2730}
2731
2732impl<V: 'static + Render> WindowHandle<V> {
2733    pub fn new(id: WindowId) -> Self {
2734        WindowHandle {
2735            any_handle: AnyWindowHandle {
2736                id,
2737                state_type: TypeId::of::<V>(),
2738            },
2739            state_type: PhantomData,
2740        }
2741    }
2742
2743    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2744    where
2745        C: Context,
2746    {
2747        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2748            root_view
2749                .downcast::<V>()
2750                .map_err(|_| anyhow!("the type of the window's root view has changed"))
2751        }))
2752    }
2753
2754    pub fn update<C, R>(
2755        &self,
2756        cx: &mut C,
2757        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2758    ) -> Result<R>
2759    where
2760        C: Context,
2761    {
2762        cx.update_window(self.any_handle, |root_view, cx| {
2763            let view = root_view
2764                .downcast::<V>()
2765                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2766            Ok(cx.update_view(&view, update))
2767        })?
2768    }
2769
2770    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2771        let x = cx
2772            .windows
2773            .get(self.id)
2774            .and_then(|window| {
2775                window
2776                    .as_ref()
2777                    .and_then(|window| window.root_view.clone())
2778                    .map(|root_view| root_view.downcast::<V>())
2779            })
2780            .ok_or_else(|| anyhow!("window not found"))?
2781            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2782
2783        Ok(x.read(cx))
2784    }
2785
2786    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2787    where
2788        C: Context,
2789    {
2790        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2791    }
2792
2793    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2794    where
2795        C: Context,
2796    {
2797        cx.read_window(self, |root_view, _cx| root_view.clone())
2798    }
2799
2800    pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
2801        cx.windows
2802            .get(self.id)
2803            .and_then(|window| window.as_ref().map(|window| window.active))
2804    }
2805}
2806
2807impl<V> Copy for WindowHandle<V> {}
2808
2809impl<V> Clone for WindowHandle<V> {
2810    fn clone(&self) -> Self {
2811        WindowHandle {
2812            any_handle: self.any_handle,
2813            state_type: PhantomData,
2814        }
2815    }
2816}
2817
2818impl<V> PartialEq for WindowHandle<V> {
2819    fn eq(&self, other: &Self) -> bool {
2820        self.any_handle == other.any_handle
2821    }
2822}
2823
2824impl<V> Eq for WindowHandle<V> {}
2825
2826impl<V> Hash for WindowHandle<V> {
2827    fn hash<H: Hasher>(&self, state: &mut H) {
2828        self.any_handle.hash(state);
2829    }
2830}
2831
2832impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2833    fn into(self) -> AnyWindowHandle {
2834        self.any_handle
2835    }
2836}
2837
2838#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2839pub struct AnyWindowHandle {
2840    pub(crate) id: WindowId,
2841    state_type: TypeId,
2842}
2843
2844impl AnyWindowHandle {
2845    pub fn window_id(&self) -> WindowId {
2846        self.id
2847    }
2848
2849    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2850        if TypeId::of::<T>() == self.state_type {
2851            Some(WindowHandle {
2852                any_handle: *self,
2853                state_type: PhantomData,
2854            })
2855        } else {
2856            None
2857        }
2858    }
2859
2860    pub fn update<C, R>(
2861        self,
2862        cx: &mut C,
2863        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2864    ) -> Result<R>
2865    where
2866        C: Context,
2867    {
2868        cx.update_window(self, update)
2869    }
2870
2871    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2872    where
2873        C: Context,
2874        T: 'static,
2875    {
2876        let view = self
2877            .downcast::<T>()
2878            .context("the type of the window's root view has changed")?;
2879
2880        cx.read_window(&view, read)
2881    }
2882}
2883
2884#[cfg(any(test, feature = "test-support"))]
2885impl From<SmallVec<[u32; 16]>> for StackingOrder {
2886    fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2887        StackingOrder(small_vec)
2888    }
2889}
2890
2891#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2892pub enum ElementId {
2893    View(EntityId),
2894    Integer(usize),
2895    Name(SharedString),
2896    FocusHandle(FocusId),
2897    NamedInteger(SharedString, usize),
2898}
2899
2900impl ElementId {
2901    pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
2902        ElementId::View(entity_id)
2903    }
2904}
2905
2906impl TryInto<SharedString> for ElementId {
2907    type Error = anyhow::Error;
2908
2909    fn try_into(self) -> anyhow::Result<SharedString> {
2910        if let ElementId::Name(name) = self {
2911            Ok(name)
2912        } else {
2913            Err(anyhow!("element id is not string"))
2914        }
2915    }
2916}
2917
2918impl From<usize> for ElementId {
2919    fn from(id: usize) -> Self {
2920        ElementId::Integer(id)
2921    }
2922}
2923
2924impl From<i32> for ElementId {
2925    fn from(id: i32) -> Self {
2926        Self::Integer(id as usize)
2927    }
2928}
2929
2930impl From<SharedString> for ElementId {
2931    fn from(name: SharedString) -> Self {
2932        ElementId::Name(name)
2933    }
2934}
2935
2936impl From<&'static str> for ElementId {
2937    fn from(name: &'static str) -> Self {
2938        ElementId::Name(name.into())
2939    }
2940}
2941
2942impl<'a> From<&'a FocusHandle> for ElementId {
2943    fn from(handle: &'a FocusHandle) -> Self {
2944        ElementId::FocusHandle(handle.id)
2945    }
2946}
2947
2948impl From<(&'static str, EntityId)> for ElementId {
2949    fn from((name, id): (&'static str, EntityId)) -> Self {
2950        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
2951    }
2952}
2953
2954impl From<(&'static str, usize)> for ElementId {
2955    fn from((name, id): (&'static str, usize)) -> Self {
2956        ElementId::NamedInteger(name.into(), id)
2957    }
2958}
2959
2960impl From<(&'static str, u64)> for ElementId {
2961    fn from((name, id): (&'static str, u64)) -> Self {
2962        ElementId::NamedInteger(name.into(), id as usize)
2963    }
2964}