window.rs

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