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