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