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