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