window.rs

   1use crate::{
   2    hash, point, prelude::*, px, size, transparent_black, Action, AnyDrag, AnyElement, AnyTooltip,
   3    AnyView, AppContext, Arena, Asset, AsyncWindowContext, AvailableSpace, Bounds, BoxShadow,
   4    Context, Corners, CursorStyle, DevicePixels, DispatchActionListener, DispatchNodeId,
   5    DispatchTree, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter, FileDropEvent, Flatten,
   6    FontId, Global, GlobalElementId, GlyphId, Hsla, ImageData, InputHandler, IsZero, KeyBinding,
   7    KeyContext, KeyDownEvent, KeyEvent, KeyMatch, KeymatchResult, Keystroke, KeystrokeEvent,
   8    LayoutId, LineLayoutIndex, Model, ModelContext, Modifiers, ModifiersChangedEvent,
   9    MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels,
  10    PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point,
  11    PolychromeSprite, PromptLevel, Quad, Render, RenderGlyphParams, RenderImageParams,
  12    RenderSvgParams, ScaledPixels, Scene, Shadow, SharedString, Size, StrikethroughStyle, Style,
  13    SubscriberSet, Subscription, TaffyLayoutEngine, Task, TextStyle, TextStyleRefinement,
  14    TransformationMatrix, Underline, UnderlineStyle, View, VisualContext, WeakView,
  15    WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowOptions, WindowParams,
  16    WindowTextSystem, SUBPIXEL_VARIANTS,
  17};
  18use anyhow::{anyhow, Context as _, Result};
  19use collections::{FxHashMap, FxHashSet};
  20use derive_more::{Deref, DerefMut};
  21use futures::channel::oneshot;
  22use futures::{future::Shared, FutureExt};
  23#[cfg(target_os = "macos")]
  24use media::core_video::CVImageBuffer;
  25use parking_lot::RwLock;
  26use refineable::Refineable;
  27use slotmap::SlotMap;
  28use smallvec::SmallVec;
  29use std::{
  30    any::{Any, TypeId},
  31    borrow::{Borrow, BorrowMut, Cow},
  32    cell::{Cell, RefCell},
  33    cmp,
  34    fmt::{Debug, Display},
  35    future::Future,
  36    hash::{Hash, Hasher},
  37    marker::PhantomData,
  38    mem,
  39    ops::Range,
  40    rc::Rc,
  41    sync::{
  42        atomic::{AtomicUsize, Ordering::SeqCst},
  43        Arc, Weak,
  44    },
  45    time::{Duration, Instant},
  46};
  47use util::post_inc;
  48use util::{measure, ResultExt};
  49use uuid::Uuid;
  50
  51mod prompts;
  52
  53pub use prompts::*;
  54
  55pub(crate) const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1024.), px(700.));
  56
  57/// Represents the two different phases when dispatching events.
  58#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
  59pub enum DispatchPhase {
  60    /// After the capture phase comes the bubble phase, in which mouse event listeners are
  61    /// invoked front to back and keyboard event listeners are invoked from the focused element
  62    /// to the root of the element tree. This is the phase you'll most commonly want to use when
  63    /// registering event listeners.
  64    #[default]
  65    Bubble,
  66    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
  67    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
  68    /// is used for special purposes such as clearing the "pressed" state for click events. If
  69    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
  70    /// outside of the immediate region may rely on detecting non-local events during this phase.
  71    Capture,
  72}
  73
  74impl DispatchPhase {
  75    /// Returns true if this represents the "bubble" phase.
  76    pub fn bubble(self) -> bool {
  77        self == DispatchPhase::Bubble
  78    }
  79
  80    /// Returns true if this represents the "capture" phase.
  81    pub fn capture(self) -> bool {
  82        self == DispatchPhase::Capture
  83    }
  84}
  85
  86type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
  87
  88type AnyWindowFocusListener =
  89    Box<dyn FnMut(&WindowFocusEvent, &mut WindowContext) -> bool + 'static>;
  90
  91struct WindowFocusEvent {
  92    previous_focus_path: SmallVec<[FocusId; 8]>,
  93    current_focus_path: SmallVec<[FocusId; 8]>,
  94}
  95
  96/// This is provided when subscribing for `ViewContext::on_focus_out` events.
  97pub struct FocusOutEvent {
  98    /// A weak focus handle representing what was blurred.
  99    pub blurred: WeakFocusHandle,
 100}
 101
 102slotmap::new_key_type! {
 103    /// A globally unique identifier for a focusable element.
 104    pub struct FocusId;
 105}
 106
 107thread_local! {
 108    /// 8MB wasn't quite enough...
 109    pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(32 * 1024 * 1024));
 110}
 111
 112impl FocusId {
 113    /// Obtains whether the element associated with this handle is currently focused.
 114    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 115        cx.window.focus == Some(*self)
 116    }
 117
 118    /// Obtains whether the element associated with this handle contains the focused
 119    /// element or is itself focused.
 120    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
 121        cx.focused()
 122            .map_or(false, |focused| self.contains(focused.id, cx))
 123    }
 124
 125    /// Obtains whether the element associated with this handle is contained within the
 126    /// focused element or is itself focused.
 127    pub fn within_focused(&self, cx: &WindowContext) -> bool {
 128        let focused = cx.focused();
 129        focused.map_or(false, |focused| focused.id.contains(*self, cx))
 130    }
 131
 132    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 133    pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
 134        cx.window
 135            .rendered_frame
 136            .dispatch_tree
 137            .focus_contains(*self, other)
 138    }
 139}
 140
 141/// A handle which can be used to track and manipulate the focused element in a window.
 142pub struct FocusHandle {
 143    pub(crate) id: FocusId,
 144    handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 145}
 146
 147impl std::fmt::Debug for FocusHandle {
 148    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 149        f.write_fmt(format_args!("FocusHandle({:?})", self.id))
 150    }
 151}
 152
 153impl FocusHandle {
 154    pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
 155        let id = handles.write().insert(AtomicUsize::new(1));
 156        Self {
 157            id,
 158            handles: handles.clone(),
 159        }
 160    }
 161
 162    pub(crate) fn for_id(
 163        id: FocusId,
 164        handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 165    ) -> Option<Self> {
 166        let lock = handles.read();
 167        let ref_count = lock.get(id)?;
 168        if ref_count.load(SeqCst) == 0 {
 169            None
 170        } else {
 171            ref_count.fetch_add(1, SeqCst);
 172            Some(Self {
 173                id,
 174                handles: handles.clone(),
 175            })
 176        }
 177    }
 178
 179    /// Converts this focus handle into a weak variant, which does not prevent it from being released.
 180    pub fn downgrade(&self) -> WeakFocusHandle {
 181        WeakFocusHandle {
 182            id: self.id,
 183            handles: Arc::downgrade(&self.handles),
 184        }
 185    }
 186
 187    /// Moves the focus to the element associated with this handle.
 188    pub fn focus(&self, cx: &mut WindowContext) {
 189        cx.focus(self)
 190    }
 191
 192    /// Obtains whether the element associated with this handle is currently focused.
 193    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 194        self.id.is_focused(cx)
 195    }
 196
 197    /// Obtains whether the element associated with this handle contains the focused
 198    /// element or is itself focused.
 199    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
 200        self.id.contains_focused(cx)
 201    }
 202
 203    /// Obtains whether the element associated with this handle is contained within the
 204    /// focused element or is itself focused.
 205    pub fn within_focused(&self, cx: &WindowContext) -> bool {
 206        self.id.within_focused(cx)
 207    }
 208
 209    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 210    pub fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
 211        self.id.contains(other.id, cx)
 212    }
 213
 214    /// Dispatch an action on the element that rendered this focus handle
 215    pub fn dispatch_action(&self, action: &dyn Action, cx: &mut WindowContext) {
 216        if let Some(node_id) = cx
 217            .window
 218            .rendered_frame
 219            .dispatch_tree
 220            .focusable_node_id(self.id)
 221        {
 222            cx.dispatch_action_on_node(node_id, action)
 223        }
 224    }
 225}
 226
 227impl Clone for FocusHandle {
 228    fn clone(&self) -> Self {
 229        Self::for_id(self.id, &self.handles).unwrap()
 230    }
 231}
 232
 233impl PartialEq for FocusHandle {
 234    fn eq(&self, other: &Self) -> bool {
 235        self.id == other.id
 236    }
 237}
 238
 239impl Eq for FocusHandle {}
 240
 241impl Drop for FocusHandle {
 242    fn drop(&mut self) {
 243        self.handles
 244            .read()
 245            .get(self.id)
 246            .unwrap()
 247            .fetch_sub(1, SeqCst);
 248    }
 249}
 250
 251/// A weak reference to a focus handle.
 252#[derive(Clone, Debug)]
 253pub struct WeakFocusHandle {
 254    pub(crate) id: FocusId,
 255    handles: Weak<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 256}
 257
 258impl WeakFocusHandle {
 259    /// Attempts to upgrade the [WeakFocusHandle] to a [FocusHandle].
 260    pub fn upgrade(&self) -> Option<FocusHandle> {
 261        let handles = self.handles.upgrade()?;
 262        FocusHandle::for_id(self.id, &handles)
 263    }
 264}
 265
 266impl PartialEq for WeakFocusHandle {
 267    fn eq(&self, other: &WeakFocusHandle) -> bool {
 268        self.id == other.id
 269    }
 270}
 271
 272impl Eq for WeakFocusHandle {}
 273
 274impl PartialEq<FocusHandle> for WeakFocusHandle {
 275    fn eq(&self, other: &FocusHandle) -> bool {
 276        self.id == other.id
 277    }
 278}
 279
 280impl PartialEq<WeakFocusHandle> for FocusHandle {
 281    fn eq(&self, other: &WeakFocusHandle) -> bool {
 282        self.id == other.id
 283    }
 284}
 285
 286/// FocusableView allows users of your view to easily
 287/// focus it (using cx.focus_view(view))
 288pub trait FocusableView: 'static + Render {
 289    /// Returns the focus handle associated with this view.
 290    fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
 291}
 292
 293/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
 294/// where the lifecycle of the view is handled by another view.
 295pub trait ManagedView: FocusableView + EventEmitter<DismissEvent> {}
 296
 297impl<M: FocusableView + EventEmitter<DismissEvent>> ManagedView for M {}
 298
 299/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
 300pub struct DismissEvent;
 301
 302type FrameCallback = Box<dyn FnOnce(&mut WindowContext)>;
 303
 304pub(crate) type AnyMouseListener =
 305    Box<dyn FnMut(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
 306
 307#[derive(Clone)]
 308pub(crate) struct CursorStyleRequest {
 309    pub(crate) hitbox_id: HitboxId,
 310    pub(crate) style: CursorStyle,
 311}
 312
 313/// An identifier for a [Hitbox].
 314#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
 315pub struct HitboxId(usize);
 316
 317impl HitboxId {
 318    /// Checks if the hitbox with this id is currently hovered.
 319    pub fn is_hovered(&self, cx: &WindowContext) -> bool {
 320        cx.window.mouse_hit_test.0.contains(self)
 321    }
 322}
 323
 324/// A rectangular region that potentially blocks hitboxes inserted prior.
 325/// See [WindowContext::insert_hitbox] for more details.
 326#[derive(Clone, Debug, Deref)]
 327pub struct Hitbox {
 328    /// A unique identifier for the hitbox.
 329    pub id: HitboxId,
 330    /// The bounds of the hitbox.
 331    #[deref]
 332    pub bounds: Bounds<Pixels>,
 333    /// The content mask when the hitbox was inserted.
 334    pub content_mask: ContentMask<Pixels>,
 335    /// Whether the hitbox occludes other hitboxes inserted prior.
 336    pub opaque: bool,
 337}
 338
 339impl Hitbox {
 340    /// Checks if the hitbox is currently hovered.
 341    pub fn is_hovered(&self, cx: &WindowContext) -> bool {
 342        self.id.is_hovered(cx)
 343    }
 344}
 345
 346#[derive(Default, Eq, PartialEq)]
 347pub(crate) struct HitTest(SmallVec<[HitboxId; 8]>);
 348
 349/// An identifier for a tooltip.
 350#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
 351pub struct TooltipId(usize);
 352
 353impl TooltipId {
 354    /// Checks if the tooltip is currently hovered.
 355    pub fn is_hovered(&self, cx: &WindowContext) -> bool {
 356        cx.window
 357            .tooltip_bounds
 358            .as_ref()
 359            .map_or(false, |tooltip_bounds| {
 360                tooltip_bounds.id == *self && tooltip_bounds.bounds.contains(&cx.mouse_position())
 361            })
 362    }
 363}
 364
 365pub(crate) struct TooltipBounds {
 366    id: TooltipId,
 367    bounds: Bounds<Pixels>,
 368}
 369
 370#[derive(Clone)]
 371pub(crate) struct TooltipRequest {
 372    id: TooltipId,
 373    tooltip: AnyTooltip,
 374}
 375
 376pub(crate) struct DeferredDraw {
 377    priority: usize,
 378    parent_node: DispatchNodeId,
 379    element_id_stack: SmallVec<[ElementId; 32]>,
 380    text_style_stack: Vec<TextStyleRefinement>,
 381    element: Option<AnyElement>,
 382    absolute_offset: Point<Pixels>,
 383    prepaint_range: Range<PrepaintStateIndex>,
 384    paint_range: Range<PaintIndex>,
 385}
 386
 387pub(crate) struct Frame {
 388    pub(crate) focus: Option<FocusId>,
 389    pub(crate) window_active: bool,
 390    pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
 391    accessed_element_states: Vec<(GlobalElementId, TypeId)>,
 392    pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
 393    pub(crate) dispatch_tree: DispatchTree,
 394    pub(crate) scene: Scene,
 395    pub(crate) hitboxes: Vec<Hitbox>,
 396    pub(crate) deferred_draws: Vec<DeferredDraw>,
 397    pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
 398    pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
 399    pub(crate) cursor_styles: Vec<CursorStyleRequest>,
 400    #[cfg(any(test, feature = "test-support"))]
 401    pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
 402}
 403
 404#[derive(Clone, Default)]
 405pub(crate) struct PrepaintStateIndex {
 406    hitboxes_index: usize,
 407    tooltips_index: usize,
 408    deferred_draws_index: usize,
 409    dispatch_tree_index: usize,
 410    accessed_element_states_index: usize,
 411    line_layout_index: LineLayoutIndex,
 412}
 413
 414#[derive(Clone, Default)]
 415pub(crate) struct PaintIndex {
 416    scene_index: usize,
 417    mouse_listeners_index: usize,
 418    input_handlers_index: usize,
 419    cursor_styles_index: usize,
 420    accessed_element_states_index: usize,
 421    line_layout_index: LineLayoutIndex,
 422}
 423
 424impl Frame {
 425    pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
 426        Frame {
 427            focus: None,
 428            window_active: false,
 429            element_states: FxHashMap::default(),
 430            accessed_element_states: Vec::new(),
 431            mouse_listeners: Vec::new(),
 432            dispatch_tree,
 433            scene: Scene::default(),
 434            hitboxes: Vec::new(),
 435            deferred_draws: Vec::new(),
 436            input_handlers: Vec::new(),
 437            tooltip_requests: Vec::new(),
 438            cursor_styles: Vec::new(),
 439
 440            #[cfg(any(test, feature = "test-support"))]
 441            debug_bounds: FxHashMap::default(),
 442        }
 443    }
 444
 445    pub(crate) fn clear(&mut self) {
 446        self.element_states.clear();
 447        self.accessed_element_states.clear();
 448        self.mouse_listeners.clear();
 449        self.dispatch_tree.clear();
 450        self.scene.clear();
 451        self.input_handlers.clear();
 452        self.tooltip_requests.clear();
 453        self.cursor_styles.clear();
 454        self.hitboxes.clear();
 455        self.deferred_draws.clear();
 456    }
 457
 458    pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
 459        let mut hit_test = HitTest::default();
 460        for hitbox in self.hitboxes.iter().rev() {
 461            let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
 462            if bounds.contains(&position) {
 463                hit_test.0.push(hitbox.id);
 464                if hitbox.opaque {
 465                    break;
 466                }
 467            }
 468        }
 469        hit_test
 470    }
 471
 472    pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
 473        self.focus
 474            .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
 475            .unwrap_or_default()
 476    }
 477
 478    pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
 479        for element_state_key in &self.accessed_element_states {
 480            if let Some((element_state_key, element_state)) =
 481                prev_frame.element_states.remove_entry(element_state_key)
 482            {
 483                self.element_states.insert(element_state_key, element_state);
 484            }
 485        }
 486
 487        self.scene.finish();
 488    }
 489}
 490
 491// Holds the state for a specific window.
 492#[doc(hidden)]
 493pub struct Window {
 494    pub(crate) handle: AnyWindowHandle,
 495    pub(crate) removed: bool,
 496    pub(crate) platform_window: Box<dyn PlatformWindow>,
 497    display_id: Option<DisplayId>,
 498    sprite_atlas: Arc<dyn PlatformAtlas>,
 499    text_system: Arc<WindowTextSystem>,
 500    rem_size: Pixels,
 501    /// The stack of override values for the window's rem size.
 502    ///
 503    /// This is used by `with_rem_size` to allow rendering an element tree with
 504    /// a given rem size.
 505    rem_size_override_stack: SmallVec<[Pixels; 8]>,
 506    pub(crate) viewport_size: Size<Pixels>,
 507    layout_engine: Option<TaffyLayoutEngine>,
 508    pub(crate) root_view: Option<AnyView>,
 509    pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
 510    pub(crate) text_style_stack: Vec<TextStyleRefinement>,
 511    pub(crate) element_offset_stack: Vec<Point<Pixels>>,
 512    pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
 513    pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
 514    pub(crate) rendered_frame: Frame,
 515    pub(crate) next_frame: Frame,
 516    pub(crate) next_hitbox_id: HitboxId,
 517    pub(crate) next_tooltip_id: TooltipId,
 518    pub(crate) tooltip_bounds: Option<TooltipBounds>,
 519    next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
 520    pub(crate) dirty_views: FxHashSet<EntityId>,
 521    pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 522    focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
 523    focus_lost_listeners: SubscriberSet<(), AnyObserver>,
 524    default_prevented: bool,
 525    mouse_position: Point<Pixels>,
 526    mouse_hit_test: HitTest,
 527    modifiers: Modifiers,
 528    scale_factor: f32,
 529    bounds_observers: SubscriberSet<(), AnyObserver>,
 530    appearance: WindowAppearance,
 531    appearance_observers: SubscriberSet<(), AnyObserver>,
 532    active: Rc<Cell<bool>>,
 533    pub(crate) dirty: Rc<Cell<bool>>,
 534    pub(crate) needs_present: Rc<Cell<bool>>,
 535    pub(crate) last_input_timestamp: Rc<Cell<Instant>>,
 536    pub(crate) refreshing: bool,
 537    pub(crate) draw_phase: DrawPhase,
 538    activation_observers: SubscriberSet<(), AnyObserver>,
 539    pub(crate) focus: Option<FocusId>,
 540    focus_enabled: bool,
 541    pending_input: Option<PendingInput>,
 542    pending_input_observers: SubscriberSet<(), AnyObserver>,
 543    prompt: Option<RenderablePromptHandle>,
 544}
 545
 546#[derive(Clone, Copy, Debug, Eq, PartialEq)]
 547pub(crate) enum DrawPhase {
 548    None,
 549    Prepaint,
 550    Paint,
 551    Focus,
 552}
 553
 554#[derive(Default, Debug)]
 555struct PendingInput {
 556    keystrokes: SmallVec<[Keystroke; 1]>,
 557    bindings: SmallVec<[KeyBinding; 1]>,
 558    focus: Option<FocusId>,
 559    timer: Option<Task<()>>,
 560}
 561
 562impl PendingInput {
 563    fn input(&self) -> String {
 564        self.keystrokes
 565            .iter()
 566            .flat_map(|k| k.ime_key.clone())
 567            .collect::<Vec<String>>()
 568            .join("")
 569    }
 570
 571    fn used_by_binding(&self, binding: &KeyBinding) -> bool {
 572        if self.keystrokes.is_empty() {
 573            return true;
 574        }
 575        let keystroke = &self.keystrokes[0];
 576        for candidate in keystroke.match_candidates() {
 577            if binding.match_keystrokes(&[candidate]) == KeyMatch::Pending {
 578                return true;
 579            }
 580        }
 581        false
 582    }
 583}
 584
 585pub(crate) struct ElementStateBox {
 586    pub(crate) inner: Box<dyn Any>,
 587    #[cfg(debug_assertions)]
 588    pub(crate) type_name: &'static str,
 589}
 590
 591fn default_bounds(display_id: Option<DisplayId>, cx: &mut AppContext) -> Bounds<Pixels> {
 592    const DEFAULT_WINDOW_OFFSET: Point<Pixels> = point(px(0.), px(35.));
 593
 594    cx.active_window()
 595        .and_then(|w| w.update(cx, |_, cx| cx.bounds()).ok())
 596        .map(|bounds| bounds.map_origin(|origin| origin + DEFAULT_WINDOW_OFFSET))
 597        .unwrap_or_else(|| {
 598            let display = display_id
 599                .map(|id| cx.find_display(id))
 600                .unwrap_or_else(|| cx.primary_display());
 601
 602            display
 603                .map(|display| display.default_bounds())
 604                .unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE))
 605        })
 606}
 607
 608impl Window {
 609    pub(crate) fn new(
 610        handle: AnyWindowHandle,
 611        options: WindowOptions,
 612        cx: &mut AppContext,
 613    ) -> Result<Self> {
 614        let WindowOptions {
 615            window_bounds,
 616            titlebar,
 617            focus,
 618            show,
 619            kind,
 620            is_movable,
 621            display_id,
 622            window_background,
 623            app_id,
 624        } = options;
 625
 626        let bounds = window_bounds
 627            .map(|bounds| bounds.get_bounds())
 628            .unwrap_or_else(|| default_bounds(display_id, cx));
 629        let mut platform_window = cx.platform.open_window(
 630            handle,
 631            WindowParams {
 632                bounds,
 633                titlebar,
 634                kind,
 635                is_movable,
 636                focus,
 637                show,
 638                display_id,
 639                window_background,
 640            },
 641        )?;
 642        let display_id = platform_window.display().map(|display| display.id());
 643        let sprite_atlas = platform_window.sprite_atlas();
 644        let mouse_position = platform_window.mouse_position();
 645        let modifiers = platform_window.modifiers();
 646        let content_size = platform_window.content_size();
 647        let scale_factor = platform_window.scale_factor();
 648        let appearance = platform_window.appearance();
 649        let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
 650        let dirty = Rc::new(Cell::new(true));
 651        let active = Rc::new(Cell::new(platform_window.is_active()));
 652        let needs_present = Rc::new(Cell::new(false));
 653        let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
 654        let last_input_timestamp = Rc::new(Cell::new(Instant::now()));
 655
 656        if let Some(ref window_open_state) = window_bounds {
 657            match window_open_state {
 658                WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
 659                WindowBounds::Maximized(_) => platform_window.zoom(),
 660                WindowBounds::Windowed(_) => {}
 661            }
 662        }
 663
 664        platform_window.on_close(Box::new({
 665            let mut cx = cx.to_async();
 666            move || {
 667                let _ = handle.update(&mut cx, |_, cx| cx.remove_window());
 668            }
 669        }));
 670        platform_window.on_request_frame(Box::new({
 671            let mut cx = cx.to_async();
 672            let dirty = dirty.clone();
 673            let active = active.clone();
 674            let needs_present = needs_present.clone();
 675            let next_frame_callbacks = next_frame_callbacks.clone();
 676            let last_input_timestamp = last_input_timestamp.clone();
 677            move || {
 678                let next_frame_callbacks = next_frame_callbacks.take();
 679                if !next_frame_callbacks.is_empty() {
 680                    handle
 681                        .update(&mut cx, |_, cx| {
 682                            for callback in next_frame_callbacks {
 683                                callback(cx);
 684                            }
 685                        })
 686                        .log_err();
 687                }
 688
 689                // Keep presenting the current scene for 1 extra second since the
 690                // last input to prevent the display from underclocking the refresh rate.
 691                let needs_present = needs_present.get()
 692                    || (active.get()
 693                        && last_input_timestamp.get().elapsed() < Duration::from_secs(1));
 694
 695                if dirty.get() {
 696                    measure("frame duration", || {
 697                        handle
 698                            .update(&mut cx, |_, cx| {
 699                                cx.draw();
 700                                cx.present();
 701                            })
 702                            .log_err();
 703                    })
 704                } else if needs_present {
 705                    handle.update(&mut cx, |_, cx| cx.present()).log_err();
 706                }
 707
 708                handle
 709                    .update(&mut cx, |_, cx| {
 710                        cx.complete_frame();
 711                    })
 712                    .log_err();
 713            }
 714        }));
 715        platform_window.on_resize(Box::new({
 716            let mut cx = cx.to_async();
 717            move |_, _| {
 718                handle
 719                    .update(&mut cx, |_, cx| cx.bounds_changed())
 720                    .log_err();
 721            }
 722        }));
 723        platform_window.on_moved(Box::new({
 724            let mut cx = cx.to_async();
 725            move || {
 726                handle
 727                    .update(&mut cx, |_, cx| cx.bounds_changed())
 728                    .log_err();
 729            }
 730        }));
 731        platform_window.on_appearance_changed(Box::new({
 732            let mut cx = cx.to_async();
 733            move || {
 734                handle
 735                    .update(&mut cx, |_, cx| cx.appearance_changed())
 736                    .log_err();
 737            }
 738        }));
 739        platform_window.on_active_status_change(Box::new({
 740            let mut cx = cx.to_async();
 741            move |active| {
 742                handle
 743                    .update(&mut cx, |_, cx| {
 744                        cx.window.active.set(active);
 745                        cx.window
 746                            .activation_observers
 747                            .clone()
 748                            .retain(&(), |callback| callback(cx));
 749                        cx.refresh();
 750                    })
 751                    .log_err();
 752            }
 753        }));
 754
 755        platform_window.on_input({
 756            let mut cx = cx.to_async();
 757            Box::new(move |event| {
 758                handle
 759                    .update(&mut cx, |_, cx| cx.dispatch_event(event))
 760                    .log_err()
 761                    .unwrap_or(DispatchEventResult::default())
 762            })
 763        });
 764
 765        if let Some(app_id) = app_id {
 766            platform_window.set_app_id(&app_id);
 767        }
 768
 769        Ok(Window {
 770            handle,
 771            removed: false,
 772            platform_window,
 773            display_id,
 774            sprite_atlas,
 775            text_system,
 776            rem_size: px(16.),
 777            rem_size_override_stack: SmallVec::new(),
 778            viewport_size: content_size,
 779            layout_engine: Some(TaffyLayoutEngine::new()),
 780            root_view: None,
 781            element_id_stack: SmallVec::default(),
 782            text_style_stack: Vec::new(),
 783            element_offset_stack: Vec::new(),
 784            content_mask_stack: Vec::new(),
 785            requested_autoscroll: None,
 786            rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 787            next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 788            next_frame_callbacks,
 789            next_hitbox_id: HitboxId::default(),
 790            next_tooltip_id: TooltipId::default(),
 791            tooltip_bounds: None,
 792            dirty_views: FxHashSet::default(),
 793            focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
 794            focus_listeners: SubscriberSet::new(),
 795            focus_lost_listeners: SubscriberSet::new(),
 796            default_prevented: true,
 797            mouse_position,
 798            mouse_hit_test: HitTest::default(),
 799            modifiers,
 800            scale_factor,
 801            bounds_observers: SubscriberSet::new(),
 802            appearance,
 803            appearance_observers: SubscriberSet::new(),
 804            active,
 805            dirty,
 806            needs_present,
 807            last_input_timestamp,
 808            refreshing: false,
 809            draw_phase: DrawPhase::None,
 810            activation_observers: SubscriberSet::new(),
 811            focus: None,
 812            focus_enabled: true,
 813            pending_input: None,
 814            pending_input_observers: SubscriberSet::new(),
 815            prompt: None,
 816        })
 817    }
 818    fn new_focus_listener(
 819        &mut self,
 820        value: AnyWindowFocusListener,
 821    ) -> (Subscription, impl FnOnce()) {
 822        self.focus_listeners.insert((), value)
 823    }
 824}
 825
 826#[derive(Clone, Debug, Default, PartialEq, Eq)]
 827pub(crate) struct DispatchEventResult {
 828    pub propagate: bool,
 829    pub default_prevented: bool,
 830}
 831
 832/// Indicates which region of the window is visible. Content falling outside of this mask will not be
 833/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
 834/// to leave room to support more complex shapes in the future.
 835#[derive(Clone, Debug, Default, PartialEq, Eq)]
 836#[repr(C)]
 837pub struct ContentMask<P: Clone + Default + Debug> {
 838    /// The bounds
 839    pub bounds: Bounds<P>,
 840}
 841
 842impl ContentMask<Pixels> {
 843    /// Scale the content mask's pixel units by the given scaling factor.
 844    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
 845        ContentMask {
 846            bounds: self.bounds.scale(factor),
 847        }
 848    }
 849
 850    /// Intersect the content mask with the given content mask.
 851    pub fn intersect(&self, other: &Self) -> Self {
 852        let bounds = self.bounds.intersect(&other.bounds);
 853        ContentMask { bounds }
 854    }
 855}
 856
 857/// Provides access to application state in the context of a single window. Derefs
 858/// to an [`AppContext`], so you can also pass a [`WindowContext`] to any method that takes
 859/// an [`AppContext`] and call any [`AppContext`] methods.
 860pub struct WindowContext<'a> {
 861    pub(crate) app: &'a mut AppContext,
 862    pub(crate) window: &'a mut Window,
 863}
 864
 865impl<'a> WindowContext<'a> {
 866    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
 867        Self { app, window }
 868    }
 869
 870    /// Obtain a handle to the window that belongs to this context.
 871    pub fn window_handle(&self) -> AnyWindowHandle {
 872        self.window.handle
 873    }
 874
 875    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
 876    pub fn refresh(&mut self) {
 877        if self.window.draw_phase == DrawPhase::None {
 878            self.window.refreshing = true;
 879            self.window.dirty.set(true);
 880        }
 881    }
 882
 883    /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
 884    /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
 885    pub fn notify(&mut self, view_id: EntityId) {
 886        for view_id in self
 887            .window
 888            .rendered_frame
 889            .dispatch_tree
 890            .view_path(view_id)
 891            .into_iter()
 892            .rev()
 893        {
 894            if !self.window.dirty_views.insert(view_id) {
 895                break;
 896            }
 897        }
 898
 899        if self.window.draw_phase == DrawPhase::None {
 900            self.window.dirty.set(true);
 901            self.app.push_effect(Effect::Notify { emitter: view_id });
 902        }
 903    }
 904
 905    /// Close this window.
 906    pub fn remove_window(&mut self) {
 907        self.window.removed = true;
 908    }
 909
 910    /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
 911    /// for elements rendered within this window.
 912    pub fn focus_handle(&mut self) -> FocusHandle {
 913        FocusHandle::new(&self.window.focus_handles)
 914    }
 915
 916    /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
 917    pub fn focused(&self) -> Option<FocusHandle> {
 918        self.window
 919            .focus
 920            .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
 921    }
 922
 923    /// Move focus to the element associated with the given [`FocusHandle`].
 924    pub fn focus(&mut self, handle: &FocusHandle) {
 925        if !self.window.focus_enabled || self.window.focus == Some(handle.id) {
 926            return;
 927        }
 928
 929        self.window.focus = Some(handle.id);
 930        self.window
 931            .rendered_frame
 932            .dispatch_tree
 933            .clear_pending_keystrokes();
 934        self.refresh();
 935    }
 936
 937    /// Remove focus from all elements within this context's window.
 938    pub fn blur(&mut self) {
 939        if !self.window.focus_enabled {
 940            return;
 941        }
 942
 943        self.window.focus = None;
 944        self.refresh();
 945    }
 946
 947    /// Blur the window and don't allow anything in it to be focused again.
 948    pub fn disable_focus(&mut self) {
 949        self.blur();
 950        self.window.focus_enabled = false;
 951    }
 952
 953    /// Accessor for the text system.
 954    pub fn text_system(&self) -> &Arc<WindowTextSystem> {
 955        &self.window.text_system
 956    }
 957
 958    /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
 959    pub fn text_style(&self) -> TextStyle {
 960        let mut style = TextStyle::default();
 961        for refinement in &self.window.text_style_stack {
 962            style.refine(refinement);
 963        }
 964        style
 965    }
 966
 967    /// Check if the platform window is maximized
 968    /// On some platforms (namely Windows) this is different than the bounds being the size of the display
 969    pub fn is_maximized(&self) -> bool {
 970        self.window.platform_window.is_maximized()
 971    }
 972
 973    /// Return the `WindowBounds` to indicate that how a window should be opened
 974    /// after it has been closed
 975    pub fn window_bounds(&self) -> WindowBounds {
 976        self.window.platform_window.window_bounds()
 977    }
 978
 979    /// Dispatch the given action on the currently focused element.
 980    pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
 981        let focus_handle = self.focused();
 982
 983        let window = self.window.handle;
 984        self.app.defer(move |cx| {
 985            window
 986                .update(cx, |_, cx| {
 987                    let node_id = focus_handle
 988                        .and_then(|handle| {
 989                            cx.window
 990                                .rendered_frame
 991                                .dispatch_tree
 992                                .focusable_node_id(handle.id)
 993                        })
 994                        .unwrap_or_else(|| cx.window.rendered_frame.dispatch_tree.root_node_id());
 995
 996                    cx.dispatch_action_on_node(node_id, action.as_ref());
 997                })
 998                .log_err();
 999        })
1000    }
1001
1002    pub(crate) fn dispatch_keystroke_observers(
1003        &mut self,
1004        event: &dyn Any,
1005        action: Option<Box<dyn Action>>,
1006    ) {
1007        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1008            return;
1009        };
1010
1011        self.keystroke_observers
1012            .clone()
1013            .retain(&(), move |callback| {
1014                (callback)(
1015                    &KeystrokeEvent {
1016                        keystroke: key_down_event.keystroke.clone(),
1017                        action: action.as_ref().map(|action| action.boxed_clone()),
1018                    },
1019                    self,
1020                );
1021                true
1022            });
1023    }
1024
1025    pub(crate) fn clear_pending_keystrokes(&mut self) {
1026        self.window
1027            .rendered_frame
1028            .dispatch_tree
1029            .clear_pending_keystrokes();
1030        self.window
1031            .next_frame
1032            .dispatch_tree
1033            .clear_pending_keystrokes();
1034    }
1035
1036    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1037    /// that are currently on the stack to be returned to the app.
1038    pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
1039        let handle = self.window.handle;
1040        self.app.defer(move |cx| {
1041            handle.update(cx, |_, cx| f(cx)).ok();
1042        });
1043    }
1044
1045    /// Subscribe to events emitted by a model or view.
1046    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1047    /// 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.
1048    pub fn observe<E, T>(
1049        &mut self,
1050        entity: &E,
1051        mut on_notify: impl FnMut(E, &mut WindowContext<'_>) + 'static,
1052    ) -> Subscription
1053    where
1054        E: Entity<T>,
1055    {
1056        let entity_id = entity.entity_id();
1057        let entity = entity.downgrade();
1058        let window_handle = self.window.handle;
1059        self.app.new_observer(
1060            entity_id,
1061            Box::new(move |cx| {
1062                window_handle
1063                    .update(cx, |_, cx| {
1064                        if let Some(handle) = E::upgrade_from(&entity) {
1065                            on_notify(handle, cx);
1066                            true
1067                        } else {
1068                            false
1069                        }
1070                    })
1071                    .unwrap_or(false)
1072            }),
1073        )
1074    }
1075
1076    /// Subscribe to events emitted by a model or view.
1077    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1078    /// 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.
1079    pub fn subscribe<Emitter, E, Evt>(
1080        &mut self,
1081        entity: &E,
1082        mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
1083    ) -> Subscription
1084    where
1085        Emitter: EventEmitter<Evt>,
1086        E: Entity<Emitter>,
1087        Evt: 'static,
1088    {
1089        let entity_id = entity.entity_id();
1090        let entity = entity.downgrade();
1091        let window_handle = self.window.handle;
1092        self.app.new_subscription(
1093            entity_id,
1094            (
1095                TypeId::of::<Evt>(),
1096                Box::new(move |event, cx| {
1097                    window_handle
1098                        .update(cx, |_, cx| {
1099                            if let Some(handle) = E::upgrade_from(&entity) {
1100                                let event = event.downcast_ref().expect("invalid event type");
1101                                on_event(handle, event, cx);
1102                                true
1103                            } else {
1104                                false
1105                            }
1106                        })
1107                        .unwrap_or(false)
1108                }),
1109            ),
1110        )
1111    }
1112
1113    /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
1114    /// await points in async code.
1115    pub fn to_async(&self) -> AsyncWindowContext {
1116        AsyncWindowContext::new(self.app.to_async(), self.window.handle)
1117    }
1118
1119    /// Schedule the given closure to be run directly after the current frame is rendered.
1120    pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
1121        RefCell::borrow_mut(&self.window.next_frame_callbacks).push(Box::new(callback));
1122    }
1123
1124    /// Spawn the future returned by the given closure on the application thread pool.
1125    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
1126    /// use within your future.
1127    pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
1128    where
1129        R: 'static,
1130        Fut: Future<Output = R> + 'static,
1131    {
1132        self.app
1133            .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
1134    }
1135
1136    fn bounds_changed(&mut self) {
1137        self.window.scale_factor = self.window.platform_window.scale_factor();
1138        self.window.viewport_size = self.window.platform_window.content_size();
1139        self.window.display_id = self
1140            .window
1141            .platform_window
1142            .display()
1143            .map(|display| display.id());
1144
1145        self.refresh();
1146
1147        self.window
1148            .bounds_observers
1149            .clone()
1150            .retain(&(), |callback| callback(self));
1151    }
1152
1153    /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
1154    pub fn bounds(&self) -> Bounds<Pixels> {
1155        self.window.platform_window.bounds()
1156    }
1157
1158    /// Returns whether or not the window is currently fullscreen
1159    pub fn is_fullscreen(&self) -> bool {
1160        self.window.platform_window.is_fullscreen()
1161    }
1162
1163    pub(crate) fn appearance_changed(&mut self) {
1164        self.window.appearance = self.window.platform_window.appearance();
1165
1166        self.window
1167            .appearance_observers
1168            .clone()
1169            .retain(&(), |callback| callback(self));
1170    }
1171
1172    /// Returns the appearance of the current window.
1173    pub fn appearance(&self) -> WindowAppearance {
1174        self.window.appearance
1175    }
1176
1177    /// Returns the size of the drawable area within the window.
1178    pub fn viewport_size(&self) -> Size<Pixels> {
1179        self.window.viewport_size
1180    }
1181
1182    /// Returns whether this window is focused by the operating system (receiving key events).
1183    pub fn is_window_active(&self) -> bool {
1184        self.window.active.get()
1185    }
1186
1187    /// Toggle zoom on the window.
1188    pub fn zoom_window(&self) {
1189        self.window.platform_window.zoom();
1190    }
1191
1192    /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
1193    pub fn show_window_menu(&self, position: Point<Pixels>) {
1194        self.window.platform_window.show_window_menu(position)
1195    }
1196
1197    /// Tells the compositor to take control of window movement (Wayland and X11)
1198    ///
1199    /// Events may not be received during a move operation.
1200    pub fn start_system_move(&self) {
1201        self.window.platform_window.start_system_move()
1202    }
1203
1204    /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
1205    pub fn should_render_window_controls(&self) -> bool {
1206        self.window.platform_window.should_render_window_controls()
1207    }
1208
1209    /// Updates the window's title at the platform level.
1210    pub fn set_window_title(&mut self, title: &str) {
1211        self.window.platform_window.set_title(title);
1212    }
1213
1214    /// Sets the application identifier.
1215    pub fn set_app_id(&mut self, app_id: &str) {
1216        self.window.platform_window.set_app_id(app_id);
1217    }
1218
1219    /// Sets the window background appearance.
1220    pub fn set_background_appearance(&mut self, background_appearance: WindowBackgroundAppearance) {
1221        self.window
1222            .platform_window
1223            .set_background_appearance(background_appearance);
1224    }
1225
1226    /// Mark the window as dirty at the platform level.
1227    pub fn set_window_edited(&mut self, edited: bool) {
1228        self.window.platform_window.set_edited(edited);
1229    }
1230
1231    /// Determine the display on which the window is visible.
1232    pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1233        self.platform
1234            .displays()
1235            .into_iter()
1236            .find(|display| Some(display.id()) == self.window.display_id)
1237    }
1238
1239    /// Show the platform character palette.
1240    pub fn show_character_palette(&self) {
1241        self.window.platform_window.show_character_palette();
1242    }
1243
1244    /// The scale factor of the display associated with the window. For example, it could
1245    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
1246    /// be rendered as two pixels on screen.
1247    pub fn scale_factor(&self) -> f32 {
1248        self.window.scale_factor
1249    }
1250
1251    /// The size of an em for the base font of the application. Adjusting this value allows the
1252    /// UI to scale, just like zooming a web page.
1253    pub fn rem_size(&self) -> Pixels {
1254        self.window
1255            .rem_size_override_stack
1256            .last()
1257            .copied()
1258            .unwrap_or(self.window.rem_size)
1259    }
1260
1261    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
1262    /// UI to scale, just like zooming a web page.
1263    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
1264        self.window.rem_size = rem_size.into();
1265    }
1266
1267    /// Executes the provided function with the specified rem size.
1268    ///
1269    /// This method must only be called as part of element drawing.
1270    pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
1271    where
1272        F: FnOnce(&mut Self) -> R,
1273    {
1274        debug_assert!(
1275            matches!(
1276                self.window.draw_phase,
1277                DrawPhase::Prepaint | DrawPhase::Paint
1278            ),
1279            "this method can only be called during request_layout, prepaint, or paint"
1280        );
1281
1282        if let Some(rem_size) = rem_size {
1283            self.window.rem_size_override_stack.push(rem_size.into());
1284            let result = f(self);
1285            self.window.rem_size_override_stack.pop();
1286            result
1287        } else {
1288            f(self)
1289        }
1290    }
1291
1292    /// The line height associated with the current text style.
1293    pub fn line_height(&self) -> Pixels {
1294        let rem_size = self.rem_size();
1295        let text_style = self.text_style();
1296        text_style
1297            .line_height
1298            .to_pixels(text_style.font_size, rem_size)
1299    }
1300
1301    /// Call to prevent the default action of an event. Currently only used to prevent
1302    /// parent elements from becoming focused on mouse down.
1303    pub fn prevent_default(&mut self) {
1304        self.window.default_prevented = true;
1305    }
1306
1307    /// Obtain whether default has been prevented for the event currently being dispatched.
1308    pub fn default_prevented(&self) -> bool {
1309        self.window.default_prevented
1310    }
1311
1312    /// Determine whether the given action is available along the dispatch path to the currently focused element.
1313    pub fn is_action_available(&self, action: &dyn Action) -> bool {
1314        let target = self
1315            .focused()
1316            .and_then(|focused_handle| {
1317                self.window
1318                    .rendered_frame
1319                    .dispatch_tree
1320                    .focusable_node_id(focused_handle.id)
1321            })
1322            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1323        self.window
1324            .rendered_frame
1325            .dispatch_tree
1326            .is_action_available(action, target)
1327    }
1328
1329    /// The position of the mouse relative to the window.
1330    pub fn mouse_position(&self) -> Point<Pixels> {
1331        self.window.mouse_position
1332    }
1333
1334    /// The current state of the keyboard's modifiers
1335    pub fn modifiers(&self) -> Modifiers {
1336        self.window.modifiers
1337    }
1338
1339    fn complete_frame(&self) {
1340        self.window.platform_window.completed_frame();
1341    }
1342
1343    /// Produces a new frame and assigns it to `rendered_frame`. To actually show
1344    /// the contents of the new [Scene], use [present].
1345    #[profiling::function]
1346    pub fn draw(&mut self) {
1347        self.window.dirty.set(false);
1348        self.window.requested_autoscroll = None;
1349
1350        // Restore the previously-used input handler.
1351        if let Some(input_handler) = self.window.platform_window.take_input_handler() {
1352            self.window
1353                .rendered_frame
1354                .input_handlers
1355                .push(Some(input_handler));
1356        }
1357
1358        self.draw_roots();
1359        self.window.dirty_views.clear();
1360
1361        self.window
1362            .next_frame
1363            .dispatch_tree
1364            .preserve_pending_keystrokes(
1365                &mut self.window.rendered_frame.dispatch_tree,
1366                self.window.focus,
1367            );
1368        self.window.next_frame.focus = self.window.focus;
1369        self.window.next_frame.window_active = self.window.active.get();
1370
1371        // Register requested input handler with the platform window.
1372        if let Some(input_handler) = self.window.next_frame.input_handlers.pop() {
1373            self.window
1374                .platform_window
1375                .set_input_handler(input_handler.unwrap());
1376        }
1377
1378        self.window.layout_engine.as_mut().unwrap().clear();
1379        self.text_system().finish_frame();
1380        self.window
1381            .next_frame
1382            .finish(&mut self.window.rendered_frame);
1383        ELEMENT_ARENA.with_borrow_mut(|element_arena| {
1384            let percentage = (element_arena.len() as f32 / element_arena.capacity() as f32) * 100.;
1385            if percentage >= 80. {
1386                log::warn!("elevated element arena occupation: {}.", percentage);
1387            }
1388            element_arena.clear();
1389        });
1390
1391        self.window.draw_phase = DrawPhase::Focus;
1392        let previous_focus_path = self.window.rendered_frame.focus_path();
1393        let previous_window_active = self.window.rendered_frame.window_active;
1394        mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
1395        self.window.next_frame.clear();
1396        let current_focus_path = self.window.rendered_frame.focus_path();
1397        let current_window_active = self.window.rendered_frame.window_active;
1398
1399        if previous_focus_path != current_focus_path
1400            || previous_window_active != current_window_active
1401        {
1402            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1403                self.window
1404                    .focus_lost_listeners
1405                    .clone()
1406                    .retain(&(), |listener| listener(self));
1407            }
1408
1409            let event = WindowFocusEvent {
1410                previous_focus_path: if previous_window_active {
1411                    previous_focus_path
1412                } else {
1413                    Default::default()
1414                },
1415                current_focus_path: if current_window_active {
1416                    current_focus_path
1417                } else {
1418                    Default::default()
1419                },
1420            };
1421            self.window
1422                .focus_listeners
1423                .clone()
1424                .retain(&(), |listener| listener(&event, self));
1425        }
1426
1427        self.reset_cursor_style();
1428        self.window.refreshing = false;
1429        self.window.draw_phase = DrawPhase::None;
1430        self.window.needs_present.set(true);
1431    }
1432
1433    #[profiling::function]
1434    fn present(&self) {
1435        self.window
1436            .platform_window
1437            .draw(&self.window.rendered_frame.scene);
1438        self.window.needs_present.set(false);
1439        profiling::finish_frame!();
1440    }
1441
1442    fn draw_roots(&mut self) {
1443        self.window.draw_phase = DrawPhase::Prepaint;
1444        self.window.tooltip_bounds.take();
1445
1446        // Layout all root elements.
1447        let mut root_element = self.window.root_view.as_ref().unwrap().clone().into_any();
1448        root_element.prepaint_as_root(Point::default(), self.window.viewport_size.into(), self);
1449
1450        let mut sorted_deferred_draws =
1451            (0..self.window.next_frame.deferred_draws.len()).collect::<SmallVec<[_; 8]>>();
1452        sorted_deferred_draws.sort_by_key(|ix| self.window.next_frame.deferred_draws[*ix].priority);
1453        self.prepaint_deferred_draws(&sorted_deferred_draws);
1454
1455        let mut prompt_element = None;
1456        let mut active_drag_element = None;
1457        let mut tooltip_element = None;
1458        if let Some(prompt) = self.window.prompt.take() {
1459            let mut element = prompt.view.any_view().into_any();
1460            element.prepaint_as_root(Point::default(), self.window.viewport_size.into(), self);
1461            prompt_element = Some(element);
1462            self.window.prompt = Some(prompt);
1463        } else if let Some(active_drag) = self.app.active_drag.take() {
1464            let mut element = active_drag.view.clone().into_any();
1465            let offset = self.mouse_position() - active_drag.cursor_offset;
1466            element.prepaint_as_root(offset, AvailableSpace::min_size(), self);
1467            active_drag_element = Some(element);
1468            self.app.active_drag = Some(active_drag);
1469        } else {
1470            tooltip_element = self.prepaint_tooltip();
1471        }
1472
1473        self.window.mouse_hit_test = self.window.next_frame.hit_test(self.window.mouse_position);
1474
1475        // Now actually paint the elements.
1476        self.window.draw_phase = DrawPhase::Paint;
1477        root_element.paint(self);
1478
1479        self.paint_deferred_draws(&sorted_deferred_draws);
1480
1481        if let Some(mut prompt_element) = prompt_element {
1482            prompt_element.paint(self)
1483        } else if let Some(mut drag_element) = active_drag_element {
1484            drag_element.paint(self);
1485        } else if let Some(mut tooltip_element) = tooltip_element {
1486            tooltip_element.paint(self);
1487        }
1488    }
1489
1490    fn prepaint_tooltip(&mut self) -> Option<AnyElement> {
1491        let tooltip_request = self.window.next_frame.tooltip_requests.last().cloned()?;
1492        let tooltip_request = tooltip_request.unwrap();
1493        let mut element = tooltip_request.tooltip.view.clone().into_any();
1494        let mouse_position = tooltip_request.tooltip.mouse_position;
1495        let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self);
1496
1497        let mut tooltip_bounds = Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
1498        let window_bounds = Bounds {
1499            origin: Point::default(),
1500            size: self.viewport_size(),
1501        };
1502
1503        if tooltip_bounds.right() > window_bounds.right() {
1504            let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
1505            if new_x >= Pixels::ZERO {
1506                tooltip_bounds.origin.x = new_x;
1507            } else {
1508                tooltip_bounds.origin.x = cmp::max(
1509                    Pixels::ZERO,
1510                    tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
1511                );
1512            }
1513        }
1514
1515        if tooltip_bounds.bottom() > window_bounds.bottom() {
1516            let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
1517            if new_y >= Pixels::ZERO {
1518                tooltip_bounds.origin.y = new_y;
1519            } else {
1520                tooltip_bounds.origin.y = cmp::max(
1521                    Pixels::ZERO,
1522                    tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
1523                );
1524            }
1525        }
1526
1527        self.with_absolute_element_offset(tooltip_bounds.origin, |cx| element.prepaint(cx));
1528
1529        self.window.tooltip_bounds = Some(TooltipBounds {
1530            id: tooltip_request.id,
1531            bounds: tooltip_bounds,
1532        });
1533        Some(element)
1534    }
1535
1536    fn prepaint_deferred_draws(&mut self, deferred_draw_indices: &[usize]) {
1537        assert_eq!(self.window.element_id_stack.len(), 0);
1538
1539        let mut deferred_draws = mem::take(&mut self.window.next_frame.deferred_draws);
1540        for deferred_draw_ix in deferred_draw_indices {
1541            let deferred_draw = &mut deferred_draws[*deferred_draw_ix];
1542            self.window
1543                .element_id_stack
1544                .clone_from(&deferred_draw.element_id_stack);
1545            self.window
1546                .text_style_stack
1547                .clone_from(&deferred_draw.text_style_stack);
1548            self.window
1549                .next_frame
1550                .dispatch_tree
1551                .set_active_node(deferred_draw.parent_node);
1552
1553            let prepaint_start = self.prepaint_index();
1554            if let Some(element) = deferred_draw.element.as_mut() {
1555                self.with_absolute_element_offset(deferred_draw.absolute_offset, |cx| {
1556                    element.prepaint(cx)
1557                });
1558            } else {
1559                self.reuse_prepaint(deferred_draw.prepaint_range.clone());
1560            }
1561            let prepaint_end = self.prepaint_index();
1562            deferred_draw.prepaint_range = prepaint_start..prepaint_end;
1563        }
1564        assert_eq!(
1565            self.window.next_frame.deferred_draws.len(),
1566            0,
1567            "cannot call defer_draw during deferred drawing"
1568        );
1569        self.window.next_frame.deferred_draws = deferred_draws;
1570        self.window.element_id_stack.clear();
1571        self.window.text_style_stack.clear();
1572    }
1573
1574    fn paint_deferred_draws(&mut self, deferred_draw_indices: &[usize]) {
1575        assert_eq!(self.window.element_id_stack.len(), 0);
1576
1577        let mut deferred_draws = mem::take(&mut self.window.next_frame.deferred_draws);
1578        for deferred_draw_ix in deferred_draw_indices {
1579            let mut deferred_draw = &mut deferred_draws[*deferred_draw_ix];
1580            self.window
1581                .element_id_stack
1582                .clone_from(&deferred_draw.element_id_stack);
1583            self.window
1584                .next_frame
1585                .dispatch_tree
1586                .set_active_node(deferred_draw.parent_node);
1587
1588            let paint_start = self.paint_index();
1589            if let Some(element) = deferred_draw.element.as_mut() {
1590                element.paint(self);
1591            } else {
1592                self.reuse_paint(deferred_draw.paint_range.clone());
1593            }
1594            let paint_end = self.paint_index();
1595            deferred_draw.paint_range = paint_start..paint_end;
1596        }
1597        self.window.next_frame.deferred_draws = deferred_draws;
1598        self.window.element_id_stack.clear();
1599    }
1600
1601    pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
1602        PrepaintStateIndex {
1603            hitboxes_index: self.window.next_frame.hitboxes.len(),
1604            tooltips_index: self.window.next_frame.tooltip_requests.len(),
1605            deferred_draws_index: self.window.next_frame.deferred_draws.len(),
1606            dispatch_tree_index: self.window.next_frame.dispatch_tree.len(),
1607            accessed_element_states_index: self.window.next_frame.accessed_element_states.len(),
1608            line_layout_index: self.window.text_system.layout_index(),
1609        }
1610    }
1611
1612    pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
1613        let window = &mut self.window;
1614        window.next_frame.hitboxes.extend(
1615            window.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
1616                .iter()
1617                .cloned(),
1618        );
1619        window.next_frame.tooltip_requests.extend(
1620            window.rendered_frame.tooltip_requests
1621                [range.start.tooltips_index..range.end.tooltips_index]
1622                .iter_mut()
1623                .map(|request| request.take()),
1624        );
1625        window.next_frame.accessed_element_states.extend(
1626            window.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
1627                ..range.end.accessed_element_states_index]
1628                .iter()
1629                .map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
1630        );
1631        window
1632            .text_system
1633            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
1634
1635        let reused_subtree = window.next_frame.dispatch_tree.reuse_subtree(
1636            range.start.dispatch_tree_index..range.end.dispatch_tree_index,
1637            &mut window.rendered_frame.dispatch_tree,
1638        );
1639        window.next_frame.deferred_draws.extend(
1640            window.rendered_frame.deferred_draws
1641                [range.start.deferred_draws_index..range.end.deferred_draws_index]
1642                .iter()
1643                .map(|deferred_draw| DeferredDraw {
1644                    parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
1645                    element_id_stack: deferred_draw.element_id_stack.clone(),
1646                    text_style_stack: deferred_draw.text_style_stack.clone(),
1647                    priority: deferred_draw.priority,
1648                    element: None,
1649                    absolute_offset: deferred_draw.absolute_offset,
1650                    prepaint_range: deferred_draw.prepaint_range.clone(),
1651                    paint_range: deferred_draw.paint_range.clone(),
1652                }),
1653        );
1654    }
1655
1656    pub(crate) fn paint_index(&self) -> PaintIndex {
1657        PaintIndex {
1658            scene_index: self.window.next_frame.scene.len(),
1659            mouse_listeners_index: self.window.next_frame.mouse_listeners.len(),
1660            input_handlers_index: self.window.next_frame.input_handlers.len(),
1661            cursor_styles_index: self.window.next_frame.cursor_styles.len(),
1662            accessed_element_states_index: self.window.next_frame.accessed_element_states.len(),
1663            line_layout_index: self.window.text_system.layout_index(),
1664        }
1665    }
1666
1667    pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
1668        let window = &mut self.window;
1669
1670        window.next_frame.cursor_styles.extend(
1671            window.rendered_frame.cursor_styles
1672                [range.start.cursor_styles_index..range.end.cursor_styles_index]
1673                .iter()
1674                .cloned(),
1675        );
1676        window.next_frame.input_handlers.extend(
1677            window.rendered_frame.input_handlers
1678                [range.start.input_handlers_index..range.end.input_handlers_index]
1679                .iter_mut()
1680                .map(|handler| handler.take()),
1681        );
1682        window.next_frame.mouse_listeners.extend(
1683            window.rendered_frame.mouse_listeners
1684                [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
1685                .iter_mut()
1686                .map(|listener| listener.take()),
1687        );
1688        window.next_frame.accessed_element_states.extend(
1689            window.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
1690                ..range.end.accessed_element_states_index]
1691                .iter()
1692                .map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
1693        );
1694        window
1695            .text_system
1696            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
1697        window.next_frame.scene.replay(
1698            range.start.scene_index..range.end.scene_index,
1699            &window.rendered_frame.scene,
1700        );
1701    }
1702
1703    /// Push a text style onto the stack, and call a function with that style active.
1704    /// Use [`AppContext::text_style`] to get the current, combined text style. This method
1705    /// should only be called as part of element drawing.
1706    pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
1707    where
1708        F: FnOnce(&mut Self) -> R,
1709    {
1710        debug_assert!(
1711            matches!(
1712                self.window.draw_phase,
1713                DrawPhase::Prepaint | DrawPhase::Paint
1714            ),
1715            "this method can only be called during request_layout, prepaint, or paint"
1716        );
1717        if let Some(style) = style {
1718            self.window.text_style_stack.push(style);
1719            let result = f(self);
1720            self.window.text_style_stack.pop();
1721            result
1722        } else {
1723            f(self)
1724        }
1725    }
1726
1727    /// Updates the cursor style at the platform level. This method should only be called
1728    /// during the prepaint phase of element drawing.
1729    pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
1730        debug_assert_eq!(
1731            self.window.draw_phase,
1732            DrawPhase::Paint,
1733            "this method can only be called during paint"
1734        );
1735        self.window
1736            .next_frame
1737            .cursor_styles
1738            .push(CursorStyleRequest {
1739                hitbox_id: hitbox.id,
1740                style,
1741            });
1742    }
1743
1744    /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
1745    /// during the paint phase of element drawing.
1746    pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
1747        debug_assert_eq!(
1748            self.window.draw_phase,
1749            DrawPhase::Prepaint,
1750            "this method can only be called during prepaint"
1751        );
1752        let id = TooltipId(post_inc(&mut self.window.next_tooltip_id.0));
1753        self.window
1754            .next_frame
1755            .tooltip_requests
1756            .push(Some(TooltipRequest { id, tooltip }));
1757        id
1758    }
1759
1760    /// Invoke the given function with the given content mask after intersecting it
1761    /// with the current mask. This method should only be called during element drawing.
1762    pub fn with_content_mask<R>(
1763        &mut self,
1764        mask: Option<ContentMask<Pixels>>,
1765        f: impl FnOnce(&mut Self) -> R,
1766    ) -> R {
1767        debug_assert!(
1768            matches!(
1769                self.window.draw_phase,
1770                DrawPhase::Prepaint | DrawPhase::Paint
1771            ),
1772            "this method can only be called during request_layout, prepaint, or paint"
1773        );
1774        if let Some(mask) = mask {
1775            let mask = mask.intersect(&self.content_mask());
1776            self.window_mut().content_mask_stack.push(mask);
1777            let result = f(self);
1778            self.window_mut().content_mask_stack.pop();
1779            result
1780        } else {
1781            f(self)
1782        }
1783    }
1784
1785    /// Updates the global element offset relative to the current offset. This is used to implement
1786    /// scrolling. This method should only be called during the prepaint phase of element drawing.
1787    pub fn with_element_offset<R>(
1788        &mut self,
1789        offset: Point<Pixels>,
1790        f: impl FnOnce(&mut Self) -> R,
1791    ) -> R {
1792        debug_assert_eq!(
1793            self.window.draw_phase,
1794            DrawPhase::Prepaint,
1795            "this method can only be called during request_layout, or prepaint"
1796        );
1797
1798        if offset.is_zero() {
1799            return f(self);
1800        };
1801
1802        let abs_offset = self.element_offset() + offset;
1803        self.with_absolute_element_offset(abs_offset, f)
1804    }
1805
1806    /// Updates the global element offset based on the given offset. This is used to implement
1807    /// drag handles and other manual painting of elements. This method should only be called during
1808    /// the prepaint phase of element drawing.
1809    pub fn with_absolute_element_offset<R>(
1810        &mut self,
1811        offset: Point<Pixels>,
1812        f: impl FnOnce(&mut Self) -> R,
1813    ) -> R {
1814        debug_assert_eq!(
1815            self.window.draw_phase,
1816            DrawPhase::Prepaint,
1817            "this method can only be called during request_layout, or prepaint"
1818        );
1819        self.window_mut().element_offset_stack.push(offset);
1820        let result = f(self);
1821        self.window_mut().element_offset_stack.pop();
1822        result
1823    }
1824
1825    /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
1826    /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
1827    /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
1828    /// element offset and prepaint again. See [`List`] for an example. This method should only be
1829    /// called during the prepaint phase of element drawing.
1830    pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
1831        debug_assert_eq!(
1832            self.window.draw_phase,
1833            DrawPhase::Prepaint,
1834            "this method can only be called during prepaint"
1835        );
1836        let index = self.prepaint_index();
1837        let result = f(self);
1838        if result.is_err() {
1839            self.window
1840                .next_frame
1841                .hitboxes
1842                .truncate(index.hitboxes_index);
1843            self.window
1844                .next_frame
1845                .tooltip_requests
1846                .truncate(index.tooltips_index);
1847            self.window
1848                .next_frame
1849                .deferred_draws
1850                .truncate(index.deferred_draws_index);
1851            self.window
1852                .next_frame
1853                .dispatch_tree
1854                .truncate(index.dispatch_tree_index);
1855            self.window
1856                .next_frame
1857                .accessed_element_states
1858                .truncate(index.accessed_element_states_index);
1859            self.window
1860                .text_system
1861                .truncate_layouts(index.line_layout_index);
1862        }
1863        result
1864    }
1865
1866    /// When you call this method during [`prepaint`], containing elements will attempt to
1867    /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
1868    /// [`prepaint`] again with a new set of bounds. See [`List`] for an example of an element
1869    /// that supports this method being called on the elements it contains. This method should only be
1870    /// called during the prepaint phase of element drawing.
1871    pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
1872        debug_assert_eq!(
1873            self.window.draw_phase,
1874            DrawPhase::Prepaint,
1875            "this method can only be called during prepaint"
1876        );
1877        self.window.requested_autoscroll = Some(bounds);
1878    }
1879
1880    /// This method can be called from a containing element such as [`List`] to support the autoscroll behavior
1881    /// described in [`request_autoscroll`].
1882    pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
1883        debug_assert_eq!(
1884            self.window.draw_phase,
1885            DrawPhase::Prepaint,
1886            "this method can only be called during prepaint"
1887        );
1888        self.window.requested_autoscroll.take()
1889    }
1890
1891    /// Remove an asset from GPUI's cache
1892    pub fn remove_cached_asset<A: Asset + 'static>(
1893        &mut self,
1894        source: &A::Source,
1895    ) -> Option<A::Output> {
1896        self.asset_cache.remove::<A>(source)
1897    }
1898
1899    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1900    /// Your view will be re-drawn once the asset has finished loading.
1901    ///
1902    /// Note that the multiple calls to this method will only result in one `Asset::load` call.
1903    /// The results of that call will be cached, and returned on subsequent uses of this API.
1904    ///
1905    /// Use [Self::remove_cached_asset] to reload your asset.
1906    pub fn use_cached_asset<A: Asset + 'static>(
1907        &mut self,
1908        source: &A::Source,
1909    ) -> Option<A::Output> {
1910        self.asset_cache.get::<A>(source).or_else(|| {
1911            if let Some(asset) = self.use_asset::<A>(source) {
1912                self.asset_cache
1913                    .insert::<A>(source.to_owned(), asset.clone());
1914                Some(asset)
1915            } else {
1916                None
1917            }
1918        })
1919    }
1920
1921    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1922    /// Your view will be re-drawn once the asset has finished loading.
1923    ///
1924    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
1925    /// time.
1926    ///
1927    /// This asset will not be cached by default, see [Self::use_cached_asset]
1928    pub fn use_asset<A: Asset + 'static>(&mut self, source: &A::Source) -> Option<A::Output> {
1929        let asset_id = (TypeId::of::<A>(), hash(source));
1930        let mut is_first = false;
1931        let task = self
1932            .loading_assets
1933            .remove(&asset_id)
1934            .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
1935            .unwrap_or_else(|| {
1936                is_first = true;
1937                let future = A::load(source.clone(), self);
1938                let task = self.background_executor().spawn(future).shared();
1939                task
1940            });
1941
1942        task.clone().now_or_never().or_else(|| {
1943            if is_first {
1944                let parent_id = self.parent_view_id();
1945                self.spawn({
1946                    let task = task.clone();
1947                    |mut cx| async move {
1948                        task.await;
1949
1950                        cx.on_next_frame(move |cx| {
1951                            if let Some(parent_id) = parent_id {
1952                                cx.notify(parent_id)
1953                            } else {
1954                                cx.refresh()
1955                            }
1956                        });
1957                    }
1958                })
1959                .detach();
1960            }
1961
1962            self.loading_assets.insert(asset_id, Box::new(task));
1963
1964            None
1965        })
1966    }
1967
1968    /// Obtain the current element offset. This method should only be called during the
1969    /// prepaint phase of element drawing.
1970    pub fn element_offset(&self) -> Point<Pixels> {
1971        debug_assert_eq!(
1972            self.window.draw_phase,
1973            DrawPhase::Prepaint,
1974            "this method can only be called during prepaint"
1975        );
1976        self.window()
1977            .element_offset_stack
1978            .last()
1979            .copied()
1980            .unwrap_or_default()
1981    }
1982
1983    /// Obtain the current content mask. This method should only be called during element drawing.
1984    pub fn content_mask(&self) -> ContentMask<Pixels> {
1985        debug_assert!(
1986            matches!(
1987                self.window.draw_phase,
1988                DrawPhase::Prepaint | DrawPhase::Paint
1989            ),
1990            "this method can only be called during prepaint, or paint"
1991        );
1992        self.window()
1993            .content_mask_stack
1994            .last()
1995            .cloned()
1996            .unwrap_or_else(|| ContentMask {
1997                bounds: Bounds {
1998                    origin: Point::default(),
1999                    size: self.window().viewport_size,
2000                },
2001            })
2002    }
2003
2004    /// Provide elements in the called function with a new namespace in which their identiers must be unique.
2005    /// This can be used within a custom element to distinguish multiple sets of child elements.
2006    pub fn with_element_namespace<R>(
2007        &mut self,
2008        element_id: impl Into<ElementId>,
2009        f: impl FnOnce(&mut Self) -> R,
2010    ) -> R {
2011        self.window.element_id_stack.push(element_id.into());
2012        let result = f(self);
2013        self.window.element_id_stack.pop();
2014        result
2015    }
2016
2017    /// Updates or initializes state for an element with the given id that lives across multiple
2018    /// frames. If an element with this ID existed in the rendered frame, its state will be passed
2019    /// to the given closure. The state returned by the closure will be stored so it can be referenced
2020    /// when drawing the next frame. This method should only be called as part of element drawing.
2021    pub fn with_element_state<S, R>(
2022        &mut self,
2023        global_id: &GlobalElementId,
2024        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2025    ) -> R
2026    where
2027        S: 'static,
2028    {
2029        debug_assert!(
2030            matches!(
2031                self.window.draw_phase,
2032                DrawPhase::Prepaint | DrawPhase::Paint
2033            ),
2034            "this method can only be called during request_layout, prepaint, or paint"
2035        );
2036
2037        let key = (GlobalElementId(global_id.0.clone()), TypeId::of::<S>());
2038        self.window
2039            .next_frame
2040            .accessed_element_states
2041            .push((GlobalElementId(key.0.clone()), TypeId::of::<S>()));
2042
2043        if let Some(any) = self
2044            .window
2045            .next_frame
2046            .element_states
2047            .remove(&key)
2048            .or_else(|| self.window.rendered_frame.element_states.remove(&key))
2049        {
2050            let ElementStateBox {
2051                inner,
2052                #[cfg(debug_assertions)]
2053                type_name,
2054            } = any;
2055            // Using the extra inner option to avoid needing to reallocate a new box.
2056            let mut state_box = inner
2057                .downcast::<Option<S>>()
2058                .map_err(|_| {
2059                    #[cfg(debug_assertions)]
2060                    {
2061                        anyhow::anyhow!(
2062                            "invalid element state type for id, requested {:?}, actual: {:?}",
2063                            std::any::type_name::<S>(),
2064                            type_name
2065                        )
2066                    }
2067
2068                    #[cfg(not(debug_assertions))]
2069                    {
2070                        anyhow::anyhow!(
2071                            "invalid element state type for id, requested {:?}",
2072                            std::any::type_name::<S>(),
2073                        )
2074                    }
2075                })
2076                .unwrap();
2077
2078            let state = state_box.take().expect(
2079                "reentrant call to with_element_state for the same state type and element id",
2080            );
2081            let (result, state) = f(Some(state), self);
2082            state_box.replace(state);
2083            self.window.next_frame.element_states.insert(
2084                key,
2085                ElementStateBox {
2086                    inner: state_box,
2087                    #[cfg(debug_assertions)]
2088                    type_name,
2089                },
2090            );
2091            result
2092        } else {
2093            let (result, state) = f(None, self);
2094            self.window.next_frame.element_states.insert(
2095                key,
2096                ElementStateBox {
2097                    inner: Box::new(Some(state)),
2098                    #[cfg(debug_assertions)]
2099                    type_name: std::any::type_name::<S>(),
2100                },
2101            );
2102            result
2103        }
2104    }
2105
2106    /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
2107    /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
2108    /// when the element is guaranteed to have an id.
2109    pub fn with_optional_element_state<S, R>(
2110        &mut self,
2111        global_id: Option<&GlobalElementId>,
2112        f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
2113    ) -> R
2114    where
2115        S: 'static,
2116    {
2117        debug_assert!(
2118            matches!(
2119                self.window.draw_phase,
2120                DrawPhase::Prepaint | DrawPhase::Paint
2121            ),
2122            "this method can only be called during request_layout, prepaint, or paint"
2123        );
2124
2125        if let Some(global_id) = global_id {
2126            self.with_element_state(global_id, |state, cx| {
2127                let (result, state) = f(Some(state), cx);
2128                let state =
2129                    state.expect("you must return some state when you pass some element id");
2130                (result, state)
2131            })
2132        } else {
2133            let (result, state) = f(None, self);
2134            debug_assert!(
2135                state.is_none(),
2136                "you must not return an element state when passing None for the global id"
2137            );
2138            result
2139        }
2140    }
2141
2142    /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
2143    /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
2144    /// with higher values being drawn on top.
2145    ///
2146    /// This method should only be called as part of the prepaint phase of element drawing.
2147    pub fn defer_draw(
2148        &mut self,
2149        element: AnyElement,
2150        absolute_offset: Point<Pixels>,
2151        priority: usize,
2152    ) {
2153        let window = &mut self.window;
2154        debug_assert_eq!(
2155            window.draw_phase,
2156            DrawPhase::Prepaint,
2157            "this method can only be called during request_layout or prepaint"
2158        );
2159        let parent_node = window.next_frame.dispatch_tree.active_node_id().unwrap();
2160        window.next_frame.deferred_draws.push(DeferredDraw {
2161            parent_node,
2162            element_id_stack: window.element_id_stack.clone(),
2163            text_style_stack: window.text_style_stack.clone(),
2164            priority,
2165            element: Some(element),
2166            absolute_offset,
2167            prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
2168            paint_range: PaintIndex::default()..PaintIndex::default(),
2169        });
2170    }
2171
2172    /// Creates a new painting layer for the specified bounds. A "layer" is a batch
2173    /// of geometry that are non-overlapping and have the same draw order. This is typically used
2174    /// for performance reasons.
2175    ///
2176    /// This method should only be called as part of the paint phase of element drawing.
2177    pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
2178        debug_assert_eq!(
2179            self.window.draw_phase,
2180            DrawPhase::Paint,
2181            "this method can only be called during paint"
2182        );
2183
2184        let scale_factor = self.scale_factor();
2185        let content_mask = self.content_mask();
2186        let clipped_bounds = bounds.intersect(&content_mask.bounds);
2187        if !clipped_bounds.is_empty() {
2188            self.window
2189                .next_frame
2190                .scene
2191                .push_layer(clipped_bounds.scale(scale_factor));
2192        }
2193
2194        let result = f(self);
2195
2196        if !clipped_bounds.is_empty() {
2197            self.window.next_frame.scene.pop_layer();
2198        }
2199
2200        result
2201    }
2202
2203    /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
2204    ///
2205    /// This method should only be called as part of the paint phase of element drawing.
2206    pub fn paint_shadows(
2207        &mut self,
2208        bounds: Bounds<Pixels>,
2209        corner_radii: Corners<Pixels>,
2210        shadows: &[BoxShadow],
2211    ) {
2212        debug_assert_eq!(
2213            self.window.draw_phase,
2214            DrawPhase::Paint,
2215            "this method can only be called during paint"
2216        );
2217
2218        let scale_factor = self.scale_factor();
2219        let content_mask = self.content_mask();
2220        for shadow in shadows {
2221            let mut shadow_bounds = bounds;
2222            shadow_bounds.origin += shadow.offset;
2223            shadow_bounds.dilate(shadow.spread_radius);
2224            self.window.next_frame.scene.insert_primitive(Shadow {
2225                order: 0,
2226                blur_radius: shadow.blur_radius.scale(scale_factor),
2227                bounds: shadow_bounds.scale(scale_factor),
2228                content_mask: content_mask.scale(scale_factor),
2229                corner_radii: corner_radii.scale(scale_factor),
2230                color: shadow.color,
2231            });
2232        }
2233    }
2234
2235    /// Paint one or more quads into the scene for the next frame at the current stacking context.
2236    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
2237    /// see [`fill`](crate::fill), [`outline`](crate::outline), and [`quad`](crate::quad) to construct this type.
2238    ///
2239    /// This method should only be called as part of the paint phase of element drawing.
2240    pub fn paint_quad(&mut self, quad: PaintQuad) {
2241        debug_assert_eq!(
2242            self.window.draw_phase,
2243            DrawPhase::Paint,
2244            "this method can only be called during paint"
2245        );
2246
2247        let scale_factor = self.scale_factor();
2248        let content_mask = self.content_mask();
2249        self.window.next_frame.scene.insert_primitive(Quad {
2250            order: 0,
2251            pad: 0,
2252            bounds: quad.bounds.scale(scale_factor),
2253            content_mask: content_mask.scale(scale_factor),
2254            background: quad.background,
2255            border_color: quad.border_color,
2256            corner_radii: quad.corner_radii.scale(scale_factor),
2257            border_widths: quad.border_widths.scale(scale_factor),
2258        });
2259    }
2260
2261    /// Paint the given `Path` into the scene for the next frame at the current z-index.
2262    ///
2263    /// This method should only be called as part of the paint phase of element drawing.
2264    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
2265        debug_assert_eq!(
2266            self.window.draw_phase,
2267            DrawPhase::Paint,
2268            "this method can only be called during paint"
2269        );
2270
2271        let scale_factor = self.scale_factor();
2272        let content_mask = self.content_mask();
2273        path.content_mask = content_mask;
2274        path.color = color.into();
2275        self.window
2276            .next_frame
2277            .scene
2278            .insert_primitive(path.scale(scale_factor));
2279    }
2280
2281    /// Paint an underline into the scene for the next frame at the current z-index.
2282    ///
2283    /// This method should only be called as part of the paint phase of element drawing.
2284    pub fn paint_underline(
2285        &mut self,
2286        origin: Point<Pixels>,
2287        width: Pixels,
2288        style: &UnderlineStyle,
2289    ) {
2290        debug_assert_eq!(
2291            self.window.draw_phase,
2292            DrawPhase::Paint,
2293            "this method can only be called during paint"
2294        );
2295
2296        let scale_factor = self.scale_factor();
2297        let height = if style.wavy {
2298            style.thickness * 3.
2299        } else {
2300            style.thickness
2301        };
2302        let bounds = Bounds {
2303            origin,
2304            size: size(width, height),
2305        };
2306        let content_mask = self.content_mask();
2307
2308        self.window.next_frame.scene.insert_primitive(Underline {
2309            order: 0,
2310            pad: 0,
2311            bounds: bounds.scale(scale_factor),
2312            content_mask: content_mask.scale(scale_factor),
2313            color: style.color.unwrap_or_default(),
2314            thickness: style.thickness.scale(scale_factor),
2315            wavy: style.wavy,
2316        });
2317    }
2318
2319    /// Paint a strikethrough into the scene for the next frame at the current z-index.
2320    ///
2321    /// This method should only be called as part of the paint phase of element drawing.
2322    pub fn paint_strikethrough(
2323        &mut self,
2324        origin: Point<Pixels>,
2325        width: Pixels,
2326        style: &StrikethroughStyle,
2327    ) {
2328        debug_assert_eq!(
2329            self.window.draw_phase,
2330            DrawPhase::Paint,
2331            "this method can only be called during paint"
2332        );
2333
2334        let scale_factor = self.scale_factor();
2335        let height = style.thickness;
2336        let bounds = Bounds {
2337            origin,
2338            size: size(width, height),
2339        };
2340        let content_mask = self.content_mask();
2341
2342        self.window.next_frame.scene.insert_primitive(Underline {
2343            order: 0,
2344            pad: 0,
2345            bounds: bounds.scale(scale_factor),
2346            content_mask: content_mask.scale(scale_factor),
2347            thickness: style.thickness.scale(scale_factor),
2348            color: style.color.unwrap_or_default(),
2349            wavy: false,
2350        });
2351    }
2352
2353    /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
2354    ///
2355    /// The y component of the origin is the baseline of the glyph.
2356    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2357    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2358    /// This method is only useful if you need to paint a single glyph that has already been shaped.
2359    ///
2360    /// This method should only be called as part of the paint phase of element drawing.
2361    pub fn paint_glyph(
2362        &mut self,
2363        origin: Point<Pixels>,
2364        font_id: FontId,
2365        glyph_id: GlyphId,
2366        font_size: Pixels,
2367        color: Hsla,
2368    ) -> Result<()> {
2369        debug_assert_eq!(
2370            self.window.draw_phase,
2371            DrawPhase::Paint,
2372            "this method can only be called during paint"
2373        );
2374
2375        let scale_factor = self.scale_factor();
2376        let glyph_origin = origin.scale(scale_factor);
2377        let subpixel_variant = Point {
2378            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2379            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2380        };
2381        let params = RenderGlyphParams {
2382            font_id,
2383            glyph_id,
2384            font_size,
2385            subpixel_variant,
2386            scale_factor,
2387            is_emoji: false,
2388        };
2389
2390        let raster_bounds = self.text_system().raster_bounds(&params)?;
2391        if !raster_bounds.is_zero() {
2392            let tile = self
2393                .window
2394                .sprite_atlas
2395                .get_or_insert_with(&params.clone().into(), &mut || {
2396                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
2397                    Ok(Some((size, Cow::Owned(bytes))))
2398                })?
2399                .expect("Callback above only errors or returns Some");
2400            let bounds = Bounds {
2401                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2402                size: tile.bounds.size.map(Into::into),
2403            };
2404            let content_mask = self.content_mask().scale(scale_factor);
2405            self.window
2406                .next_frame
2407                .scene
2408                .insert_primitive(MonochromeSprite {
2409                    order: 0,
2410                    pad: 0,
2411                    bounds,
2412                    content_mask,
2413                    color,
2414                    tile,
2415                    transformation: TransformationMatrix::unit(),
2416                });
2417        }
2418        Ok(())
2419    }
2420
2421    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
2422    ///
2423    /// The y component of the origin is the baseline of the glyph.
2424    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2425    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2426    /// This method is only useful if you need to paint a single emoji that has already been shaped.
2427    ///
2428    /// This method should only be called as part of the paint phase of element drawing.
2429    pub fn paint_emoji(
2430        &mut self,
2431        origin: Point<Pixels>,
2432        font_id: FontId,
2433        glyph_id: GlyphId,
2434        font_size: Pixels,
2435    ) -> Result<()> {
2436        debug_assert_eq!(
2437            self.window.draw_phase,
2438            DrawPhase::Paint,
2439            "this method can only be called during paint"
2440        );
2441
2442        let scale_factor = self.scale_factor();
2443        let glyph_origin = origin.scale(scale_factor);
2444        let params = RenderGlyphParams {
2445            font_id,
2446            glyph_id,
2447            font_size,
2448            // We don't render emojis with subpixel variants.
2449            subpixel_variant: Default::default(),
2450            scale_factor,
2451            is_emoji: true,
2452        };
2453
2454        let raster_bounds = self.text_system().raster_bounds(&params)?;
2455        if !raster_bounds.is_zero() {
2456            let tile = self
2457                .window
2458                .sprite_atlas
2459                .get_or_insert_with(&params.clone().into(), &mut || {
2460                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
2461                    Ok(Some((size, Cow::Owned(bytes))))
2462                })?
2463                .expect("Callback above only errors or returns Some");
2464
2465            let bounds = Bounds {
2466                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2467                size: tile.bounds.size.map(Into::into),
2468            };
2469            let content_mask = self.content_mask().scale(scale_factor);
2470
2471            self.window
2472                .next_frame
2473                .scene
2474                .insert_primitive(PolychromeSprite {
2475                    order: 0,
2476                    grayscale: false,
2477                    bounds,
2478                    corner_radii: Default::default(),
2479                    content_mask,
2480                    tile,
2481                });
2482        }
2483        Ok(())
2484    }
2485
2486    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
2487    ///
2488    /// This method should only be called as part of the paint phase of element drawing.
2489    pub fn paint_svg(
2490        &mut self,
2491        bounds: Bounds<Pixels>,
2492        path: SharedString,
2493        transformation: TransformationMatrix,
2494        color: Hsla,
2495    ) -> Result<()> {
2496        debug_assert_eq!(
2497            self.window.draw_phase,
2498            DrawPhase::Paint,
2499            "this method can only be called during paint"
2500        );
2501
2502        let scale_factor = self.scale_factor();
2503        let bounds = bounds.scale(scale_factor);
2504        // Render the SVG at twice the size to get a higher quality result.
2505        let params = RenderSvgParams {
2506            path,
2507            size: bounds
2508                .size
2509                .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
2510        };
2511
2512        let Some(tile) =
2513            self.window
2514                .sprite_atlas
2515                .get_or_insert_with(&params.clone().into(), &mut || {
2516                    let Some(bytes) = self.svg_renderer.render(&params)? else {
2517                        return Ok(None);
2518                    };
2519                    Ok(Some((params.size, Cow::Owned(bytes))))
2520                })?
2521        else {
2522            return Ok(());
2523        };
2524        let content_mask = self.content_mask().scale(scale_factor);
2525
2526        self.window
2527            .next_frame
2528            .scene
2529            .insert_primitive(MonochromeSprite {
2530                order: 0,
2531                pad: 0,
2532                bounds,
2533                content_mask,
2534                color,
2535                tile,
2536                transformation,
2537            });
2538
2539        Ok(())
2540    }
2541
2542    /// Paint an image into the scene for the next frame at the current z-index.
2543    ///
2544    /// This method should only be called as part of the paint phase of element drawing.
2545    pub fn paint_image(
2546        &mut self,
2547        bounds: Bounds<Pixels>,
2548        corner_radii: Corners<Pixels>,
2549        data: Arc<ImageData>,
2550        grayscale: bool,
2551    ) -> Result<()> {
2552        debug_assert_eq!(
2553            self.window.draw_phase,
2554            DrawPhase::Paint,
2555            "this method can only be called during paint"
2556        );
2557
2558        let scale_factor = self.scale_factor();
2559        let bounds = bounds.scale(scale_factor);
2560        let params = RenderImageParams { image_id: data.id };
2561
2562        let tile = self
2563            .window
2564            .sprite_atlas
2565            .get_or_insert_with(&params.clone().into(), &mut || {
2566                Ok(Some((data.size(), Cow::Borrowed(data.as_bytes()))))
2567            })?
2568            .expect("Callback above only returns Some");
2569        let content_mask = self.content_mask().scale(scale_factor);
2570        let corner_radii = corner_radii.scale(scale_factor);
2571
2572        self.window
2573            .next_frame
2574            .scene
2575            .insert_primitive(PolychromeSprite {
2576                order: 0,
2577                grayscale,
2578                bounds,
2579                content_mask,
2580                corner_radii,
2581                tile,
2582            });
2583        Ok(())
2584    }
2585
2586    /// Paint a surface into the scene for the next frame at the current z-index.
2587    ///
2588    /// This method should only be called as part of the paint phase of element drawing.
2589    #[cfg(target_os = "macos")]
2590    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
2591        debug_assert_eq!(
2592            self.window.draw_phase,
2593            DrawPhase::Paint,
2594            "this method can only be called during paint"
2595        );
2596
2597        let scale_factor = self.scale_factor();
2598        let bounds = bounds.scale(scale_factor);
2599        let content_mask = self.content_mask().scale(scale_factor);
2600        self.window
2601            .next_frame
2602            .scene
2603            .insert_primitive(crate::Surface {
2604                order: 0,
2605                bounds,
2606                content_mask,
2607                image_buffer,
2608            });
2609    }
2610
2611    #[must_use]
2612    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
2613    /// layout is being requested, along with the layout ids of any children. This method is called during
2614    /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
2615    ///
2616    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2617    pub fn request_layout(
2618        &mut self,
2619        style: Style,
2620        children: impl IntoIterator<Item = LayoutId>,
2621    ) -> LayoutId {
2622        debug_assert_eq!(
2623            self.window.draw_phase,
2624            DrawPhase::Prepaint,
2625            "this method can only be called during request_layout, or prepaint"
2626        );
2627
2628        self.app.layout_id_buffer.clear();
2629        self.app.layout_id_buffer.extend(children);
2630        let rem_size = self.rem_size();
2631
2632        self.window.layout_engine.as_mut().unwrap().request_layout(
2633            style,
2634            rem_size,
2635            &self.app.layout_id_buffer,
2636        )
2637    }
2638
2639    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
2640    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
2641    /// determine the element's size. One place this is used internally is when measuring text.
2642    ///
2643    /// The given closure is invoked at layout time with the known dimensions and available space and
2644    /// returns a `Size`.
2645    ///
2646    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2647    pub fn request_measured_layout<
2648        F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
2649            + 'static,
2650    >(
2651        &mut self,
2652        style: Style,
2653        measure: F,
2654    ) -> LayoutId {
2655        debug_assert_eq!(
2656            self.window.draw_phase,
2657            DrawPhase::Prepaint,
2658            "this method can only be called during request_layout, or prepaint"
2659        );
2660
2661        let rem_size = self.rem_size();
2662        self.window
2663            .layout_engine
2664            .as_mut()
2665            .unwrap()
2666            .request_measured_layout(style, rem_size, measure)
2667    }
2668
2669    /// Compute the layout for the given id within the given available space.
2670    /// This method is called for its side effect, typically by the framework prior to painting.
2671    /// After calling it, you can request the bounds of the given layout node id or any descendant.
2672    ///
2673    /// This method should only be called as part of the prepaint phase of element drawing.
2674    pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
2675        debug_assert_eq!(
2676            self.window.draw_phase,
2677            DrawPhase::Prepaint,
2678            "this method can only be called during request_layout, or prepaint"
2679        );
2680
2681        let mut layout_engine = self.window.layout_engine.take().unwrap();
2682        layout_engine.compute_layout(layout_id, available_space, self);
2683        self.window.layout_engine = Some(layout_engine);
2684    }
2685
2686    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
2687    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
2688    ///
2689    /// This method should only be called as part of element drawing.
2690    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
2691        debug_assert_eq!(
2692            self.window.draw_phase,
2693            DrawPhase::Prepaint,
2694            "this method can only be called during request_layout, prepaint, or paint"
2695        );
2696
2697        let mut bounds = self
2698            .window
2699            .layout_engine
2700            .as_mut()
2701            .unwrap()
2702            .layout_bounds(layout_id)
2703            .map(Into::into);
2704        bounds.origin += self.element_offset();
2705        bounds
2706    }
2707
2708    /// This method should be called during `prepaint`. You can use
2709    /// the returned [Hitbox] during `paint` or in an event handler
2710    /// to determine whether the inserted hitbox was the topmost.
2711    ///
2712    /// This method should only be called as part of the prepaint phase of element drawing.
2713    pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, opaque: bool) -> Hitbox {
2714        debug_assert_eq!(
2715            self.window.draw_phase,
2716            DrawPhase::Prepaint,
2717            "this method can only be called during prepaint"
2718        );
2719
2720        let content_mask = self.content_mask();
2721        let window = &mut self.window;
2722        let id = window.next_hitbox_id;
2723        window.next_hitbox_id.0 += 1;
2724        let hitbox = Hitbox {
2725            id,
2726            bounds,
2727            content_mask,
2728            opaque,
2729        };
2730        window.next_frame.hitboxes.push(hitbox.clone());
2731        hitbox
2732    }
2733
2734    /// Sets the key context for the current element. This context will be used to translate
2735    /// keybindings into actions.
2736    ///
2737    /// This method should only be called as part of the paint phase of element drawing.
2738    pub fn set_key_context(&mut self, context: KeyContext) {
2739        debug_assert_eq!(
2740            self.window.draw_phase,
2741            DrawPhase::Paint,
2742            "this method can only be called during paint"
2743        );
2744        self.window
2745            .next_frame
2746            .dispatch_tree
2747            .set_key_context(context);
2748    }
2749
2750    /// Sets the focus handle for the current element. This handle will be used to manage focus state
2751    /// and keyboard event dispatch for the element.
2752    ///
2753    /// This method should only be called as part of the paint phase of element drawing.
2754    pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle) {
2755        debug_assert_eq!(
2756            self.window.draw_phase,
2757            DrawPhase::Paint,
2758            "this method can only be called during paint"
2759        );
2760        self.window
2761            .next_frame
2762            .dispatch_tree
2763            .set_focus_id(focus_handle.id);
2764    }
2765
2766    /// Sets the view id for the current element, which will be used to manage view caching.
2767    ///
2768    /// This method should only be called as part of element prepaint. We plan on removing this
2769    /// method eventually when we solve some issues that require us to construct editor elements
2770    /// directly instead of always using editors via views.
2771    pub fn set_view_id(&mut self, view_id: EntityId) {
2772        debug_assert_eq!(
2773            self.window.draw_phase,
2774            DrawPhase::Prepaint,
2775            "this method can only be called during prepaint"
2776        );
2777        self.window.next_frame.dispatch_tree.set_view_id(view_id);
2778    }
2779
2780    /// Get the last view id for the current element
2781    pub fn parent_view_id(&mut self) -> Option<EntityId> {
2782        self.window.next_frame.dispatch_tree.parent_view_id()
2783    }
2784
2785    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
2786    /// platform to receive textual input with proper integration with concerns such
2787    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
2788    /// rendered.
2789    ///
2790    /// This method should only be called as part of the paint phase of element drawing.
2791    ///
2792    /// [element_input_handler]: crate::ElementInputHandler
2793    pub fn handle_input(&mut self, focus_handle: &FocusHandle, input_handler: impl InputHandler) {
2794        debug_assert_eq!(
2795            self.window.draw_phase,
2796            DrawPhase::Paint,
2797            "this method can only be called during paint"
2798        );
2799
2800        if focus_handle.is_focused(self) {
2801            let cx = self.to_async();
2802            self.window
2803                .next_frame
2804                .input_handlers
2805                .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
2806        }
2807    }
2808
2809    /// Register a mouse event listener on the window for the next frame. The type of event
2810    /// is determined by the first parameter of the given listener. When the next frame is rendered
2811    /// the listener will be cleared.
2812    ///
2813    /// This method should only be called as part of the paint phase of element drawing.
2814    pub fn on_mouse_event<Event: MouseEvent>(
2815        &mut self,
2816        mut handler: impl FnMut(&Event, DispatchPhase, &mut WindowContext) + 'static,
2817    ) {
2818        debug_assert_eq!(
2819            self.window.draw_phase,
2820            DrawPhase::Paint,
2821            "this method can only be called during paint"
2822        );
2823
2824        self.window.next_frame.mouse_listeners.push(Some(Box::new(
2825            move |event: &dyn Any, phase: DispatchPhase, cx: &mut WindowContext<'_>| {
2826                if let Some(event) = event.downcast_ref() {
2827                    handler(event, phase, cx)
2828                }
2829            },
2830        )));
2831    }
2832
2833    /// Register a key event listener on the window for the next frame. The type of event
2834    /// is determined by the first parameter of the given listener. When the next frame is rendered
2835    /// the listener will be cleared.
2836    ///
2837    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2838    /// a specific need to register a global listener.
2839    ///
2840    /// This method should only be called as part of the paint phase of element drawing.
2841    pub fn on_key_event<Event: KeyEvent>(
2842        &mut self,
2843        listener: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
2844    ) {
2845        debug_assert_eq!(
2846            self.window.draw_phase,
2847            DrawPhase::Paint,
2848            "this method can only be called during paint"
2849        );
2850
2851        self.window.next_frame.dispatch_tree.on_key_event(Rc::new(
2852            move |event: &dyn Any, phase, cx: &mut WindowContext<'_>| {
2853                if let Some(event) = event.downcast_ref::<Event>() {
2854                    listener(event, phase, cx)
2855                }
2856            },
2857        ));
2858    }
2859
2860    /// Register a modifiers changed event listener on the window for the next frame.
2861    ///
2862    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2863    /// a specific need to register a global listener.
2864    ///
2865    /// This method should only be called as part of the paint phase of element drawing.
2866    pub fn on_modifiers_changed(
2867        &mut self,
2868        listener: impl Fn(&ModifiersChangedEvent, &mut WindowContext) + 'static,
2869    ) {
2870        debug_assert_eq!(
2871            self.window.draw_phase,
2872            DrawPhase::Paint,
2873            "this method can only be called during paint"
2874        );
2875
2876        self.window
2877            .next_frame
2878            .dispatch_tree
2879            .on_modifiers_changed(Rc::new(
2880                move |event: &ModifiersChangedEvent, cx: &mut WindowContext<'_>| {
2881                    listener(event, cx)
2882                },
2883            ));
2884    }
2885
2886    fn reset_cursor_style(&self) {
2887        // Set the cursor only if we're the active window.
2888        if self.is_window_active() {
2889            let style = self
2890                .window
2891                .rendered_frame
2892                .cursor_styles
2893                .iter()
2894                .rev()
2895                .find(|request| request.hitbox_id.is_hovered(self))
2896                .map(|request| request.style)
2897                .unwrap_or(CursorStyle::Arrow);
2898            self.platform.set_cursor_style(style);
2899        }
2900    }
2901
2902    /// Dispatch a given keystroke as though the user had typed it.
2903    /// You can create a keystroke with Keystroke::parse("").
2904    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke) -> bool {
2905        let keystroke = keystroke.with_simulated_ime();
2906        let result = self.dispatch_event(PlatformInput::KeyDown(KeyDownEvent {
2907            keystroke: keystroke.clone(),
2908            is_held: false,
2909        }));
2910        if !result.propagate {
2911            return true;
2912        }
2913
2914        if let Some(input) = keystroke.ime_key {
2915            if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
2916                input_handler.dispatch_input(&input, self);
2917                self.window.platform_window.set_input_handler(input_handler);
2918                return true;
2919            }
2920        }
2921
2922        false
2923    }
2924
2925    /// Represent this action as a key binding string, to display in the UI.
2926    pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
2927        self.bindings_for_action(action)
2928            .into_iter()
2929            .next()
2930            .map(|binding| {
2931                binding
2932                    .keystrokes()
2933                    .iter()
2934                    .map(ToString::to_string)
2935                    .collect::<Vec<_>>()
2936                    .join(" ")
2937            })
2938            .unwrap_or_else(|| action.name().to_string())
2939    }
2940
2941    /// Dispatch a mouse or keyboard event on the window.
2942    #[profiling::function]
2943    pub fn dispatch_event(&mut self, event: PlatformInput) -> DispatchEventResult {
2944        self.window.last_input_timestamp.set(Instant::now());
2945        // Handlers may set this to false by calling `stop_propagation`.
2946        self.app.propagate_event = true;
2947        // Handlers may set this to true by calling `prevent_default`.
2948        self.window.default_prevented = false;
2949
2950        let event = match event {
2951            // Track the mouse position with our own state, since accessing the platform
2952            // API for the mouse position can only occur on the main thread.
2953            PlatformInput::MouseMove(mouse_move) => {
2954                self.window.mouse_position = mouse_move.position;
2955                self.window.modifiers = mouse_move.modifiers;
2956                PlatformInput::MouseMove(mouse_move)
2957            }
2958            PlatformInput::MouseDown(mouse_down) => {
2959                self.window.mouse_position = mouse_down.position;
2960                self.window.modifiers = mouse_down.modifiers;
2961                PlatformInput::MouseDown(mouse_down)
2962            }
2963            PlatformInput::MouseUp(mouse_up) => {
2964                self.window.mouse_position = mouse_up.position;
2965                self.window.modifiers = mouse_up.modifiers;
2966                PlatformInput::MouseUp(mouse_up)
2967            }
2968            PlatformInput::MouseExited(mouse_exited) => {
2969                self.window.modifiers = mouse_exited.modifiers;
2970                PlatformInput::MouseExited(mouse_exited)
2971            }
2972            PlatformInput::ModifiersChanged(modifiers_changed) => {
2973                self.window.modifiers = modifiers_changed.modifiers;
2974                PlatformInput::ModifiersChanged(modifiers_changed)
2975            }
2976            PlatformInput::ScrollWheel(scroll_wheel) => {
2977                self.window.mouse_position = scroll_wheel.position;
2978                self.window.modifiers = scroll_wheel.modifiers;
2979                PlatformInput::ScrollWheel(scroll_wheel)
2980            }
2981            // Translate dragging and dropping of external files from the operating system
2982            // to internal drag and drop events.
2983            PlatformInput::FileDrop(file_drop) => match file_drop {
2984                FileDropEvent::Entered { position, paths } => {
2985                    self.window.mouse_position = position;
2986                    if self.active_drag.is_none() {
2987                        self.active_drag = Some(AnyDrag {
2988                            value: Box::new(paths.clone()),
2989                            view: self.new_view(|_| paths).into(),
2990                            cursor_offset: position,
2991                        });
2992                    }
2993                    PlatformInput::MouseMove(MouseMoveEvent {
2994                        position,
2995                        pressed_button: Some(MouseButton::Left),
2996                        modifiers: Modifiers::default(),
2997                    })
2998                }
2999                FileDropEvent::Pending { position } => {
3000                    self.window.mouse_position = position;
3001                    PlatformInput::MouseMove(MouseMoveEvent {
3002                        position,
3003                        pressed_button: Some(MouseButton::Left),
3004                        modifiers: Modifiers::default(),
3005                    })
3006                }
3007                FileDropEvent::Submit { position } => {
3008                    self.activate(true);
3009                    self.window.mouse_position = position;
3010                    PlatformInput::MouseUp(MouseUpEvent {
3011                        button: MouseButton::Left,
3012                        position,
3013                        modifiers: Modifiers::default(),
3014                        click_count: 1,
3015                    })
3016                }
3017                FileDropEvent::Exited => {
3018                    self.active_drag.take();
3019                    PlatformInput::FileDrop(FileDropEvent::Exited)
3020                }
3021            },
3022            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
3023        };
3024
3025        if let Some(any_mouse_event) = event.mouse_event() {
3026            self.dispatch_mouse_event(any_mouse_event);
3027        } else if let Some(any_key_event) = event.keyboard_event() {
3028            self.dispatch_key_event(any_key_event);
3029        }
3030
3031        DispatchEventResult {
3032            propagate: self.app.propagate_event,
3033            default_prevented: self.window.default_prevented,
3034        }
3035    }
3036
3037    fn dispatch_mouse_event(&mut self, event: &dyn Any) {
3038        let hit_test = self.window.rendered_frame.hit_test(self.mouse_position());
3039        if hit_test != self.window.mouse_hit_test {
3040            self.window.mouse_hit_test = hit_test;
3041            self.reset_cursor_style();
3042        }
3043
3044        let mut mouse_listeners = mem::take(&mut self.window.rendered_frame.mouse_listeners);
3045
3046        // Capture phase, events bubble from back to front. Handlers for this phase are used for
3047        // special purposes, such as detecting events outside of a given Bounds.
3048        for listener in &mut mouse_listeners {
3049            let listener = listener.as_mut().unwrap();
3050            listener(event, DispatchPhase::Capture, self);
3051            if !self.app.propagate_event {
3052                break;
3053            }
3054        }
3055
3056        // Bubble phase, where most normal handlers do their work.
3057        if self.app.propagate_event {
3058            for listener in mouse_listeners.iter_mut().rev() {
3059                let listener = listener.as_mut().unwrap();
3060                listener(event, DispatchPhase::Bubble, self);
3061                if !self.app.propagate_event {
3062                    break;
3063                }
3064            }
3065        }
3066
3067        self.window.rendered_frame.mouse_listeners = mouse_listeners;
3068
3069        if self.has_active_drag() {
3070            if event.is::<MouseMoveEvent>() {
3071                // If this was a mouse move event, redraw the window so that the
3072                // active drag can follow the mouse cursor.
3073                self.refresh();
3074            } else if event.is::<MouseUpEvent>() {
3075                // If this was a mouse up event, cancel the active drag and redraw
3076                // the window.
3077                self.active_drag = None;
3078                self.refresh();
3079            }
3080        }
3081    }
3082
3083    fn dispatch_key_event(&mut self, event: &dyn Any) {
3084        if self.window.dirty.get() {
3085            self.draw();
3086        }
3087
3088        let node_id = self
3089            .window
3090            .focus
3091            .and_then(|focus_id| {
3092                self.window
3093                    .rendered_frame
3094                    .dispatch_tree
3095                    .focusable_node_id(focus_id)
3096            })
3097            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3098
3099        let dispatch_path = self
3100            .window
3101            .rendered_frame
3102            .dispatch_tree
3103            .dispatch_path(node_id);
3104
3105        if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
3106            let KeymatchResult { bindings, pending } = self
3107                .window
3108                .rendered_frame
3109                .dispatch_tree
3110                .dispatch_key(&key_down_event.keystroke, &dispatch_path);
3111
3112            if pending {
3113                let mut currently_pending = self.window.pending_input.take().unwrap_or_default();
3114                if currently_pending.focus.is_some() && currently_pending.focus != self.window.focus
3115                {
3116                    currently_pending = PendingInput::default();
3117                }
3118                currently_pending.focus = self.window.focus;
3119                currently_pending
3120                    .keystrokes
3121                    .push(key_down_event.keystroke.clone());
3122                for binding in bindings {
3123                    currently_pending.bindings.push(binding);
3124                }
3125
3126                currently_pending.timer = Some(self.spawn(|mut cx| async move {
3127                    cx.background_executor.timer(Duration::from_secs(1)).await;
3128                    cx.update(move |cx| {
3129                        cx.clear_pending_keystrokes();
3130                        let Some(currently_pending) = cx.window.pending_input.take() else {
3131                            return;
3132                        };
3133                        cx.pending_input_changed();
3134                        cx.replay_pending_input(currently_pending);
3135                    })
3136                    .log_err();
3137                }));
3138
3139                self.window.pending_input = Some(currently_pending);
3140                self.pending_input_changed();
3141
3142                self.propagate_event = false;
3143
3144                return;
3145            } else if let Some(currently_pending) = self.window.pending_input.take() {
3146                self.pending_input_changed();
3147                if bindings
3148                    .iter()
3149                    .all(|binding| !currently_pending.used_by_binding(binding))
3150                {
3151                    self.replay_pending_input(currently_pending)
3152                }
3153            }
3154
3155            if !bindings.is_empty() {
3156                self.clear_pending_keystrokes();
3157            }
3158
3159            self.propagate_event = true;
3160            for binding in bindings {
3161                self.dispatch_action_on_node(node_id, binding.action.as_ref());
3162                if !self.propagate_event {
3163                    self.dispatch_keystroke_observers(event, Some(binding.action));
3164                    return;
3165                }
3166            }
3167        }
3168
3169        self.dispatch_key_down_up_event(event, &dispatch_path);
3170        if !self.propagate_event {
3171            return;
3172        }
3173
3174        self.dispatch_modifiers_changed_event(event, &dispatch_path);
3175        if !self.propagate_event {
3176            return;
3177        }
3178
3179        self.dispatch_keystroke_observers(event, None);
3180    }
3181
3182    fn pending_input_changed(&mut self) {
3183        self.window
3184            .pending_input_observers
3185            .clone()
3186            .retain(&(), |callback| callback(self));
3187    }
3188
3189    fn dispatch_key_down_up_event(
3190        &mut self,
3191        event: &dyn Any,
3192        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3193    ) {
3194        // Capture phase
3195        for node_id in dispatch_path {
3196            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3197
3198            for key_listener in node.key_listeners.clone() {
3199                key_listener(event, DispatchPhase::Capture, self);
3200                if !self.propagate_event {
3201                    return;
3202                }
3203            }
3204        }
3205
3206        // Bubble phase
3207        for node_id in dispatch_path.iter().rev() {
3208            // Handle low level key events
3209            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3210            for key_listener in node.key_listeners.clone() {
3211                key_listener(event, DispatchPhase::Bubble, self);
3212                if !self.propagate_event {
3213                    return;
3214                }
3215            }
3216        }
3217    }
3218
3219    fn dispatch_modifiers_changed_event(
3220        &mut self,
3221        event: &dyn Any,
3222        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3223    ) {
3224        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
3225            return;
3226        };
3227        for node_id in dispatch_path.iter().rev() {
3228            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3229            for listener in node.modifiers_changed_listeners.clone() {
3230                listener(event, self);
3231                if !self.propagate_event {
3232                    return;
3233                }
3234            }
3235        }
3236    }
3237
3238    /// Determine whether a potential multi-stroke key binding is in progress on this window.
3239    pub fn has_pending_keystrokes(&self) -> bool {
3240        self.window
3241            .rendered_frame
3242            .dispatch_tree
3243            .has_pending_keystrokes()
3244    }
3245
3246    /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
3247    pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
3248        self.window
3249            .pending_input
3250            .as_ref()
3251            .map(|pending_input| pending_input.keystrokes.as_slice())
3252    }
3253
3254    fn replay_pending_input(&mut self, currently_pending: PendingInput) {
3255        let node_id = self
3256            .window
3257            .focus
3258            .and_then(|focus_id| {
3259                self.window
3260                    .rendered_frame
3261                    .dispatch_tree
3262                    .focusable_node_id(focus_id)
3263            })
3264            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3265
3266        if self.window.focus != currently_pending.focus {
3267            return;
3268        }
3269
3270        let input = currently_pending.input();
3271
3272        self.propagate_event = true;
3273        for binding in currently_pending.bindings {
3274            self.dispatch_action_on_node(node_id, binding.action.as_ref());
3275            if !self.propagate_event {
3276                return;
3277            }
3278        }
3279
3280        let dispatch_path = self
3281            .window
3282            .rendered_frame
3283            .dispatch_tree
3284            .dispatch_path(node_id);
3285
3286        for keystroke in currently_pending.keystrokes {
3287            let event = KeyDownEvent {
3288                keystroke,
3289                is_held: false,
3290            };
3291
3292            self.dispatch_key_down_up_event(&event, &dispatch_path);
3293            if !self.propagate_event {
3294                return;
3295            }
3296        }
3297
3298        if !input.is_empty() {
3299            if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
3300                input_handler.dispatch_input(&input, self);
3301                self.window.platform_window.set_input_handler(input_handler)
3302            }
3303        }
3304    }
3305
3306    fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: &dyn Action) {
3307        let dispatch_path = self
3308            .window
3309            .rendered_frame
3310            .dispatch_tree
3311            .dispatch_path(node_id);
3312
3313        // Capture phase for global actions.
3314        self.propagate_event = true;
3315        if let Some(mut global_listeners) = self
3316            .global_action_listeners
3317            .remove(&action.as_any().type_id())
3318        {
3319            for listener in &global_listeners {
3320                listener(action.as_any(), DispatchPhase::Capture, self);
3321                if !self.propagate_event {
3322                    break;
3323                }
3324            }
3325
3326            global_listeners.extend(
3327                self.global_action_listeners
3328                    .remove(&action.as_any().type_id())
3329                    .unwrap_or_default(),
3330            );
3331
3332            self.global_action_listeners
3333                .insert(action.as_any().type_id(), global_listeners);
3334        }
3335
3336        if !self.propagate_event {
3337            return;
3338        }
3339
3340        // Capture phase for window actions.
3341        for node_id in &dispatch_path {
3342            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3343            for DispatchActionListener {
3344                action_type,
3345                listener,
3346            } in node.action_listeners.clone()
3347            {
3348                let any_action = action.as_any();
3349                if action_type == any_action.type_id() {
3350                    listener(any_action, DispatchPhase::Capture, self);
3351
3352                    if !self.propagate_event {
3353                        return;
3354                    }
3355                }
3356            }
3357        }
3358
3359        // Bubble phase for window actions.
3360        for node_id in dispatch_path.iter().rev() {
3361            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3362            for DispatchActionListener {
3363                action_type,
3364                listener,
3365            } in node.action_listeners.clone()
3366            {
3367                let any_action = action.as_any();
3368                if action_type == any_action.type_id() {
3369                    self.propagate_event = false; // Actions stop propagation by default during the bubble phase
3370                    listener(any_action, DispatchPhase::Bubble, self);
3371
3372                    if !self.propagate_event {
3373                        return;
3374                    }
3375                }
3376            }
3377        }
3378
3379        // Bubble phase for global actions.
3380        if let Some(mut global_listeners) = self
3381            .global_action_listeners
3382            .remove(&action.as_any().type_id())
3383        {
3384            for listener in global_listeners.iter().rev() {
3385                self.propagate_event = false; // Actions stop propagation by default during the bubble phase
3386
3387                listener(action.as_any(), DispatchPhase::Bubble, self);
3388                if !self.propagate_event {
3389                    break;
3390                }
3391            }
3392
3393            global_listeners.extend(
3394                self.global_action_listeners
3395                    .remove(&action.as_any().type_id())
3396                    .unwrap_or_default(),
3397            );
3398
3399            self.global_action_listeners
3400                .insert(action.as_any().type_id(), global_listeners);
3401        }
3402    }
3403
3404    /// Register the given handler to be invoked whenever the global of the given type
3405    /// is updated.
3406    pub fn observe_global<G: Global>(
3407        &mut self,
3408        f: impl Fn(&mut WindowContext<'_>) + 'static,
3409    ) -> Subscription {
3410        let window_handle = self.window.handle;
3411        let (subscription, activate) = self.global_observers.insert(
3412            TypeId::of::<G>(),
3413            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
3414        );
3415        self.app.defer(move |_| activate());
3416        subscription
3417    }
3418
3419    /// Focus the current window and bring it to the foreground at the platform level.
3420    pub fn activate_window(&self) {
3421        self.window.platform_window.activate();
3422    }
3423
3424    /// Minimize the current window at the platform level.
3425    pub fn minimize_window(&self) {
3426        self.window.platform_window.minimize();
3427    }
3428
3429    /// Toggle full screen status on the current window at the platform level.
3430    pub fn toggle_fullscreen(&self) {
3431        self.window.platform_window.toggle_fullscreen();
3432    }
3433
3434    /// Present a platform dialog.
3435    /// The provided message will be presented, along with buttons for each answer.
3436    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
3437    pub fn prompt(
3438        &mut self,
3439        level: PromptLevel,
3440        message: &str,
3441        detail: Option<&str>,
3442        answers: &[&str],
3443    ) -> oneshot::Receiver<usize> {
3444        let prompt_builder = self.app.prompt_builder.take();
3445        let Some(prompt_builder) = prompt_builder else {
3446            unreachable!("Re-entrant window prompting is not supported by GPUI");
3447        };
3448
3449        let receiver = match &prompt_builder {
3450            PromptBuilder::Default => self
3451                .window
3452                .platform_window
3453                .prompt(level, message, detail, answers)
3454                .unwrap_or_else(|| {
3455                    self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
3456                }),
3457            PromptBuilder::Custom(_) => {
3458                self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
3459            }
3460        };
3461
3462        self.app.prompt_builder = Some(prompt_builder);
3463
3464        receiver
3465    }
3466
3467    fn build_custom_prompt(
3468        &mut self,
3469        prompt_builder: &PromptBuilder,
3470        level: PromptLevel,
3471        message: &str,
3472        detail: Option<&str>,
3473        answers: &[&str],
3474    ) -> oneshot::Receiver<usize> {
3475        let (sender, receiver) = oneshot::channel();
3476        let handle = PromptHandle::new(sender);
3477        let handle = (prompt_builder)(level, message, detail, answers, handle, self);
3478        self.window.prompt = Some(handle);
3479        receiver
3480    }
3481
3482    /// Returns all available actions for the focused element.
3483    pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
3484        let node_id = self
3485            .window
3486            .focus
3487            .and_then(|focus_id| {
3488                self.window
3489                    .rendered_frame
3490                    .dispatch_tree
3491                    .focusable_node_id(focus_id)
3492            })
3493            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3494
3495        let mut actions = self
3496            .window
3497            .rendered_frame
3498            .dispatch_tree
3499            .available_actions(node_id);
3500        for action_type in self.global_action_listeners.keys() {
3501            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
3502                let action = self.actions.build_action_type(action_type).ok();
3503                if let Some(action) = action {
3504                    actions.insert(ix, action);
3505                }
3506            }
3507        }
3508        actions
3509    }
3510
3511    /// Returns key bindings that invoke the given action on the currently focused element.
3512    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
3513        self.window
3514            .rendered_frame
3515            .dispatch_tree
3516            .bindings_for_action(
3517                action,
3518                &self.window.rendered_frame.dispatch_tree.context_stack,
3519            )
3520    }
3521
3522    /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
3523    pub fn bindings_for_action_in(
3524        &self,
3525        action: &dyn Action,
3526        focus_handle: &FocusHandle,
3527    ) -> Vec<KeyBinding> {
3528        let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
3529
3530        let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
3531            return vec![];
3532        };
3533        let context_stack: Vec<_> = dispatch_tree
3534            .dispatch_path(node_id)
3535            .into_iter()
3536            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
3537            .collect();
3538        dispatch_tree.bindings_for_action(action, &context_stack)
3539    }
3540
3541    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
3542    pub fn listener_for<V: Render, E>(
3543        &self,
3544        view: &View<V>,
3545        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
3546    ) -> impl Fn(&E, &mut WindowContext) + 'static {
3547        let view = view.downgrade();
3548        move |e: &E, cx: &mut WindowContext| {
3549            view.update(cx, |view, cx| f(view, e, cx)).ok();
3550        }
3551    }
3552
3553    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
3554    pub fn handler_for<V: Render>(
3555        &self,
3556        view: &View<V>,
3557        f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
3558    ) -> impl Fn(&mut WindowContext) {
3559        let view = view.downgrade();
3560        move |cx: &mut WindowContext| {
3561            view.update(cx, |view, cx| f(view, cx)).ok();
3562        }
3563    }
3564
3565    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
3566    /// If the callback returns false, the window won't be closed.
3567    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
3568        let mut this = self.to_async();
3569        self.window
3570            .platform_window
3571            .on_should_close(Box::new(move || this.update(|cx| f(cx)).unwrap_or(true)))
3572    }
3573
3574    /// Register an action listener on the window for the next frame. The type of action
3575    /// is determined by the first parameter of the given listener. When the next frame is rendered
3576    /// the listener will be cleared.
3577    ///
3578    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
3579    /// a specific need to register a global listener.
3580    pub fn on_action(
3581        &mut self,
3582        action_type: TypeId,
3583        listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
3584    ) {
3585        self.window
3586            .next_frame
3587            .dispatch_tree
3588            .on_action(action_type, Rc::new(listener));
3589    }
3590}
3591
3592#[cfg(target_os = "windows")]
3593impl WindowContext<'_> {
3594    /// Returns the raw HWND handle for the window.
3595    pub fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND {
3596        self.window.platform_window.get_raw_handle()
3597    }
3598}
3599
3600impl Context for WindowContext<'_> {
3601    type Result<T> = T;
3602
3603    fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
3604    where
3605        T: 'static,
3606    {
3607        let slot = self.app.entities.reserve();
3608        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
3609        self.entities.insert(slot, model)
3610    }
3611
3612    fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
3613        self.app.reserve_model()
3614    }
3615
3616    fn insert_model<T: 'static>(
3617        &mut self,
3618        reservation: crate::Reservation<T>,
3619        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
3620    ) -> Self::Result<Model<T>> {
3621        self.app.insert_model(reservation, build_model)
3622    }
3623
3624    fn update_model<T: 'static, R>(
3625        &mut self,
3626        model: &Model<T>,
3627        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
3628    ) -> R {
3629        let mut entity = self.entities.lease(model);
3630        let result = update(
3631            &mut *entity,
3632            &mut ModelContext::new(&mut *self.app, model.downgrade()),
3633        );
3634        self.entities.end_lease(entity);
3635        result
3636    }
3637
3638    fn read_model<T, R>(
3639        &self,
3640        handle: &Model<T>,
3641        read: impl FnOnce(&T, &AppContext) -> R,
3642    ) -> Self::Result<R>
3643    where
3644        T: 'static,
3645    {
3646        let entity = self.entities.read(handle);
3647        read(entity, &*self.app)
3648    }
3649
3650    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
3651    where
3652        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
3653    {
3654        if window == self.window.handle {
3655            let root_view = self.window.root_view.clone().unwrap();
3656            Ok(update(root_view, self))
3657        } else {
3658            window.update(self.app, update)
3659        }
3660    }
3661
3662    fn read_window<T, R>(
3663        &self,
3664        window: &WindowHandle<T>,
3665        read: impl FnOnce(View<T>, &AppContext) -> R,
3666    ) -> Result<R>
3667    where
3668        T: 'static,
3669    {
3670        if window.any_handle == self.window.handle {
3671            let root_view = self
3672                .window
3673                .root_view
3674                .clone()
3675                .unwrap()
3676                .downcast::<T>()
3677                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3678            Ok(read(root_view, self))
3679        } else {
3680            self.app.read_window(window, read)
3681        }
3682    }
3683}
3684
3685impl VisualContext for WindowContext<'_> {
3686    fn new_view<V>(
3687        &mut self,
3688        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
3689    ) -> Self::Result<View<V>>
3690    where
3691        V: 'static + Render,
3692    {
3693        let slot = self.app.entities.reserve();
3694        let view = View {
3695            model: slot.clone(),
3696        };
3697        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
3698        let entity = build_view_state(&mut cx);
3699        cx.entities.insert(slot, entity);
3700
3701        // Non-generic part to avoid leaking SubscriberSet to invokers of `new_view`.
3702        fn notify_observers(cx: &mut WindowContext, tid: TypeId, view: AnyView) {
3703            cx.new_view_observers.clone().retain(&tid, |observer| {
3704                let any_view = view.clone();
3705                (observer)(any_view, cx);
3706                true
3707            });
3708        }
3709        notify_observers(self, TypeId::of::<V>(), AnyView::from(view.clone()));
3710
3711        view
3712    }
3713
3714    /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
3715    fn update_view<T: 'static, R>(
3716        &mut self,
3717        view: &View<T>,
3718        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
3719    ) -> Self::Result<R> {
3720        let mut lease = self.app.entities.lease(&view.model);
3721        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
3722        let result = update(&mut *lease, &mut cx);
3723        cx.app.entities.end_lease(lease);
3724        result
3725    }
3726
3727    fn replace_root_view<V>(
3728        &mut self,
3729        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
3730    ) -> Self::Result<View<V>>
3731    where
3732        V: 'static + Render,
3733    {
3734        let view = self.new_view(build_view);
3735        self.window.root_view = Some(view.clone().into());
3736        self.refresh();
3737        view
3738    }
3739
3740    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
3741        self.update_view(view, |view, cx| {
3742            view.focus_handle(cx).clone().focus(cx);
3743        })
3744    }
3745
3746    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
3747    where
3748        V: ManagedView,
3749    {
3750        self.update_view(view, |_, cx| cx.emit(DismissEvent))
3751    }
3752}
3753
3754impl<'a> std::ops::Deref for WindowContext<'a> {
3755    type Target = AppContext;
3756
3757    fn deref(&self) -> &Self::Target {
3758        self.app
3759    }
3760}
3761
3762impl<'a> std::ops::DerefMut for WindowContext<'a> {
3763    fn deref_mut(&mut self) -> &mut Self::Target {
3764        self.app
3765    }
3766}
3767
3768impl<'a> Borrow<AppContext> for WindowContext<'a> {
3769    fn borrow(&self) -> &AppContext {
3770        self.app
3771    }
3772}
3773
3774impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
3775    fn borrow_mut(&mut self) -> &mut AppContext {
3776        self.app
3777    }
3778}
3779
3780/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
3781pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
3782    #[doc(hidden)]
3783    fn app_mut(&mut self) -> &mut AppContext {
3784        self.borrow_mut()
3785    }
3786
3787    #[doc(hidden)]
3788    fn app(&self) -> &AppContext {
3789        self.borrow()
3790    }
3791
3792    #[doc(hidden)]
3793    fn window(&self) -> &Window {
3794        self.borrow()
3795    }
3796
3797    #[doc(hidden)]
3798    fn window_mut(&mut self) -> &mut Window {
3799        self.borrow_mut()
3800    }
3801}
3802
3803impl Borrow<Window> for WindowContext<'_> {
3804    fn borrow(&self) -> &Window {
3805        self.window
3806    }
3807}
3808
3809impl BorrowMut<Window> for WindowContext<'_> {
3810    fn borrow_mut(&mut self) -> &mut Window {
3811        self.window
3812    }
3813}
3814
3815impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
3816
3817/// Provides access to application state that is specialized for a particular [`View`].
3818/// Allows you to interact with focus, emit events, etc.
3819/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
3820/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
3821pub struct ViewContext<'a, V> {
3822    window_cx: WindowContext<'a>,
3823    view: &'a View<V>,
3824}
3825
3826impl<V> Borrow<AppContext> for ViewContext<'_, V> {
3827    fn borrow(&self) -> &AppContext {
3828        &*self.window_cx.app
3829    }
3830}
3831
3832impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
3833    fn borrow_mut(&mut self) -> &mut AppContext {
3834        &mut *self.window_cx.app
3835    }
3836}
3837
3838impl<V> Borrow<Window> for ViewContext<'_, V> {
3839    fn borrow(&self) -> &Window {
3840        &*self.window_cx.window
3841    }
3842}
3843
3844impl<V> BorrowMut<Window> for ViewContext<'_, V> {
3845    fn borrow_mut(&mut self) -> &mut Window {
3846        &mut *self.window_cx.window
3847    }
3848}
3849
3850impl<'a, V: 'static> ViewContext<'a, V> {
3851    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
3852        Self {
3853            window_cx: WindowContext::new(app, window),
3854            view,
3855        }
3856    }
3857
3858    /// Get the entity_id of this view.
3859    pub fn entity_id(&self) -> EntityId {
3860        self.view.entity_id()
3861    }
3862
3863    /// Get the view pointer underlying this context.
3864    pub fn view(&self) -> &View<V> {
3865        self.view
3866    }
3867
3868    /// Get the model underlying this view.
3869    pub fn model(&self) -> &Model<V> {
3870        &self.view.model
3871    }
3872
3873    /// Access the underlying window context.
3874    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
3875        &mut self.window_cx
3876    }
3877
3878    /// Sets a given callback to be run on the next frame.
3879    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
3880    where
3881        V: 'static,
3882    {
3883        let view = self.view().clone();
3884        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
3885    }
3886
3887    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
3888    /// that are currently on the stack to be returned to the app.
3889    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
3890        let view = self.view().downgrade();
3891        self.window_cx.defer(move |cx| {
3892            view.update(cx, f).ok();
3893        });
3894    }
3895
3896    /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
3897    pub fn observe<V2, E>(
3898        &mut self,
3899        entity: &E,
3900        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
3901    ) -> Subscription
3902    where
3903        V2: 'static,
3904        V: 'static,
3905        E: Entity<V2>,
3906    {
3907        let view = self.view().downgrade();
3908        let entity_id = entity.entity_id();
3909        let entity = entity.downgrade();
3910        let window_handle = self.window.handle;
3911        self.app.new_observer(
3912            entity_id,
3913            Box::new(move |cx| {
3914                window_handle
3915                    .update(cx, |_, cx| {
3916                        if let Some(handle) = E::upgrade_from(&entity) {
3917                            view.update(cx, |this, cx| on_notify(this, handle, cx))
3918                                .is_ok()
3919                        } else {
3920                            false
3921                        }
3922                    })
3923                    .unwrap_or(false)
3924            }),
3925        )
3926    }
3927
3928    /// Subscribe to events emitted by another model or view.
3929    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
3930    /// 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.
3931    pub fn subscribe<V2, E, Evt>(
3932        &mut self,
3933        entity: &E,
3934        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
3935    ) -> Subscription
3936    where
3937        V2: EventEmitter<Evt>,
3938        E: Entity<V2>,
3939        Evt: 'static,
3940    {
3941        let view = self.view().downgrade();
3942        let entity_id = entity.entity_id();
3943        let handle = entity.downgrade();
3944        let window_handle = self.window.handle;
3945        self.app.new_subscription(
3946            entity_id,
3947            (
3948                TypeId::of::<Evt>(),
3949                Box::new(move |event, cx| {
3950                    window_handle
3951                        .update(cx, |_, cx| {
3952                            if let Some(handle) = E::upgrade_from(&handle) {
3953                                let event = event.downcast_ref().expect("invalid event type");
3954                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
3955                                    .is_ok()
3956                            } else {
3957                                false
3958                            }
3959                        })
3960                        .unwrap_or(false)
3961                }),
3962            ),
3963        )
3964    }
3965
3966    /// Register a callback to be invoked when the view is released.
3967    ///
3968    /// The callback receives a handle to the view's window. This handle may be
3969    /// invalid, if the window was closed before the view was released.
3970    pub fn on_release(
3971        &mut self,
3972        on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
3973    ) -> Subscription {
3974        let window_handle = self.window.handle;
3975        let (subscription, activate) = self.app.release_listeners.insert(
3976            self.view.model.entity_id,
3977            Box::new(move |this, cx| {
3978                let this = this.downcast_mut().expect("invalid entity type");
3979                on_release(this, window_handle, cx)
3980            }),
3981        );
3982        activate();
3983        subscription
3984    }
3985
3986    /// Register a callback to be invoked when the given Model or View is released.
3987    pub fn observe_release<V2, E>(
3988        &mut self,
3989        entity: &E,
3990        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
3991    ) -> Subscription
3992    where
3993        V: 'static,
3994        V2: 'static,
3995        E: Entity<V2>,
3996    {
3997        let view = self.view().downgrade();
3998        let entity_id = entity.entity_id();
3999        let window_handle = self.window.handle;
4000        let (subscription, activate) = self.app.release_listeners.insert(
4001            entity_id,
4002            Box::new(move |entity, cx| {
4003                let entity = entity.downcast_mut().expect("invalid entity type");
4004                let _ = window_handle.update(cx, |_, cx| {
4005                    view.update(cx, |this, cx| on_release(this, entity, cx))
4006                });
4007            }),
4008        );
4009        activate();
4010        subscription
4011    }
4012
4013    /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
4014    /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
4015    pub fn notify(&mut self) {
4016        self.window_cx.notify(self.view.entity_id());
4017    }
4018
4019    /// Register a callback to be invoked when the window is resized.
4020    pub fn observe_window_bounds(
4021        &mut self,
4022        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4023    ) -> Subscription {
4024        let view = self.view.downgrade();
4025        let (subscription, activate) = self.window.bounds_observers.insert(
4026            (),
4027            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4028        );
4029        activate();
4030        subscription
4031    }
4032
4033    /// Register a callback to be invoked when the window is activated or deactivated.
4034    pub fn observe_window_activation(
4035        &mut self,
4036        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4037    ) -> Subscription {
4038        let view = self.view.downgrade();
4039        let (subscription, activate) = self.window.activation_observers.insert(
4040            (),
4041            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4042        );
4043        activate();
4044        subscription
4045    }
4046
4047    /// Registers a callback to be invoked when the window appearance changes.
4048    pub fn observe_window_appearance(
4049        &mut self,
4050        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4051    ) -> Subscription {
4052        let view = self.view.downgrade();
4053        let (subscription, activate) = self.window.appearance_observers.insert(
4054            (),
4055            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4056        );
4057        activate();
4058        subscription
4059    }
4060
4061    /// Register a callback to be invoked when the window's pending input changes.
4062    pub fn observe_pending_input(
4063        &mut self,
4064        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4065    ) -> Subscription {
4066        let view = self.view.downgrade();
4067        let (subscription, activate) = self.window.pending_input_observers.insert(
4068            (),
4069            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4070        );
4071        activate();
4072        subscription
4073    }
4074
4075    /// Register a listener to be called when the given focus handle receives focus.
4076    /// Returns a subscription and persists until the subscription is dropped.
4077    pub fn on_focus(
4078        &mut self,
4079        handle: &FocusHandle,
4080        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4081    ) -> Subscription {
4082        let view = self.view.downgrade();
4083        let focus_id = handle.id;
4084        let (subscription, activate) =
4085            self.window.new_focus_listener(Box::new(move |event, cx| {
4086                view.update(cx, |view, cx| {
4087                    if event.previous_focus_path.last() != Some(&focus_id)
4088                        && event.current_focus_path.last() == Some(&focus_id)
4089                    {
4090                        listener(view, cx)
4091                    }
4092                })
4093                .is_ok()
4094            }));
4095        self.app.defer(|_| activate());
4096        subscription
4097    }
4098
4099    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
4100    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
4101    /// Returns a subscription and persists until the subscription is dropped.
4102    pub fn on_focus_in(
4103        &mut self,
4104        handle: &FocusHandle,
4105        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4106    ) -> Subscription {
4107        let view = self.view.downgrade();
4108        let focus_id = handle.id;
4109        let (subscription, activate) =
4110            self.window.new_focus_listener(Box::new(move |event, cx| {
4111                view.update(cx, |view, cx| {
4112                    if !event.previous_focus_path.contains(&focus_id)
4113                        && event.current_focus_path.contains(&focus_id)
4114                    {
4115                        listener(view, cx)
4116                    }
4117                })
4118                .is_ok()
4119            }));
4120        self.app.defer(move |_| activate());
4121        subscription
4122    }
4123
4124    /// Register a listener to be called when the given focus handle loses focus.
4125    /// Returns a subscription and persists until the subscription is dropped.
4126    pub fn on_blur(
4127        &mut self,
4128        handle: &FocusHandle,
4129        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4130    ) -> Subscription {
4131        let view = self.view.downgrade();
4132        let focus_id = handle.id;
4133        let (subscription, activate) =
4134            self.window.new_focus_listener(Box::new(move |event, cx| {
4135                view.update(cx, |view, cx| {
4136                    if event.previous_focus_path.last() == Some(&focus_id)
4137                        && event.current_focus_path.last() != Some(&focus_id)
4138                    {
4139                        listener(view, cx)
4140                    }
4141                })
4142                .is_ok()
4143            }));
4144        self.app.defer(move |_| activate());
4145        subscription
4146    }
4147
4148    /// Register a listener to be called when nothing in the window has focus.
4149    /// This typically happens when the node that was focused is removed from the tree,
4150    /// and this callback lets you chose a default place to restore the users focus.
4151    /// Returns a subscription and persists until the subscription is dropped.
4152    pub fn on_focus_lost(
4153        &mut self,
4154        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4155    ) -> Subscription {
4156        let view = self.view.downgrade();
4157        let (subscription, activate) = self.window.focus_lost_listeners.insert(
4158            (),
4159            Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
4160        );
4161        activate();
4162        subscription
4163    }
4164
4165    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
4166    /// Returns a subscription and persists until the subscription is dropped.
4167    pub fn on_focus_out(
4168        &mut self,
4169        handle: &FocusHandle,
4170        mut listener: impl FnMut(&mut V, FocusOutEvent, &mut ViewContext<V>) + 'static,
4171    ) -> Subscription {
4172        let view = self.view.downgrade();
4173        let focus_id = handle.id;
4174        let (subscription, activate) =
4175            self.window.new_focus_listener(Box::new(move |event, cx| {
4176                view.update(cx, |view, cx| {
4177                    if let Some(blurred_id) = event.previous_focus_path.last().copied() {
4178                        if event.previous_focus_path.contains(&focus_id)
4179                            && !event.current_focus_path.contains(&focus_id)
4180                        {
4181                            let event = FocusOutEvent {
4182                                blurred: WeakFocusHandle {
4183                                    id: blurred_id,
4184                                    handles: Arc::downgrade(&cx.window.focus_handles),
4185                                },
4186                            };
4187                            listener(view, event, cx)
4188                        }
4189                    }
4190                })
4191                .is_ok()
4192            }));
4193        self.app.defer(move |_| activate());
4194        subscription
4195    }
4196
4197    /// Schedule a future to be run asynchronously.
4198    /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
4199    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
4200    /// The returned future will be polled on the main thread.
4201    pub fn spawn<Fut, R>(
4202        &mut self,
4203        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
4204    ) -> Task<R>
4205    where
4206        R: 'static,
4207        Fut: Future<Output = R> + 'static,
4208    {
4209        let view = self.view().downgrade();
4210        self.window_cx.spawn(|cx| f(view, cx))
4211    }
4212
4213    /// Register a callback to be invoked when the given global state changes.
4214    pub fn observe_global<G: Global>(
4215        &mut self,
4216        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
4217    ) -> Subscription {
4218        let window_handle = self.window.handle;
4219        let view = self.view().downgrade();
4220        let (subscription, activate) = self.global_observers.insert(
4221            TypeId::of::<G>(),
4222            Box::new(move |cx| {
4223                window_handle
4224                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
4225                    .unwrap_or(false)
4226            }),
4227        );
4228        self.app.defer(move |_| activate());
4229        subscription
4230    }
4231
4232    /// Register a callback to be invoked when the given Action type is dispatched to the window.
4233    pub fn on_action(
4234        &mut self,
4235        action_type: TypeId,
4236        listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
4237    ) {
4238        let handle = self.view().clone();
4239        self.window_cx
4240            .on_action(action_type, move |action, phase, cx| {
4241                handle.update(cx, |view, cx| {
4242                    listener(view, action, phase, cx);
4243                })
4244            });
4245    }
4246
4247    /// Emit an event to be handled by any other views that have subscribed via [ViewContext::subscribe].
4248    pub fn emit<Evt>(&mut self, event: Evt)
4249    where
4250        Evt: 'static,
4251        V: EventEmitter<Evt>,
4252    {
4253        let emitter = self.view.model.entity_id;
4254        self.app.push_effect(Effect::Emit {
4255            emitter,
4256            event_type: TypeId::of::<Evt>(),
4257            event: Box::new(event),
4258        });
4259    }
4260
4261    /// Move focus to the current view, assuming it implements [`FocusableView`].
4262    pub fn focus_self(&mut self)
4263    where
4264        V: FocusableView,
4265    {
4266        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
4267    }
4268
4269    /// Convenience method for accessing view state in an event callback.
4270    ///
4271    /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
4272    /// but it's often useful to be able to access view state in these
4273    /// callbacks. This method provides a convenient way to do so.
4274    pub fn listener<E>(
4275        &self,
4276        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
4277    ) -> impl Fn(&E, &mut WindowContext) + 'static {
4278        let view = self.view().downgrade();
4279        move |e: &E, cx: &mut WindowContext| {
4280            view.update(cx, |view, cx| f(view, e, cx)).ok();
4281        }
4282    }
4283}
4284
4285impl<V> Context for ViewContext<'_, V> {
4286    type Result<U> = U;
4287
4288    fn new_model<T: 'static>(
4289        &mut self,
4290        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
4291    ) -> Model<T> {
4292        self.window_cx.new_model(build_model)
4293    }
4294
4295    fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
4296        self.window_cx.reserve_model()
4297    }
4298
4299    fn insert_model<T: 'static>(
4300        &mut self,
4301        reservation: crate::Reservation<T>,
4302        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
4303    ) -> Self::Result<Model<T>> {
4304        self.window_cx.insert_model(reservation, build_model)
4305    }
4306
4307    fn update_model<T: 'static, R>(
4308        &mut self,
4309        model: &Model<T>,
4310        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
4311    ) -> R {
4312        self.window_cx.update_model(model, update)
4313    }
4314
4315    fn read_model<T, R>(
4316        &self,
4317        handle: &Model<T>,
4318        read: impl FnOnce(&T, &AppContext) -> R,
4319    ) -> Self::Result<R>
4320    where
4321        T: 'static,
4322    {
4323        self.window_cx.read_model(handle, read)
4324    }
4325
4326    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
4327    where
4328        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
4329    {
4330        self.window_cx.update_window(window, update)
4331    }
4332
4333    fn read_window<T, R>(
4334        &self,
4335        window: &WindowHandle<T>,
4336        read: impl FnOnce(View<T>, &AppContext) -> R,
4337    ) -> Result<R>
4338    where
4339        T: 'static,
4340    {
4341        self.window_cx.read_window(window, read)
4342    }
4343}
4344
4345impl<V: 'static> VisualContext for ViewContext<'_, V> {
4346    fn new_view<W: Render + 'static>(
4347        &mut self,
4348        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
4349    ) -> Self::Result<View<W>> {
4350        self.window_cx.new_view(build_view_state)
4351    }
4352
4353    fn update_view<V2: 'static, R>(
4354        &mut self,
4355        view: &View<V2>,
4356        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
4357    ) -> Self::Result<R> {
4358        self.window_cx.update_view(view, update)
4359    }
4360
4361    fn replace_root_view<W>(
4362        &mut self,
4363        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
4364    ) -> Self::Result<View<W>>
4365    where
4366        W: 'static + Render,
4367    {
4368        self.window_cx.replace_root_view(build_view)
4369    }
4370
4371    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
4372        self.window_cx.focus_view(view)
4373    }
4374
4375    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
4376        self.window_cx.dismiss_view(view)
4377    }
4378}
4379
4380impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
4381    type Target = WindowContext<'a>;
4382
4383    fn deref(&self) -> &Self::Target {
4384        &self.window_cx
4385    }
4386}
4387
4388impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
4389    fn deref_mut(&mut self) -> &mut Self::Target {
4390        &mut self.window_cx
4391    }
4392}
4393
4394// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
4395slotmap::new_key_type! {
4396    /// A unique identifier for a window.
4397    pub struct WindowId;
4398}
4399
4400impl WindowId {
4401    /// Converts this window ID to a `u64`.
4402    pub fn as_u64(&self) -> u64 {
4403        self.0.as_ffi()
4404    }
4405}
4406
4407/// A handle to a window with a specific root view type.
4408/// Note that this does not keep the window alive on its own.
4409#[derive(Deref, DerefMut)]
4410pub struct WindowHandle<V> {
4411    #[deref]
4412    #[deref_mut]
4413    pub(crate) any_handle: AnyWindowHandle,
4414    state_type: PhantomData<V>,
4415}
4416
4417impl<V: 'static + Render> WindowHandle<V> {
4418    /// Creates a new handle from a window ID.
4419    /// This does not check if the root type of the window is `V`.
4420    pub fn new(id: WindowId) -> Self {
4421        WindowHandle {
4422            any_handle: AnyWindowHandle {
4423                id,
4424                state_type: TypeId::of::<V>(),
4425            },
4426            state_type: PhantomData,
4427        }
4428    }
4429
4430    /// Get the root view out of this window.
4431    ///
4432    /// This will fail if the window is closed or if the root view's type does not match `V`.
4433    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
4434    where
4435        C: Context,
4436    {
4437        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
4438            root_view
4439                .downcast::<V>()
4440                .map_err(|_| anyhow!("the type of the window's root view has changed"))
4441        }))
4442    }
4443
4444    /// Updates the root view of this window.
4445    ///
4446    /// This will fail if the window has been closed or if the root view's type does not match
4447    pub fn update<C, R>(
4448        &self,
4449        cx: &mut C,
4450        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
4451    ) -> Result<R>
4452    where
4453        C: Context,
4454    {
4455        cx.update_window(self.any_handle, |root_view, cx| {
4456            let view = root_view
4457                .downcast::<V>()
4458                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4459            Ok(cx.update_view(&view, update))
4460        })?
4461    }
4462
4463    /// Read the root view out of this window.
4464    ///
4465    /// This will fail if the window is closed or if the root view's type does not match `V`.
4466    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
4467        let x = cx
4468            .windows
4469            .get(self.id)
4470            .and_then(|window| {
4471                window
4472                    .as_ref()
4473                    .and_then(|window| window.root_view.clone())
4474                    .map(|root_view| root_view.downcast::<V>())
4475            })
4476            .ok_or_else(|| anyhow!("window not found"))?
4477            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4478
4479        Ok(x.read(cx))
4480    }
4481
4482    /// Read the root view out of this window, with a callback
4483    ///
4484    /// This will fail if the window is closed or if the root view's type does not match `V`.
4485    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
4486    where
4487        C: Context,
4488    {
4489        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
4490    }
4491
4492    /// Read the root view pointer off of this window.
4493    ///
4494    /// This will fail if the window is closed or if the root view's type does not match `V`.
4495    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
4496    where
4497        C: Context,
4498    {
4499        cx.read_window(self, |root_view, _cx| root_view.clone())
4500    }
4501
4502    /// Check if this window is 'active'.
4503    ///
4504    /// Will return `None` if the window is closed or currently
4505    /// borrowed.
4506    pub fn is_active(&self, cx: &mut AppContext) -> Option<bool> {
4507        cx.update_window(self.any_handle, |_, cx| cx.is_window_active())
4508            .ok()
4509    }
4510}
4511
4512impl<V> Copy for WindowHandle<V> {}
4513
4514impl<V> Clone for WindowHandle<V> {
4515    fn clone(&self) -> Self {
4516        *self
4517    }
4518}
4519
4520impl<V> PartialEq for WindowHandle<V> {
4521    fn eq(&self, other: &Self) -> bool {
4522        self.any_handle == other.any_handle
4523    }
4524}
4525
4526impl<V> Eq for WindowHandle<V> {}
4527
4528impl<V> Hash for WindowHandle<V> {
4529    fn hash<H: Hasher>(&self, state: &mut H) {
4530        self.any_handle.hash(state);
4531    }
4532}
4533
4534impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
4535    fn from(val: WindowHandle<V>) -> Self {
4536        val.any_handle
4537    }
4538}
4539
4540unsafe impl<V> Send for WindowHandle<V> {}
4541unsafe impl<V> Sync for WindowHandle<V> {}
4542
4543/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
4544#[derive(Copy, Clone, PartialEq, Eq, Hash)]
4545pub struct AnyWindowHandle {
4546    pub(crate) id: WindowId,
4547    state_type: TypeId,
4548}
4549
4550impl AnyWindowHandle {
4551    /// Get the ID of this window.
4552    pub fn window_id(&self) -> WindowId {
4553        self.id
4554    }
4555
4556    /// Attempt to convert this handle to a window handle with a specific root view type.
4557    /// If the types do not match, this will return `None`.
4558    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
4559        if TypeId::of::<T>() == self.state_type {
4560            Some(WindowHandle {
4561                any_handle: *self,
4562                state_type: PhantomData,
4563            })
4564        } else {
4565            None
4566        }
4567    }
4568
4569    /// Updates the state of the root view of this window.
4570    ///
4571    /// This will fail if the window has been closed.
4572    pub fn update<C, R>(
4573        self,
4574        cx: &mut C,
4575        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
4576    ) -> Result<R>
4577    where
4578        C: Context,
4579    {
4580        cx.update_window(self, update)
4581    }
4582
4583    /// Read the state of the root view of this window.
4584    ///
4585    /// This will fail if the window has been closed.
4586    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
4587    where
4588        C: Context,
4589        T: 'static,
4590    {
4591        let view = self
4592            .downcast::<T>()
4593            .context("the type of the window's root view has changed")?;
4594
4595        cx.read_window(&view, read)
4596    }
4597}
4598
4599/// An identifier for an [`Element`](crate::Element).
4600///
4601/// Can be constructed with a string, a number, or both, as well
4602/// as other internal representations.
4603#[derive(Clone, Debug, Eq, PartialEq, Hash)]
4604pub enum ElementId {
4605    /// The ID of a View element
4606    View(EntityId),
4607    /// An integer ID.
4608    Integer(usize),
4609    /// A string based ID.
4610    Name(SharedString),
4611    /// A UUID.
4612    Uuid(Uuid),
4613    /// An ID that's equated with a focus handle.
4614    FocusHandle(FocusId),
4615    /// A combination of a name and an integer.
4616    NamedInteger(SharedString, usize),
4617}
4618
4619impl Display for ElementId {
4620    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4621        match self {
4622            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
4623            ElementId::Integer(ix) => write!(f, "{}", ix)?,
4624            ElementId::Name(name) => write!(f, "{}", name)?,
4625            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
4626            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
4627            ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
4628        }
4629
4630        Ok(())
4631    }
4632}
4633
4634impl TryInto<SharedString> for ElementId {
4635    type Error = anyhow::Error;
4636
4637    fn try_into(self) -> anyhow::Result<SharedString> {
4638        if let ElementId::Name(name) = self {
4639            Ok(name)
4640        } else {
4641            Err(anyhow!("element id is not string"))
4642        }
4643    }
4644}
4645
4646impl From<usize> for ElementId {
4647    fn from(id: usize) -> Self {
4648        ElementId::Integer(id)
4649    }
4650}
4651
4652impl From<i32> for ElementId {
4653    fn from(id: i32) -> Self {
4654        Self::Integer(id as usize)
4655    }
4656}
4657
4658impl From<SharedString> for ElementId {
4659    fn from(name: SharedString) -> Self {
4660        ElementId::Name(name)
4661    }
4662}
4663
4664impl From<&'static str> for ElementId {
4665    fn from(name: &'static str) -> Self {
4666        ElementId::Name(name.into())
4667    }
4668}
4669
4670impl<'a> From<&'a FocusHandle> for ElementId {
4671    fn from(handle: &'a FocusHandle) -> Self {
4672        ElementId::FocusHandle(handle.id)
4673    }
4674}
4675
4676impl From<(&'static str, EntityId)> for ElementId {
4677    fn from((name, id): (&'static str, EntityId)) -> Self {
4678        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
4679    }
4680}
4681
4682impl From<(&'static str, usize)> for ElementId {
4683    fn from((name, id): (&'static str, usize)) -> Self {
4684        ElementId::NamedInteger(name.into(), id)
4685    }
4686}
4687
4688impl From<(&'static str, u64)> for ElementId {
4689    fn from((name, id): (&'static str, u64)) -> Self {
4690        ElementId::NamedInteger(name.into(), id as usize)
4691    }
4692}
4693
4694impl From<Uuid> for ElementId {
4695    fn from(value: Uuid) -> Self {
4696        Self::Uuid(value)
4697    }
4698}
4699
4700impl From<(&'static str, u32)> for ElementId {
4701    fn from((name, id): (&'static str, u32)) -> Self {
4702        ElementId::NamedInteger(name.into(), id as usize)
4703    }
4704}
4705
4706/// A rectangle to be rendered in the window at the given position and size.
4707/// Passed as an argument [`WindowContext::paint_quad`].
4708#[derive(Clone)]
4709pub struct PaintQuad {
4710    /// The bounds of the quad within the window.
4711    pub bounds: Bounds<Pixels>,
4712    /// The radii of the quad's corners.
4713    pub corner_radii: Corners<Pixels>,
4714    /// The background color of the quad.
4715    pub background: Hsla,
4716    /// The widths of the quad's borders.
4717    pub border_widths: Edges<Pixels>,
4718    /// The color of the quad's borders.
4719    pub border_color: Hsla,
4720}
4721
4722impl PaintQuad {
4723    /// Sets the corner radii of the quad.
4724    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
4725        PaintQuad {
4726            corner_radii: corner_radii.into(),
4727            ..self
4728        }
4729    }
4730
4731    /// Sets the border widths of the quad.
4732    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
4733        PaintQuad {
4734            border_widths: border_widths.into(),
4735            ..self
4736        }
4737    }
4738
4739    /// Sets the border color of the quad.
4740    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
4741        PaintQuad {
4742            border_color: border_color.into(),
4743            ..self
4744        }
4745    }
4746
4747    /// Sets the background color of the quad.
4748    pub fn background(self, background: impl Into<Hsla>) -> Self {
4749        PaintQuad {
4750            background: background.into(),
4751            ..self
4752        }
4753    }
4754}
4755
4756/// Creates a quad with the given parameters.
4757pub fn quad(
4758    bounds: Bounds<Pixels>,
4759    corner_radii: impl Into<Corners<Pixels>>,
4760    background: impl Into<Hsla>,
4761    border_widths: impl Into<Edges<Pixels>>,
4762    border_color: impl Into<Hsla>,
4763) -> PaintQuad {
4764    PaintQuad {
4765        bounds,
4766        corner_radii: corner_radii.into(),
4767        background: background.into(),
4768        border_widths: border_widths.into(),
4769        border_color: border_color.into(),
4770    }
4771}
4772
4773/// Creates a filled quad with the given bounds and background color.
4774pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
4775    PaintQuad {
4776        bounds: bounds.into(),
4777        corner_radii: (0.).into(),
4778        background: background.into(),
4779        border_widths: (0.).into(),
4780        border_color: transparent_black(),
4781    }
4782}
4783
4784/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
4785pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
4786    PaintQuad {
4787        bounds: bounds.into(),
4788        corner_radii: (0.).into(),
4789        background: transparent_black(),
4790        border_widths: (1.).into(),
4791        border_color: border_color.into(),
4792    }
4793}