window.rs

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