window.rs

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