window.rs

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