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