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