window.rs

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