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.view_stack.pop();
2038                result
2039            }
2040        })
2041    }
2042
2043    /// Update or initialize state for an element with the given id that lives across multiple
2044    /// frames. If an element with this id existed in the rendered frame, its state will be passed
2045    /// to the given closure. The state returned by the closure will be stored so it can be referenced
2046    /// when drawing the next frame.
2047    pub(crate) fn with_element_state<S, R>(
2048        &mut self,
2049        id: ElementId,
2050        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2051    ) -> R
2052    where
2053        S: 'static,
2054    {
2055        self.with_element_id(Some(id), |cx| {
2056            let global_id = cx.window().element_id_stack.clone();
2057
2058            if let Some(any) = cx
2059                .window_mut()
2060                .next_frame
2061                .element_states
2062                .remove(&global_id)
2063                .or_else(|| {
2064                    cx.window_mut()
2065                        .rendered_frame
2066                        .element_states
2067                        .remove(&global_id)
2068                })
2069            {
2070                let ElementStateBox {
2071                    inner,
2072                    parent_view_id,
2073                    #[cfg(debug_assertions)]
2074                    type_name
2075                } = any;
2076                // Using the extra inner option to avoid needing to reallocate a new box.
2077                let mut state_box = inner
2078                    .downcast::<Option<S>>()
2079                    .map_err(|_| {
2080                        #[cfg(debug_assertions)]
2081                        {
2082                            anyhow!(
2083                                "invalid element state type for id, requested_type {:?}, actual type: {:?}",
2084                                std::any::type_name::<S>(),
2085                                type_name
2086                            )
2087                        }
2088
2089                        #[cfg(not(debug_assertions))]
2090                        {
2091                            anyhow!(
2092                                "invalid element state type for id, requested_type {:?}",
2093                                std::any::type_name::<S>(),
2094                            )
2095                        }
2096                    })
2097                    .unwrap();
2098
2099                // Actual: Option<AnyElement> <- View
2100                // Requested: () <- AnyElemet
2101                let state = state_box
2102                    .take()
2103                    .expect("element state is already on the stack");
2104                let (result, state) = f(Some(state), cx);
2105                state_box.replace(state);
2106                cx.window_mut()
2107                    .next_frame
2108                    .element_states
2109                    .insert(global_id, ElementStateBox {
2110                        inner: state_box,
2111                        parent_view_id,
2112                        #[cfg(debug_assertions)]
2113                        type_name
2114                    });
2115                result
2116            } else {
2117                let (result, state) = f(None, cx);
2118                let parent_view_id = cx.parent_view_id();
2119                cx.window_mut()
2120                    .next_frame
2121                    .element_states
2122                    .insert(global_id,
2123                        ElementStateBox {
2124                            inner: Box::new(Some(state)),
2125                            parent_view_id,
2126                            #[cfg(debug_assertions)]
2127                            type_name: std::any::type_name::<S>()
2128                        }
2129
2130                    );
2131                result
2132            }
2133        })
2134    }
2135
2136    fn parent_view_id(&self) -> EntityId {
2137        *self
2138            .window
2139            .next_frame
2140            .view_stack
2141            .last()
2142            .expect("a view should always be on the stack while drawing")
2143    }
2144
2145    /// Set an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
2146    /// platform to receive textual input with proper integration with concerns such
2147    /// as IME interactions.
2148    ///
2149    /// [element_input_handler]: crate::ElementInputHandler
2150    pub fn handle_input(
2151        &mut self,
2152        focus_handle: &FocusHandle,
2153        input_handler: impl PlatformInputHandler,
2154    ) {
2155        if focus_handle.is_focused(self) {
2156            let view_id = self.parent_view_id();
2157            self.window.next_frame.requested_input_handler = Some(RequestedInputHandler {
2158                view_id,
2159                handler: Some(Box::new(input_handler)),
2160            })
2161        }
2162    }
2163
2164    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
2165    /// If the callback returns false, the window won't be closed.
2166    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
2167        let mut this = self.to_async();
2168        self.window
2169            .platform_window
2170            .on_should_close(Box::new(move || {
2171                this.update(|_, cx| {
2172                    // Ensure that the window is removed from the app if it's been closed
2173                    // by always pre-empting the system close event.
2174                    if f(cx) {
2175                        cx.remove_window();
2176                    }
2177                    false
2178                })
2179                .unwrap_or(true)
2180            }))
2181    }
2182}
2183
2184impl Context for WindowContext<'_> {
2185    type Result<T> = T;
2186
2187    fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
2188    where
2189        T: 'static,
2190    {
2191        let slot = self.app.entities.reserve();
2192        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
2193        self.entities.insert(slot, model)
2194    }
2195
2196    fn update_model<T: 'static, R>(
2197        &mut self,
2198        model: &Model<T>,
2199        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2200    ) -> R {
2201        let mut entity = self.entities.lease(model);
2202        let result = update(
2203            &mut *entity,
2204            &mut ModelContext::new(&mut *self.app, model.downgrade()),
2205        );
2206        self.entities.end_lease(entity);
2207        result
2208    }
2209
2210    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2211    where
2212        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2213    {
2214        if window == self.window.handle {
2215            let root_view = self.window.root_view.clone().unwrap();
2216            Ok(update(root_view, self))
2217        } else {
2218            window.update(self.app, update)
2219        }
2220    }
2221
2222    fn read_model<T, R>(
2223        &self,
2224        handle: &Model<T>,
2225        read: impl FnOnce(&T, &AppContext) -> R,
2226    ) -> Self::Result<R>
2227    where
2228        T: 'static,
2229    {
2230        let entity = self.entities.read(handle);
2231        read(entity, &*self.app)
2232    }
2233
2234    fn read_window<T, R>(
2235        &self,
2236        window: &WindowHandle<T>,
2237        read: impl FnOnce(View<T>, &AppContext) -> R,
2238    ) -> Result<R>
2239    where
2240        T: 'static,
2241    {
2242        if window.any_handle == self.window.handle {
2243            let root_view = self
2244                .window
2245                .root_view
2246                .clone()
2247                .unwrap()
2248                .downcast::<T>()
2249                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2250            Ok(read(root_view, self))
2251        } else {
2252            self.app.read_window(window, read)
2253        }
2254    }
2255}
2256
2257impl VisualContext for WindowContext<'_> {
2258    fn new_view<V>(
2259        &mut self,
2260        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
2261    ) -> Self::Result<View<V>>
2262    where
2263        V: 'static + Render,
2264    {
2265        let slot = self.app.entities.reserve();
2266        let view = View {
2267            model: slot.clone(),
2268        };
2269        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
2270        let entity = build_view_state(&mut cx);
2271        cx.entities.insert(slot, entity);
2272
2273        cx.new_view_observers
2274            .clone()
2275            .retain(&TypeId::of::<V>(), |observer| {
2276                let any_view = AnyView::from(view.clone());
2277                (observer)(any_view, self);
2278                true
2279            });
2280
2281        view
2282    }
2283
2284    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
2285    fn update_view<T: 'static, R>(
2286        &mut self,
2287        view: &View<T>,
2288        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
2289    ) -> Self::Result<R> {
2290        let mut lease = self.app.entities.lease(&view.model);
2291        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
2292        let result = update(&mut *lease, &mut cx);
2293        cx.app.entities.end_lease(lease);
2294        result
2295    }
2296
2297    fn replace_root_view<V>(
2298        &mut self,
2299        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
2300    ) -> Self::Result<View<V>>
2301    where
2302        V: 'static + Render,
2303    {
2304        let view = self.new_view(build_view);
2305        self.window.root_view = Some(view.clone().into());
2306        self.refresh();
2307        view
2308    }
2309
2310    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
2311        self.update_view(view, |view, cx| {
2312            view.focus_handle(cx).clone().focus(cx);
2313        })
2314    }
2315
2316    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
2317    where
2318        V: ManagedView,
2319    {
2320        self.update_view(view, |_, cx| cx.emit(DismissEvent))
2321    }
2322}
2323
2324impl<'a> std::ops::Deref for WindowContext<'a> {
2325    type Target = AppContext;
2326
2327    fn deref(&self) -> &Self::Target {
2328        self.app
2329    }
2330}
2331
2332impl<'a> std::ops::DerefMut for WindowContext<'a> {
2333    fn deref_mut(&mut self) -> &mut Self::Target {
2334        self.app
2335    }
2336}
2337
2338impl<'a> Borrow<AppContext> for WindowContext<'a> {
2339    fn borrow(&self) -> &AppContext {
2340        self.app
2341    }
2342}
2343
2344impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
2345    fn borrow_mut(&mut self) -> &mut AppContext {
2346        self.app
2347    }
2348}
2349
2350/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
2351pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
2352    #[doc(hidden)]
2353    fn app_mut(&mut self) -> &mut AppContext {
2354        self.borrow_mut()
2355    }
2356
2357    #[doc(hidden)]
2358    fn app(&self) -> &AppContext {
2359        self.borrow()
2360    }
2361
2362    #[doc(hidden)]
2363    fn window(&self) -> &Window {
2364        self.borrow()
2365    }
2366
2367    #[doc(hidden)]
2368    fn window_mut(&mut self) -> &mut Window {
2369        self.borrow_mut()
2370    }
2371
2372    /// Pushes the given element id onto the global stack and invokes the given closure
2373    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
2374    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
2375    /// used to associate state with identified elements across separate frames.
2376    fn with_element_id<R>(
2377        &mut self,
2378        id: Option<impl Into<ElementId>>,
2379        f: impl FnOnce(&mut Self) -> R,
2380    ) -> R {
2381        if let Some(id) = id.map(Into::into) {
2382            let window = self.window_mut();
2383            window.element_id_stack.push(id);
2384            let result = f(self);
2385            let window: &mut Window = self.borrow_mut();
2386            window.element_id_stack.pop();
2387            result
2388        } else {
2389            f(self)
2390        }
2391    }
2392
2393    /// Invoke the given function with the given content mask after intersecting it
2394    /// with the current mask.
2395    fn with_content_mask<R>(
2396        &mut self,
2397        mask: Option<ContentMask<Pixels>>,
2398        f: impl FnOnce(&mut Self) -> R,
2399    ) -> R {
2400        if let Some(mask) = mask {
2401            let mask = mask.intersect(&self.content_mask());
2402            self.window_mut().next_frame.content_mask_stack.push(mask);
2403            let result = f(self);
2404            self.window_mut().next_frame.content_mask_stack.pop();
2405            result
2406        } else {
2407            f(self)
2408        }
2409    }
2410
2411    /// Invoke the given function with the content mask reset to that
2412    /// of the window.
2413    fn break_content_mask<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
2414        let mask = ContentMask {
2415            bounds: Bounds {
2416                origin: Point::default(),
2417                size: self.window().viewport_size,
2418            },
2419        };
2420        let new_stacking_order_id =
2421            post_inc(&mut self.window_mut().next_frame.next_stacking_order_id);
2422        let old_stacking_order = mem::take(&mut self.window_mut().next_frame.z_index_stack);
2423        self.window_mut().next_frame.z_index_stack.id = new_stacking_order_id;
2424        self.window_mut().next_frame.content_mask_stack.push(mask);
2425        let result = f(self);
2426        self.window_mut().next_frame.content_mask_stack.pop();
2427        self.window_mut().next_frame.z_index_stack = old_stacking_order;
2428        result
2429    }
2430
2431    /// Called during painting to invoke the given closure in a new stacking context. The given
2432    /// z-index is interpreted relative to the previous call to `stack`.
2433    fn with_z_index<R>(&mut self, z_index: u8, f: impl FnOnce(&mut Self) -> R) -> R {
2434        let new_stacking_order_id =
2435            post_inc(&mut self.window_mut().next_frame.next_stacking_order_id);
2436        let old_stacking_order_id = mem::replace(
2437            &mut self.window_mut().next_frame.z_index_stack.id,
2438            new_stacking_order_id,
2439        );
2440        self.window_mut().next_frame.z_index_stack.id = new_stacking_order_id;
2441        self.window_mut().next_frame.z_index_stack.push(z_index);
2442        let result = f(self);
2443        self.window_mut().next_frame.z_index_stack.id = old_stacking_order_id;
2444        self.window_mut().next_frame.z_index_stack.pop();
2445        result
2446    }
2447
2448    /// Update the global element offset relative to the current offset. This is used to implement
2449    /// scrolling.
2450    fn with_element_offset<R>(
2451        &mut self,
2452        offset: Point<Pixels>,
2453        f: impl FnOnce(&mut Self) -> R,
2454    ) -> R {
2455        if offset.is_zero() {
2456            return f(self);
2457        };
2458
2459        let abs_offset = self.element_offset() + offset;
2460        self.with_absolute_element_offset(abs_offset, f)
2461    }
2462
2463    /// Update the global element offset based on the given offset. This is used to implement
2464    /// drag handles and other manual painting of elements.
2465    fn with_absolute_element_offset<R>(
2466        &mut self,
2467        offset: Point<Pixels>,
2468        f: impl FnOnce(&mut Self) -> R,
2469    ) -> R {
2470        self.window_mut()
2471            .next_frame
2472            .element_offset_stack
2473            .push(offset);
2474        let result = f(self);
2475        self.window_mut().next_frame.element_offset_stack.pop();
2476        result
2477    }
2478
2479    /// Obtain the current element offset.
2480    fn element_offset(&self) -> Point<Pixels> {
2481        self.window()
2482            .next_frame
2483            .element_offset_stack
2484            .last()
2485            .copied()
2486            .unwrap_or_default()
2487    }
2488
2489    /// Obtain the current content mask.
2490    fn content_mask(&self) -> ContentMask<Pixels> {
2491        self.window()
2492            .next_frame
2493            .content_mask_stack
2494            .last()
2495            .cloned()
2496            .unwrap_or_else(|| ContentMask {
2497                bounds: Bounds {
2498                    origin: Point::default(),
2499                    size: self.window().viewport_size,
2500                },
2501            })
2502    }
2503
2504    /// The size of an em for the base font of the application. Adjusting this value allows the
2505    /// UI to scale, just like zooming a web page.
2506    fn rem_size(&self) -> Pixels {
2507        self.window().rem_size
2508    }
2509}
2510
2511impl Borrow<Window> for WindowContext<'_> {
2512    fn borrow(&self) -> &Window {
2513        self.window
2514    }
2515}
2516
2517impl BorrowMut<Window> for WindowContext<'_> {
2518    fn borrow_mut(&mut self) -> &mut Window {
2519        self.window
2520    }
2521}
2522
2523impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
2524
2525/// Provides access to application state that is specialized for a particular [`View`].
2526/// Allows you to interact with focus, emit events, etc.
2527/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
2528/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
2529pub struct ViewContext<'a, V> {
2530    window_cx: WindowContext<'a>,
2531    view: &'a View<V>,
2532}
2533
2534impl<V> Borrow<AppContext> for ViewContext<'_, V> {
2535    fn borrow(&self) -> &AppContext {
2536        &*self.window_cx.app
2537    }
2538}
2539
2540impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
2541    fn borrow_mut(&mut self) -> &mut AppContext {
2542        &mut *self.window_cx.app
2543    }
2544}
2545
2546impl<V> Borrow<Window> for ViewContext<'_, V> {
2547    fn borrow(&self) -> &Window {
2548        &*self.window_cx.window
2549    }
2550}
2551
2552impl<V> BorrowMut<Window> for ViewContext<'_, V> {
2553    fn borrow_mut(&mut self) -> &mut Window {
2554        &mut *self.window_cx.window
2555    }
2556}
2557
2558impl<'a, V: 'static> ViewContext<'a, V> {
2559    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
2560        Self {
2561            window_cx: WindowContext::new(app, window),
2562            view,
2563        }
2564    }
2565
2566    /// Get the entity_id of this view.
2567    pub fn entity_id(&self) -> EntityId {
2568        self.view.entity_id()
2569    }
2570
2571    /// Get the view pointer underlying this context.
2572    pub fn view(&self) -> &View<V> {
2573        self.view
2574    }
2575
2576    /// Get the model underlying this view.
2577    pub fn model(&self) -> &Model<V> {
2578        &self.view.model
2579    }
2580
2581    /// Access the underlying window context.
2582    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2583        &mut self.window_cx
2584    }
2585
2586    /// Set a given callback to be run on the next frame.
2587    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2588    where
2589        V: 'static,
2590    {
2591        let view = self.view().clone();
2592        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2593    }
2594
2595    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2596    /// that are currently on the stack to be returned to the app.
2597    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2598        let view = self.view().downgrade();
2599        self.window_cx.defer(move |cx| {
2600            view.update(cx, f).ok();
2601        });
2602    }
2603
2604    /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
2605    pub fn observe<V2, E>(
2606        &mut self,
2607        entity: &E,
2608        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2609    ) -> Subscription
2610    where
2611        V2: 'static,
2612        V: 'static,
2613        E: Entity<V2>,
2614    {
2615        let view = self.view().downgrade();
2616        let entity_id = entity.entity_id();
2617        let entity = entity.downgrade();
2618        let window_handle = self.window.handle;
2619        let (subscription, activate) = self.app.observers.insert(
2620            entity_id,
2621            Box::new(move |cx| {
2622                window_handle
2623                    .update(cx, |_, cx| {
2624                        if let Some(handle) = E::upgrade_from(&entity) {
2625                            view.update(cx, |this, cx| on_notify(this, handle, cx))
2626                                .is_ok()
2627                        } else {
2628                            false
2629                        }
2630                    })
2631                    .unwrap_or(false)
2632            }),
2633        );
2634        self.app.defer(move |_| activate());
2635        subscription
2636    }
2637
2638    /// Subscribe to events emitted by another model or view.
2639    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
2640    /// 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.
2641    pub fn subscribe<V2, E, Evt>(
2642        &mut self,
2643        entity: &E,
2644        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2645    ) -> Subscription
2646    where
2647        V2: EventEmitter<Evt>,
2648        E: Entity<V2>,
2649        Evt: 'static,
2650    {
2651        let view = self.view().downgrade();
2652        let entity_id = entity.entity_id();
2653        let handle = entity.downgrade();
2654        let window_handle = self.window.handle;
2655        let (subscription, activate) = self.app.event_listeners.insert(
2656            entity_id,
2657            (
2658                TypeId::of::<Evt>(),
2659                Box::new(move |event, cx| {
2660                    window_handle
2661                        .update(cx, |_, cx| {
2662                            if let Some(handle) = E::upgrade_from(&handle) {
2663                                let event = event.downcast_ref().expect("invalid event type");
2664                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
2665                                    .is_ok()
2666                            } else {
2667                                false
2668                            }
2669                        })
2670                        .unwrap_or(false)
2671                }),
2672            ),
2673        );
2674        self.app.defer(move |_| activate());
2675        subscription
2676    }
2677
2678    /// Register a callback to be invoked when the view is released.
2679    ///
2680    /// The callback receives a handle to the view's window. This handle may be
2681    /// invalid, if the window was closed before the view was released.
2682    pub fn on_release(
2683        &mut self,
2684        on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
2685    ) -> Subscription {
2686        let window_handle = self.window.handle;
2687        let (subscription, activate) = self.app.release_listeners.insert(
2688            self.view.model.entity_id,
2689            Box::new(move |this, cx| {
2690                let this = this.downcast_mut().expect("invalid entity type");
2691                on_release(this, window_handle, cx)
2692            }),
2693        );
2694        activate();
2695        subscription
2696    }
2697
2698    /// Register a callback to be invoked when the given Model or View is released.
2699    pub fn observe_release<V2, E>(
2700        &mut self,
2701        entity: &E,
2702        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2703    ) -> Subscription
2704    where
2705        V: 'static,
2706        V2: 'static,
2707        E: Entity<V2>,
2708    {
2709        let view = self.view().downgrade();
2710        let entity_id = entity.entity_id();
2711        let window_handle = self.window.handle;
2712        let (subscription, activate) = self.app.release_listeners.insert(
2713            entity_id,
2714            Box::new(move |entity, cx| {
2715                let entity = entity.downcast_mut().expect("invalid entity type");
2716                let _ = window_handle.update(cx, |_, cx| {
2717                    view.update(cx, |this, cx| on_release(this, entity, cx))
2718                });
2719            }),
2720        );
2721        activate();
2722        subscription
2723    }
2724
2725    /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
2726    /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
2727    pub fn notify(&mut self) {
2728        for view_id in self
2729            .window
2730            .rendered_frame
2731            .dispatch_tree
2732            .view_path(self.view.entity_id())
2733        {
2734            if !self.window.dirty_views.insert(view_id) {
2735                break;
2736            }
2737        }
2738
2739        if !self.window.drawing {
2740            self.window_cx.window.dirty = true;
2741            self.window_cx.app.push_effect(Effect::Notify {
2742                emitter: self.view.model.entity_id,
2743            });
2744        }
2745    }
2746
2747    /// Register a callback to be invoked when the window is resized.
2748    pub fn observe_window_bounds(
2749        &mut self,
2750        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2751    ) -> Subscription {
2752        let view = self.view.downgrade();
2753        let (subscription, activate) = self.window.bounds_observers.insert(
2754            (),
2755            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2756        );
2757        activate();
2758        subscription
2759    }
2760
2761    /// Register a callback to be invoked when the window is activated or deactivated.
2762    pub fn observe_window_activation(
2763        &mut self,
2764        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2765    ) -> Subscription {
2766        let view = self.view.downgrade();
2767        let (subscription, activate) = self.window.activation_observers.insert(
2768            (),
2769            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2770        );
2771        activate();
2772        subscription
2773    }
2774
2775    /// Register a listener to be called when the given focus handle receives focus.
2776    /// Returns a subscription and persists until the subscription is dropped.
2777    pub fn on_focus(
2778        &mut self,
2779        handle: &FocusHandle,
2780        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2781    ) -> Subscription {
2782        let view = self.view.downgrade();
2783        let focus_id = handle.id;
2784        let (subscription, activate) = self.window.focus_listeners.insert(
2785            (),
2786            Box::new(move |event, cx| {
2787                view.update(cx, |view, cx| {
2788                    if event.previous_focus_path.last() != Some(&focus_id)
2789                        && event.current_focus_path.last() == Some(&focus_id)
2790                    {
2791                        listener(view, cx)
2792                    }
2793                })
2794                .is_ok()
2795            }),
2796        );
2797        self.app.defer(move |_| activate());
2798        subscription
2799    }
2800
2801    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2802    /// Returns a subscription and persists until the subscription is dropped.
2803    pub fn on_focus_in(
2804        &mut self,
2805        handle: &FocusHandle,
2806        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2807    ) -> Subscription {
2808        let view = self.view.downgrade();
2809        let focus_id = handle.id;
2810        let (subscription, activate) = self.window.focus_listeners.insert(
2811            (),
2812            Box::new(move |event, cx| {
2813                view.update(cx, |view, cx| {
2814                    if !event.previous_focus_path.contains(&focus_id)
2815                        && event.current_focus_path.contains(&focus_id)
2816                    {
2817                        listener(view, cx)
2818                    }
2819                })
2820                .is_ok()
2821            }),
2822        );
2823        self.app.defer(move |_| activate());
2824        subscription
2825    }
2826
2827    /// Register a listener to be called when the given focus handle loses focus.
2828    /// Returns a subscription and persists until the subscription is dropped.
2829    pub fn on_blur(
2830        &mut self,
2831        handle: &FocusHandle,
2832        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2833    ) -> Subscription {
2834        let view = self.view.downgrade();
2835        let focus_id = handle.id;
2836        let (subscription, activate) = self.window.focus_listeners.insert(
2837            (),
2838            Box::new(move |event, cx| {
2839                view.update(cx, |view, cx| {
2840                    if event.previous_focus_path.last() == Some(&focus_id)
2841                        && event.current_focus_path.last() != Some(&focus_id)
2842                    {
2843                        listener(view, cx)
2844                    }
2845                })
2846                .is_ok()
2847            }),
2848        );
2849        self.app.defer(move |_| activate());
2850        subscription
2851    }
2852
2853    /// Register a listener to be called when nothing in the window has focus.
2854    /// This typically happens when the node that was focused is removed from the tree,
2855    /// and this callback lets you chose a default place to restore the users focus.
2856    /// Returns a subscription and persists until the subscription is dropped.
2857    pub fn on_focus_lost(
2858        &mut self,
2859        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2860    ) -> Subscription {
2861        let view = self.view.downgrade();
2862        let (subscription, activate) = self.window.focus_lost_listeners.insert(
2863            (),
2864            Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2865        );
2866        activate();
2867        subscription
2868    }
2869
2870    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2871    /// Returns a subscription and persists until the subscription is dropped.
2872    pub fn on_focus_out(
2873        &mut self,
2874        handle: &FocusHandle,
2875        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2876    ) -> Subscription {
2877        let view = self.view.downgrade();
2878        let focus_id = handle.id;
2879        let (subscription, activate) = self.window.focus_listeners.insert(
2880            (),
2881            Box::new(move |event, cx| {
2882                view.update(cx, |view, cx| {
2883                    if event.previous_focus_path.contains(&focus_id)
2884                        && !event.current_focus_path.contains(&focus_id)
2885                    {
2886                        listener(view, cx)
2887                    }
2888                })
2889                .is_ok()
2890            }),
2891        );
2892        self.app.defer(move |_| activate());
2893        subscription
2894    }
2895
2896    /// Schedule a future to be run asynchronously.
2897    /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
2898    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
2899    /// The returned future will be polled on the main thread.
2900    pub fn spawn<Fut, R>(
2901        &mut self,
2902        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2903    ) -> Task<R>
2904    where
2905        R: 'static,
2906        Fut: Future<Output = R> + 'static,
2907    {
2908        let view = self.view().downgrade();
2909        self.window_cx.spawn(|cx| f(view, cx))
2910    }
2911
2912    /// Update the global state of the given type.
2913    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2914    where
2915        G: 'static,
2916    {
2917        let mut global = self.app.lease_global::<G>();
2918        let result = f(&mut global, self);
2919        self.app.end_global_lease(global);
2920        result
2921    }
2922
2923    /// Register a callback to be invoked when the given global state changes.
2924    pub fn observe_global<G: 'static>(
2925        &mut self,
2926        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2927    ) -> Subscription {
2928        let window_handle = self.window.handle;
2929        let view = self.view().downgrade();
2930        let (subscription, activate) = self.global_observers.insert(
2931            TypeId::of::<G>(),
2932            Box::new(move |cx| {
2933                window_handle
2934                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2935                    .unwrap_or(false)
2936            }),
2937        );
2938        self.app.defer(move |_| activate());
2939        subscription
2940    }
2941
2942    /// Add a listener for any mouse event that occurs in the window.
2943    /// This is a fairly low level method.
2944    /// Typically, you'll want to use methods on UI elements, which perform bounds checking etc.
2945    pub fn on_mouse_event<Event: 'static>(
2946        &mut self,
2947        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2948    ) {
2949        let handle = self.view().clone();
2950        self.window_cx.on_mouse_event(move |event, phase, cx| {
2951            handle.update(cx, |view, cx| {
2952                handler(view, event, phase, cx);
2953            })
2954        });
2955    }
2956
2957    /// Register a callback to be invoked when the given Key Event is dispatched to the window.
2958    pub fn on_key_event<Event: 'static>(
2959        &mut self,
2960        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2961    ) {
2962        let handle = self.view().clone();
2963        self.window_cx.on_key_event(move |event, phase, cx| {
2964            handle.update(cx, |view, cx| {
2965                handler(view, event, phase, cx);
2966            })
2967        });
2968    }
2969
2970    /// Register a callback to be invoked when the given Action type is dispatched to the window.
2971    pub fn on_action(
2972        &mut self,
2973        action_type: TypeId,
2974        listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2975    ) {
2976        let handle = self.view().clone();
2977        self.window_cx
2978            .on_action(action_type, move |action, phase, cx| {
2979                handle.update(cx, |view, cx| {
2980                    listener(view, action, phase, cx);
2981                })
2982            });
2983    }
2984
2985    /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
2986    pub fn emit<Evt>(&mut self, event: Evt)
2987    where
2988        Evt: 'static,
2989        V: EventEmitter<Evt>,
2990    {
2991        let emitter = self.view.model.entity_id;
2992        self.app.push_effect(Effect::Emit {
2993            emitter,
2994            event_type: TypeId::of::<Evt>(),
2995            event: Box::new(event),
2996        });
2997    }
2998
2999    /// Move focus to the current view, assuming it implements [`FocusableView`].
3000    pub fn focus_self(&mut self)
3001    where
3002        V: FocusableView,
3003    {
3004        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
3005    }
3006
3007    /// Convenience method for accessing view state in an event callback.
3008    ///
3009    /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
3010    /// but it's often useful to be able to access view state in these
3011    /// callbacks. This method provides a convenient way to do so.
3012    pub fn listener<E>(
3013        &self,
3014        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
3015    ) -> impl Fn(&E, &mut WindowContext) + 'static {
3016        let view = self.view().downgrade();
3017        move |e: &E, cx: &mut WindowContext| {
3018            view.update(cx, |view, cx| f(view, e, cx)).ok();
3019        }
3020    }
3021}
3022
3023impl<V> Context for ViewContext<'_, V> {
3024    type Result<U> = U;
3025
3026    fn new_model<T: 'static>(
3027        &mut self,
3028        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
3029    ) -> Model<T> {
3030        self.window_cx.new_model(build_model)
3031    }
3032
3033    fn update_model<T: 'static, R>(
3034        &mut self,
3035        model: &Model<T>,
3036        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
3037    ) -> R {
3038        self.window_cx.update_model(model, update)
3039    }
3040
3041    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
3042    where
3043        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
3044    {
3045        self.window_cx.update_window(window, update)
3046    }
3047
3048    fn read_model<T, R>(
3049        &self,
3050        handle: &Model<T>,
3051        read: impl FnOnce(&T, &AppContext) -> R,
3052    ) -> Self::Result<R>
3053    where
3054        T: 'static,
3055    {
3056        self.window_cx.read_model(handle, read)
3057    }
3058
3059    fn read_window<T, R>(
3060        &self,
3061        window: &WindowHandle<T>,
3062        read: impl FnOnce(View<T>, &AppContext) -> R,
3063    ) -> Result<R>
3064    where
3065        T: 'static,
3066    {
3067        self.window_cx.read_window(window, read)
3068    }
3069}
3070
3071impl<V: 'static> VisualContext for ViewContext<'_, V> {
3072    fn new_view<W: Render + 'static>(
3073        &mut self,
3074        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
3075    ) -> Self::Result<View<W>> {
3076        self.window_cx.new_view(build_view_state)
3077    }
3078
3079    fn update_view<V2: 'static, R>(
3080        &mut self,
3081        view: &View<V2>,
3082        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
3083    ) -> Self::Result<R> {
3084        self.window_cx.update_view(view, update)
3085    }
3086
3087    fn replace_root_view<W>(
3088        &mut self,
3089        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
3090    ) -> Self::Result<View<W>>
3091    where
3092        W: 'static + Render,
3093    {
3094        self.window_cx.replace_root_view(build_view)
3095    }
3096
3097    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
3098        self.window_cx.focus_view(view)
3099    }
3100
3101    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
3102        self.window_cx.dismiss_view(view)
3103    }
3104}
3105
3106impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
3107    type Target = WindowContext<'a>;
3108
3109    fn deref(&self) -> &Self::Target {
3110        &self.window_cx
3111    }
3112}
3113
3114impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
3115    fn deref_mut(&mut self) -> &mut Self::Target {
3116        &mut self.window_cx
3117    }
3118}
3119
3120// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
3121slotmap::new_key_type! {
3122    /// A unique identifier for a window.
3123    pub struct WindowId;
3124}
3125
3126impl WindowId {
3127    /// Converts this window ID to a `u64`.
3128    pub fn as_u64(&self) -> u64 {
3129        self.0.as_ffi()
3130    }
3131}
3132
3133/// A handle to a window with a specific root view type.
3134/// Note that this does not keep the window alive on its own.
3135#[derive(Deref, DerefMut)]
3136pub struct WindowHandle<V> {
3137    #[deref]
3138    #[deref_mut]
3139    pub(crate) any_handle: AnyWindowHandle,
3140    state_type: PhantomData<V>,
3141}
3142
3143impl<V: 'static + Render> WindowHandle<V> {
3144    /// Create a new handle from a window ID.
3145    /// This does not check if the root type of the window is `V`.
3146    pub fn new(id: WindowId) -> Self {
3147        WindowHandle {
3148            any_handle: AnyWindowHandle {
3149                id,
3150                state_type: TypeId::of::<V>(),
3151            },
3152            state_type: PhantomData,
3153        }
3154    }
3155
3156    /// Get the root view out of this window.
3157    ///
3158    /// This will fail if the window is closed or if the root view's type does not match `V`.
3159    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
3160    where
3161        C: Context,
3162    {
3163        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
3164            root_view
3165                .downcast::<V>()
3166                .map_err(|_| anyhow!("the type of the window's root view has changed"))
3167        }))
3168    }
3169
3170    /// Update the root view of this window.
3171    ///
3172    /// This will fail if the window has been closed or if the root view's type does not match
3173    pub fn update<C, R>(
3174        &self,
3175        cx: &mut C,
3176        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
3177    ) -> Result<R>
3178    where
3179        C: Context,
3180    {
3181        cx.update_window(self.any_handle, |root_view, cx| {
3182            let view = root_view
3183                .downcast::<V>()
3184                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3185            Ok(cx.update_view(&view, update))
3186        })?
3187    }
3188
3189    /// Read the root view out of this window.
3190    ///
3191    /// This will fail if the window is closed or if the root view's type does not match `V`.
3192    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
3193        let x = cx
3194            .windows
3195            .get(self.id)
3196            .and_then(|window| {
3197                window
3198                    .as_ref()
3199                    .and_then(|window| window.root_view.clone())
3200                    .map(|root_view| root_view.downcast::<V>())
3201            })
3202            .ok_or_else(|| anyhow!("window not found"))?
3203            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3204
3205        Ok(x.read(cx))
3206    }
3207
3208    /// Read the root view out of this window, with a callback
3209    ///
3210    /// This will fail if the window is closed or if the root view's type does not match `V`.
3211    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
3212    where
3213        C: Context,
3214    {
3215        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
3216    }
3217
3218    /// Read the root view pointer off of this window.
3219    ///
3220    /// This will fail if the window is closed or if the root view's type does not match `V`.
3221    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
3222    where
3223        C: Context,
3224    {
3225        cx.read_window(self, |root_view, _cx| root_view.clone())
3226    }
3227
3228    /// Check if this window is 'active'.
3229    ///
3230    /// Will return `None` if the window is closed.
3231    pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
3232        cx.windows
3233            .get(self.id)
3234            .and_then(|window| window.as_ref().map(|window| window.active))
3235    }
3236}
3237
3238impl<V> Copy for WindowHandle<V> {}
3239
3240impl<V> Clone for WindowHandle<V> {
3241    fn clone(&self) -> Self {
3242        *self
3243    }
3244}
3245
3246impl<V> PartialEq for WindowHandle<V> {
3247    fn eq(&self, other: &Self) -> bool {
3248        self.any_handle == other.any_handle
3249    }
3250}
3251
3252impl<V> Eq for WindowHandle<V> {}
3253
3254impl<V> Hash for WindowHandle<V> {
3255    fn hash<H: Hasher>(&self, state: &mut H) {
3256        self.any_handle.hash(state);
3257    }
3258}
3259
3260impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
3261    fn from(val: WindowHandle<V>) -> Self {
3262        val.any_handle
3263    }
3264}
3265
3266/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
3267#[derive(Copy, Clone, PartialEq, Eq, Hash)]
3268pub struct AnyWindowHandle {
3269    pub(crate) id: WindowId,
3270    state_type: TypeId,
3271}
3272
3273impl AnyWindowHandle {
3274    /// Get the ID of this window.
3275    pub fn window_id(&self) -> WindowId {
3276        self.id
3277    }
3278
3279    /// Attempt to convert this handle to a window handle with a specific root view type.
3280    /// If the types do not match, this will return `None`.
3281    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
3282        if TypeId::of::<T>() == self.state_type {
3283            Some(WindowHandle {
3284                any_handle: *self,
3285                state_type: PhantomData,
3286            })
3287        } else {
3288            None
3289        }
3290    }
3291
3292    /// Update the state of the root view of this window.
3293    ///
3294    /// This will fail if the window has been closed.
3295    pub fn update<C, R>(
3296        self,
3297        cx: &mut C,
3298        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
3299    ) -> Result<R>
3300    where
3301        C: Context,
3302    {
3303        cx.update_window(self, update)
3304    }
3305
3306    /// Read the state of the root view of this window.
3307    ///
3308    /// This will fail if the window has been closed.
3309    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
3310    where
3311        C: Context,
3312        T: 'static,
3313    {
3314        let view = self
3315            .downcast::<T>()
3316            .context("the type of the window's root view has changed")?;
3317
3318        cx.read_window(&view, read)
3319    }
3320}
3321
3322/// An identifier for an [`Element`](crate::Element).
3323///
3324/// Can be constructed with a string, a number, or both, as well
3325/// as other internal representations.
3326#[derive(Clone, Debug, Eq, PartialEq, Hash)]
3327pub enum ElementId {
3328    /// The ID of a View element
3329    View(EntityId),
3330    /// An integer ID.
3331    Integer(usize),
3332    /// A string based ID.
3333    Name(SharedString),
3334    /// An ID that's equated with a focus handle.
3335    FocusHandle(FocusId),
3336    /// A combination of a name and an integer.
3337    NamedInteger(SharedString, usize),
3338}
3339
3340impl ElementId {
3341    pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
3342        ElementId::View(entity_id)
3343    }
3344}
3345
3346impl TryInto<SharedString> for ElementId {
3347    type Error = anyhow::Error;
3348
3349    fn try_into(self) -> anyhow::Result<SharedString> {
3350        if let ElementId::Name(name) = self {
3351            Ok(name)
3352        } else {
3353            Err(anyhow!("element id is not string"))
3354        }
3355    }
3356}
3357
3358impl From<usize> for ElementId {
3359    fn from(id: usize) -> Self {
3360        ElementId::Integer(id)
3361    }
3362}
3363
3364impl From<i32> for ElementId {
3365    fn from(id: i32) -> Self {
3366        Self::Integer(id as usize)
3367    }
3368}
3369
3370impl From<SharedString> for ElementId {
3371    fn from(name: SharedString) -> Self {
3372        ElementId::Name(name)
3373    }
3374}
3375
3376impl From<&'static str> for ElementId {
3377    fn from(name: &'static str) -> Self {
3378        ElementId::Name(name.into())
3379    }
3380}
3381
3382impl<'a> From<&'a FocusHandle> for ElementId {
3383    fn from(handle: &'a FocusHandle) -> Self {
3384        ElementId::FocusHandle(handle.id)
3385    }
3386}
3387
3388impl From<(&'static str, EntityId)> for ElementId {
3389    fn from((name, id): (&'static str, EntityId)) -> Self {
3390        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
3391    }
3392}
3393
3394impl From<(&'static str, usize)> for ElementId {
3395    fn from((name, id): (&'static str, usize)) -> Self {
3396        ElementId::NamedInteger(name.into(), id)
3397    }
3398}
3399
3400impl From<(&'static str, u64)> for ElementId {
3401    fn from((name, id): (&'static str, u64)) -> Self {
3402        ElementId::NamedInteger(name.into(), id as usize)
3403    }
3404}
3405
3406/// A rectangle to be rendered in the window at the given position and size.
3407/// Passed as an argument [`WindowContext::paint_quad`].
3408#[derive(Clone)]
3409pub struct PaintQuad {
3410    bounds: Bounds<Pixels>,
3411    corner_radii: Corners<Pixels>,
3412    background: Hsla,
3413    border_widths: Edges<Pixels>,
3414    border_color: Hsla,
3415}
3416
3417impl PaintQuad {
3418    /// Set the corner radii of the quad.
3419    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
3420        PaintQuad {
3421            corner_radii: corner_radii.into(),
3422            ..self
3423        }
3424    }
3425
3426    /// Set the border widths of the quad.
3427    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
3428        PaintQuad {
3429            border_widths: border_widths.into(),
3430            ..self
3431        }
3432    }
3433
3434    /// Set the border color of the quad.
3435    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
3436        PaintQuad {
3437            border_color: border_color.into(),
3438            ..self
3439        }
3440    }
3441
3442    /// Set the background color of the quad.
3443    pub fn background(self, background: impl Into<Hsla>) -> Self {
3444        PaintQuad {
3445            background: background.into(),
3446            ..self
3447        }
3448    }
3449}
3450
3451/// Create a quad with the given parameters.
3452pub fn quad(
3453    bounds: Bounds<Pixels>,
3454    corner_radii: impl Into<Corners<Pixels>>,
3455    background: impl Into<Hsla>,
3456    border_widths: impl Into<Edges<Pixels>>,
3457    border_color: impl Into<Hsla>,
3458) -> PaintQuad {
3459    PaintQuad {
3460        bounds,
3461        corner_radii: corner_radii.into(),
3462        background: background.into(),
3463        border_widths: border_widths.into(),
3464        border_color: border_color.into(),
3465    }
3466}
3467
3468/// Create a filled quad with the given bounds and background color.
3469pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
3470    PaintQuad {
3471        bounds: bounds.into(),
3472        corner_radii: (0.).into(),
3473        background: background.into(),
3474        border_widths: (0.).into(),
3475        border_color: transparent_black(),
3476    }
3477}
3478
3479/// Create a rectangle outline with the given bounds, border color, and a 1px border width
3480pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
3481    PaintQuad {
3482        bounds: bounds.into(),
3483        corner_radii: (0.).into(),
3484        background: transparent_black(),
3485        border_widths: (1.).into(),
3486        border_color: border_color.into(),
3487    }
3488}