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